Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 11 additions & 5 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,21 @@ on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
python: ["3.12", "3.13"]
steps:
- uses: actions/checkout@v4
- uses: astral-sh/setup-uv@v5
with:
version: "0.12.22"
- uses: actions/setup-python@v5
with:
python-version: "3.12"
- run: uv sync --extra dev
- run: uv run ruff check src tests
- run: uv run mypy
- run: uv run pytest -q
python-version: ${{ matrix.python }}
- run: uv sync --frozen --extra dev --python ${{ matrix.python }}
- run: uv run --frozen ruff check src tests
- run: uv run --frozen mypy
- run: uv run --frozen pytest -q
- name: Demo
run: uv run --frozen bash examples/demo.sh
30 changes: 30 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,36 @@ All notable changes to ShadowGate are recorded here. The format follows
[Semantic Versioning](https://semver.org/). The version is defined once, in
`src/shadowgate/version.py`.

## [Unreleased]

### Added
- Audit head anchor (`<log>.head`): `GET /audit?verify=true` now detects removed or rewritten
newest entries and returns a `verification` object (entries, how many verified, anchored
count, error). Tampering found while writing is recorded as `audit_anchor_mismatch` and
the old anchor is kept.

- Built-in HTTPS: `shadowgate tls init` (private CA + server certificate),
`shadowgate server --tls-cert/--tls-key`, and `agent enroll --ca-file`, which pins the
CA in the agent's credential file.

- `examples/demo.sh`: one-command end-to-end demo (HTTPS, three agents, a runbook run,
audit verification and a tamper check). CI runs it, on Python 3.12 and 3.13.

### Changed
- The server refuses a non-loopback bind without TLS (`--allow-plaintext` overrides), and
agents refuse plain HTTP to non-loopback hosts. An agent stops (exit 2) when the server
certificate fails verification instead of retrying forever.
- Audit appends are O(1) instead of re-reading the whole log.

### Fixed
- Each request is now one database transaction. A failure part-way (audit write, run
engine, enqueue) rolls everything back: no job stuck `running` after a failed claim, no
enrollment whose credential nobody received, and a retried result after a server error
is recorded and advances the run instead of returning `duplicate`.
- Audit entries are written just before the database commits and dropped on rollback.
- A `.env` file may hold other programs' variables; only unknown `SHADOWGATE_*` keys are
rejected, and `shadowgate server` reports them without a traceback.

## [0.1.0] - 2026-11-30

First pre-release. Suitable for loopback evaluation with several agents on one host;
Expand Down
82 changes: 59 additions & 23 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
# ShadowGate

[![CI](https://github.com/5aranx/ShadowGate/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/5aranx/ShadowGate/actions/workflows/ci.yml)
[![Release](https://img.shields.io/github/v/tag/5aranx/ShadowGate?label=release)](https://github.com/5aranx/ShadowGate/releases/tag/v0.1.0)
[![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
![Python 3.12 | 3.13](https://img.shields.io/badge/python-3.12%20%7C%203.13-blue.svg)

ShadowGate is a control server for running audited jobs on Linux hosts you own and
administer. Operators enroll agents, queue actions or runbooks (dependency graphs of
actions) against them, and review the results on an audit log and a read-only dashboard.
Expand All @@ -8,8 +13,9 @@ actions) against them, and review the results on an audit log and a read-only da
> covert-channel, exfiltration, or evasion code anywhere in the tree.

**Status: pre-release (0.1.0).**
- The control server works for loopback evaluation with several agents and is covered by
tests, including concurrent-load tests. Run a single server process.
- The control server works with several agents, locally or across a network over its
built-in HTTPS (`shadowgate tls init`), and is covered by tests including concurrent
load and HTTPS end-to-end runs. Run a single server process.
- `shadowgate server`, `shadowgate agent enroll` and `shadowgate agent run` work end to end
(covered by a test that runs a real server and agent).
- Several known defects remain. See [Known limitations](#known-limitations) before using it
Expand All @@ -24,7 +30,7 @@ actions) against them, and review the results on an audit log and a read-only da
| **Job ownership** | An agent can claim and complete only jobs assigned to its own id. A retried identical result is acknowledged as `duplicate`; a conflicting one is rejected. |
| **Job queue** | SQLite (WAL mode). Each job is claimed with a single `UPDATE … RETURNING`. |
| **Runbooks** | Sets of steps with dependencies, registered under a name (`unnamed` if omitted). Validation rejects cycles. Steps fan out to agents by tag, with a per-run concurrency cap and compensating steps on failure. |
| **Audit log** | An append-only JSONL file. Each entry includes the SHA-256 of the previous one, so `GET /audit?verify=true` detects in-place edits. |
| **Audit log** | An append-only JSONL file. Each entry includes the SHA-256 of the previous one, and a sidecar `audit.log.head` anchors the newest entry, so `GET /audit?verify=true` detects edited, reordered, removed or rewritten entries and says where. |
| **Dashboard** | Server-rendered read-only pages at `/ui` (agents, job counts, runs). |
| **Builtin actions** | `system_info`, `disk_health`, `file_fetch` (returns a byte count and a truncation flag, never file contents), `service_status` (`systemctl is-active`). |

Expand All @@ -35,9 +41,10 @@ actions) against them, and review the results on an audit log and a read-only da
## Architecture

```
operator (curl / browser) agent (Python library)
operator (curl / browser) agent (`shadowgate agent run`)
│ Authorization: Bearer <token> │ X-ShadowGate-Agent-Token
│ or Basic (token as password) │ (plain HTTP; TLS not provided)
│ or Basic (token as password) │ HTTPS, server CA pinned at enrollment
│ │ (plain HTTP only to loopback)
▼ ▼
FastAPI app (server/app.py, built by create_app factory)
├── Store (server/store.py) SQLite WAL: agents, enroll_tokens
Expand All @@ -58,7 +65,7 @@ See [`docs/architecture.md`](docs/architecture.md) and
| `src/shadowgate/server/` | app, store, queue, runs, orchestrator, audit |
| `src/shadowgate/agent/` | executor, polling client (`Poller`), credential file (`config.py`) |
| `src/shadowgate/plugins/` | `Action` protocol, registry, loader, gate, builtins |
| `src/shadowgate/crypto/` | ed25519 manifest signing; mTLS CA helpers (unused) |
| `src/shadowgate/crypto/` | TLS CA and server certificates (`tls.py`); ed25519 manifest signing; mTLS helpers (unused) |
| `src/shadowgate/cli/` | `shadowgate` command: `server`, `agent enroll`, `agent run`, `plugin list` |
| `src/shadowgate/web/templates/` | dashboard templates |
| `docs/` | architecture, threat model |
Expand Down Expand Up @@ -93,8 +100,8 @@ uv sync --frozen --extra dev # creates .venv from uv.lock

Settings are read from environment variables with the `SHADOWGATE_` prefix, or from a
`.env` file in the working directory. Environment variables take precedence over `.env`.
A `.env` file may contain **only** ShadowGate settings: any other key, even one without
the prefix, makes startup fail with a validation error.
A `.env` file may also hold other programs' variables; they are ignored. An unknown
`SHADOWGATE_*` key (usually a typo) is rejected: `shadowgate server` names it and exits 2.

| Variable | Default | Used for |
|---|---|---|
Expand All @@ -104,16 +111,28 @@ the prefix, makes startup fail with a validation error.
| `SHADOWGATE_AUDIT_LOG_PATH` | `.shadowgate/audit.log` | Audit log file. Relative to the working directory. |
| `SHADOWGATE_DATA_DIR` | `.shadowgate` | Directory created at startup. It does **not** relocate the database or audit log. |
| `SHADOWGATE_RATE_LIMIT_PER_MINUTE` | `60` | Per-source-IP, per-endpoint limit on `POST /tokens` and `POST /enroll`. Must be ≥ 1: `0` or a negative value rejects every request. Behind a reverse proxy, all clients share the proxy's IP. |
| `SHADOWGATE_HOST`, `SHADOWGATE_PORT` | `127.0.0.1`, `8080` | Bind address for `shadowgate server` (`--host`/`--port` override them). |
| `SHADOWGATE_TLS_CERT_PATH`, `SHADOWGATE_TLS_KEY_PATH` | *(empty)* | Serve HTTPS with this certificate and key (`--tls-cert`/`--tls-key` override them). The key must be mode 600. |

`SHADOWGATE_HOST`, `SHADOWGATE_PORT`, `SHADOWGATE_ORG_KEY_PATH`, `SHADOWGATE_CA_KEY_PATH` and
`SHADOWGATE_CA_CERT_PATH` exist in `config.py` but are **not used**. Pass the bind
address and port to Uvicorn instead.
`SHADOWGATE_ORG_KEY_PATH`, `SHADOWGATE_CA_KEY_PATH` and `SHADOWGATE_CA_CERT_PATH` exist in
`config.py` but are **not used**.

Invalid token JSON, an unknown role, a malformed token, or an empty map without insecure
dev mode makes startup fail with an error, before any files are created.

## Running

### One-command demo

```bash
bash examples/demo.sh
```

In a temporary directory that is removed afterwards, the demo creates TLS certificates,
starts the server over HTTPS with fresh random tokens, enrolls three agents, runs the
example runbook on all of them, verifies the audit log, then deletes the newest audit entry
to show the tamper check failing. It needs `curl` and `jq`, and CI runs it on every push.

### Local development launcher

```bash
Expand All @@ -139,8 +158,25 @@ export SHADOWGATE_API_TOKENS_JSON='{"<admin-token>":"admin","<operator-token>":"
uv run shadowgate server # --host/--port, default 127.0.0.1:8080
```

Without operator tokens the server refuses to start (exit code 2). Binding to a
non-loopback address prints a warning, because there is no TLS.
Without operator tokens the server refuses to start (exit code 2).

### Over a network (HTTPS)

```bash
uv run shadowgate tls init --hostname gw.example --hostname 10.0.0.5 # once
uv run shadowgate server --host 0.0.0.0 --port 8443 \
--tls-cert .shadowgate/tls/server.crt --tls-key .shadowgate/tls/server.key
```

`tls init` creates a private CA and a server certificate for the names agents will use
(`localhost` and `127.0.0.1` are always included), with private keys at mode 600; it never
overwrites files. Copy `ca.crt` to agent hosts and enroll with
`--server https://gw.example:8443 --ca-file ca.crt`: the agent pins that CA in its
credential file. A certificate from a public CA works too; then omit `--ca-file`.

The server refuses a non-loopback bind without TLS. `--allow-plaintext` overrides that for
a TLS-terminating proxy on a trusted network. Agents refuse plain `http://` to anything but
loopback, and stop with exit code 2 if the server's certificate fails verification.

Replace the placeholders with long random values, e.g. `python -c 'import secrets; print(secrets.token_urlsafe(32))'`.

Expand Down Expand Up @@ -242,19 +278,21 @@ yet implemented.
- **One server process only:** database and audit-log access are serialized with in-process
locks, so requests are safe under concurrency but handled one at a time. Two server
processes (for example `uvicorn --workers 2`) on the same files would fork the audit chain.
- **Crash consistency:** some operations still commit in several steps. A crash or an
error between them (for example, the audit file failing to write after an enrollment
commit) can leave a job claimed but undelivered or a run that never advances.
- **Audit log:** deleting the newest entries is not detected.
- **Transport:** no TLS. Tokens travel in clear text; keep the server on loopback or behind
a TLS-terminating proxy you control. mTLS is not implemented.
- **Audit vs. database:** each request is one transaction, and its audit entries are written
just before the commit. If the audit write fails, nothing is committed. In the rare case
that the database commit itself fails after that, the log holds entries for a change
that did not happen.
- **Audit log:** the anchor sits next to the log, so someone who can rewrite both files
consistently (or delete the anchor and restart the server) is not detected. Copy
`verification` output or the anchor off the host if that matters.
- **Transport:** HTTPS is built in, but agents authenticate with a bearer token, not a client
certificate (no mTLS). There is no certificate rotation or revocation; `tls init` server
certificates last 397 days. Operators' own clients (`curl`, browser) must trust the CA.
- **Agent credentials:** they cannot be rotated or revoked, and agent tags cannot be changed
after enrollment, except by editing the database.
- **Enrollment edge cases:**
- If SQLite is busy, `POST /enroll` can return 500 after about 5 s. The enrollment token
is not consumed, and a retry succeeds.
- If the audit write fails just after an enrollment commits, the caller gets a 500 and
the one-time `agent_token` is lost.
- **First start after upgrading:** with more than one Uvicorn worker, the first start
against a database created by an older version can fail in some workers with
`duplicate column name: secret_hash`. Restart and it succeeds.
Expand All @@ -267,8 +305,6 @@ yet implemented.
- Jobs claimed by a crashed agent stay `running`.
- The `Poller` treats any 4xx other than 401/403 (including `408` and `429`) as final and
drops the result.
- If the server fails after marking a job finished, a retried result returns `duplicate`
and the runbook run does not advance.
- **Runbook engine defects:**
- A dependent step can start before all of its dependency's targets finish.
- A failing compensation step re-queues itself repeatedly.
Expand Down
50 changes: 34 additions & 16 deletions docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
```
+-------------------+ HTTP + Agent Token +-------------------+
operator | shadowgate | <----------------------> | shadowgate agent |
dashboard | server (FastAPI) | (mTLS deferred to T14) | (CLI: enroll, |
dashboard | server (FastAPI) | HTTPS, server CA pinned | (CLI: enroll, |
| | | run; Poller) |
| Store (sqlite) | | executor |
| qjobs (WAL) | | builtins |
Expand All @@ -29,7 +29,7 @@

## Data flow

1. Operator mints a one-time enrollment token (`POST /tokens`, optionally bound to an `agent_id`) → agent burns it once (`POST /enroll`) → `agents` stores `secret_hash` (SHA-256) and returns a one-time `agent_token`. (mTLS cert issuance/pinning is not yet implemented; deferred to T14.)
1. Operator mints a one-time enrollment token (`POST /tokens`, optionally bound to an `agent_id`) → agent burns it once (`POST /enroll`) → `agents` stores `secret_hash` (SHA-256) and returns a one-time `agent_token`. (Transport: server-side TLS, with the server CA pinned in the agent's credential file; agents do not use client certificates.)
2. Operator enqueues a job (`POST /jobs`) or starts a runbook (`POST /runs`).
3. Agent short-polls `POST /agent/poll` with `X-ShadowGate-Agent-Token` (long-poll is not yet implemented); server authenticates the agent and claims that agent's next queued job atomically (`claim_next(agent_id=...)`).
4. Agent executes the action (builtins; signed third-party plugin registry is not yet wired into an agent CLI) and posts `POST /agent/result` with `X-ShadowGate-Agent-Token`; server enforces job ownership (`id`, `agent_id`, `status='running'`).
Expand All @@ -43,15 +43,20 @@ make multi-connection reads live. `tests/test_queue.py` runs 8 threads over 40
jobs, each on its **own** connection, and asserts zero duplicate claims.

The running server shares **one** connection across FastAPI's request threads.
`Store`, `SqlQueue` and `RunEngine` hold one re-entrant lock (`server/db.py`) for
every method that touches it, so each operation, including nested run-engine
calls, runs alone. `tests/test_concurrency.py` drives 5 agents polling in
`Store`, `SqlQueue` and `RunEngine` share one `Transaction` (`server/db.py`): a
re-entrant lock that is also the unit of work. Every method that touches the
connection runs inside it; nested calls join the outer unit, the outermost exit
commits, and any exception rolls everything back. Endpoints that do several things
(claim + audit, complete + audit + run engine, enqueue + audit) wrap them in
`with store.transaction():`. Audit entries appended inside a transaction are held
back and written just before the commit, and dropped on rollback, so the log and
the database agree. `tests/test_transactions.py` injects a failure between each
former commit point. `tests/test_concurrency.py` drives 5 agents polling in
parallel over HTTP and 20 threads on one store, and asserts no errors, no
spurious 401s and no stranded jobs.

Remaining limits: the lock is per process (run one server process), requests
that touch the database are handled one at a time, and several operations still
commit in more than one step, so a crash between steps is not rolled back.
Remaining limits: the lock is per process (run one server process), and requests
that touch the database are handled one at a time.

## Plugin trust

Expand All @@ -63,13 +68,26 @@ in the codebase, but are not yet wired into an agent CLI.
## Audit integrity

`AuditLog.append` writes `prev = sha256(canonical(last_entry))` into each JSONL
line and `verify_chain()` recomputes the chain. Editing or reordering an existing
line is detected (`tests/test_audit.py` covers the edit case).
line, and `verify()` recomputes the chain. After every write, the sidecar
`<log>.head` records `{count, head}`. Verification reports `ok`, the number of
entries, how many leading entries check out, the anchored count, and an error:

- an edited, reordered or corrupt entry: where the chain breaks;
- a log shorter than its anchor: the newest entries were removed;
- a log whose entry at the anchored position has a different hash: rewritten;
- a missing or unreadable anchor.

If the server finds the log changed behind its back when it next writes, it
keeps the old anchor as `<log>.head.<timestamp>` and appends an
`audit_anchor_mismatch` entry before continuing, so the evidence survives and
`verify()` keeps failing.

Appends are O(1): the head hash, entry count and file size are cached per file,
and the file is re-read only when its size shows another writer.

Known limits:
- **Tail truncation is not detected.** Removing the newest line(s), or emptying
the file, still verifies, because nothing anchors the head.
- **Appends are serialized per process.** Reading the head and writing the
entry happen under one lock per file, so concurrent requests keep one chain.
Two processes writing the same file can still fork it. Each append still
re-reads the whole file (O(n)).
- **The anchor is local.** Rewriting the log and its anchor consistently, or
deleting the anchor and restarting (an existing log without an anchor is
adopted as-is), is not detected. Signed or off-host checkpoints are future work.
- **Appends are serialized per process.** Two processes writing the same file
can still fork the chain.
Loading
Loading