diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..38b7d4b --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 5aranx + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md index f6c64e2..47788f4 100644 --- a/README.md +++ b/README.md @@ -1,73 +1,280 @@ # ShadowGate -Authorized fleet agent-management platform. mTLS identity, an atomic job -queue, a signed plugin architecture, DAG runbook orchestration, and a -hash-chained audit log. Linux-first, Python 3.12+. +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. -> This is an agent-management tool for hosts you own and administer. There is -> no covert-channel, exfiltration, or evasion code anywhere in the tree. +> This is an agent-management tool for hosts you own and administer. There is no +> covert-channel, exfiltration, or evasion code anywhere in the tree. -## Features +**Status: pre-release (0.1.0).** +- The control server works for single-agent, loopback evaluation and is covered by tests. + Concurrent use is not reliable yet. +- The agent runs only as a Python library; the `shadowgate` command is not wired up yet. +- Several known defects remain. See [Known limitations](#known-limitations) before using it + beyond a single-host test setup. -- **Agent identity** — one-time enrollment tokens, per-agent mTLS certs -- **Atomic queue** — `UPDATE … RETURNING` exactly-once dispatch (SQLite WAL) -- **Plugin system** — builtin actions plus ed25519-signed third-party plugins - loaded via `shadowgate.actions` entry points -- **Runbooks** — YAML DAGs with cycle validation, fan-out, per-run concurrency - caps, and compensating steps on failure -- **Audit** — append-only SHA-256 chain; any edit breaks verification -- **Dashboard** — server-rendered Jinja2 + HTMX at `/ui` +## What it does -## Quickstart +| Area | What exists today | +|---|---| +| **Operator API** | FastAPI server. Operator routes are protected by bearer tokens with three roles: `viewer` < `operator` < `admin`. The server refuses to start without a valid token configuration, unless it is explicitly in insecure dev mode. | +| **Agent identity** | An admin mints a one-time enrollment token, which expires after 30 minutes and can optionally be bound to one agent id. The agent exchanges it once for a per-agent token. The server stores only the SHA-256 of that token. Agents send it in the `X-ShadowGate-Agent-Token` header. | +| **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. | +| **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`). | + +**Present in the code but not used at runtime yet:** +- mTLS certificate helpers (`crypto/mtls.py`). +- The ed25519 plugin-manifest gate for third-party plugins (`plugins/gate.py`). +- The SQLAlchemy models (`server/models.py`). + +## Architecture + +``` +operator (curl / browser) agent (Python library) + │ Authorization: Bearer │ X-ShadowGate-Agent-Token + │ or Basic (token as password) │ (plain HTTP; TLS not provided) + ▼ ▼ +FastAPI app (server/app.py, built by create_app factory) + ├── Store (server/store.py) SQLite WAL: agents, enroll_tokens + │ ├── SqlQueue (server/queue.py) qjobs: atomic claim, owner-checked completion + │ └── RunEngine (server/runs.py) runbooks, runs, steps, compensation + ├── orchestrator.py runbook parsing, validation, tag matching + ├── AuditLog (server/audit.py) hash-chained JSONL file + └── Jinja2 templates (web/) /ui pages + +agent/poll.py Poller: poll → Executor (agent/executor.py) → builtin actions → post result +``` + +See [`docs/architecture.md`](docs/architecture.md) and +[`docs/threat-model.md`](docs/threat-model.md). + +| Path | Contents | +|---|---| +| `src/shadowgate/server/` | app, store, queue, runs, orchestrator, audit (`models.py` is unused) | +| `src/shadowgate/agent/` | executor, polling client (`Poller`) | +| `src/shadowgate/plugins/` | `Action` protocol, registry, loader, gate, builtins | +| `src/shadowgate/crypto/` | ed25519 manifest signing; mTLS CA helpers (unused) | +| `src/shadowgate/cli/` | `shadowgate` entry point (placeholder) | +| `src/shadowgate/web/templates/` | dashboard templates | +| `docs/` | architecture, threat model | +| `examples/runbooks/` | sample runbook (YAML) | +| `tests/` | pytest suite | + +## Technologies + +- Python ≥ 3.12. Developed and tested on 3.13; CI runs 3.12. +- FastAPI, Uvicorn, Pydantic v2 and pydantic-settings, Jinja2. +- Standard-library `sqlite3`, which must link SQLite ≥ 3.35 for `RETURNING`. +- `cryptography` (ed25519, X.509), PyYAML, httpx. +- Tooling: [uv](https://docs.astral.sh/uv/), hatchling, pytest, ruff, mypy (strict). +- All versions are pinned in `uv.lock`. + +## Prerequisites + +- Linux. `service_status` needs systemd. +- [uv](https://docs.astral.sh/uv/getting-started/installation/), which installs a suitable + Python if needed. +- `curl` and `jq` for the examples below. + +## Installation ```bash -uv sync --extra dev -uv run pytest # 12 passing -uv run ruff check src tests # clean -uv run mypy # strict, clean -uv run uvicorn shadowgate.server.app:app --port 8080 +git clone https://github.com/5aranx/ShadowGate.git +cd ShadowGate +uv sync --frozen --extra dev # creates .venv from uv.lock ``` -Then: +## Configuration + +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. + +| Variable | Default | Used for | +|---|---|---| +| `SHADOWGATE_API_TOKENS_JSON` | *(empty)* | **Required** unless insecure dev mode is on. JSON object mapping token → role, e.g. `{"":"admin","":"viewer"}`. Roles: `viewer`, `operator`, `admin`. Tokens must be non-empty and contain no whitespace or `:`. The legacy name `SHADOWGATE_API_TOKENS` is also accepted. | +| `SHADOWGATE_INSECURE_DEV` | `false` | `true` allows an empty token map. Operator routes are then **unauthenticated**, and `/docs` and `/openapi.json` are enabled. Agent routes still require agent tokens. Local development only. | +| `SHADOWGATE_DB_PATH` | `shadowgate.db` | SQLite database. Relative to the working directory. | +| `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`, `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. + +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 + +### Local development launcher + +```bash +./run.sh +``` + +`run.sh` does the following: +1. Syncs dependencies. +2. Picks the operator tokens, highest precedence first: + 1. `SHADOWGATE_API_TOKENS_JSON` or `SHADOWGATE_API_TOKENS` already set in your shell (names + are case-insensitive). An empty value is respected, and the server then refuses to start. + 2. Either name defined in `./.env`. The server reads it itself; `run.sh` doesn't override it. + 3. Otherwise, a built-in **development** map: `admin-token`, `op-token`, `view-token`. + These are public example values; never use them anywhere reachable by others. +3. Starts the server on `127.0.0.1:8080` and prints which token source is in use. + +`./run.sh --check` syncs dependencies and runs ruff, mypy and pytest. It exports no tokens. + +### Directly ```bash -TOKEN=$(curl -s -X POST localhost:8080/tokens | jq -r .token) -curl -X POST localhost:8080/enroll -d "{\"agent_id\":\"a1\",\"token\":\"$TOKEN\",\"tags\":\"linux\"}" \ - -H 'Content-Type: application/json' -curl -X POST localhost:8080/jobs -d '{"agent_id":"a1","action":"system_info"}' \ - -H 'Content-Type: application/json' -open http://localhost:8080/ui +export SHADOWGATE_API_TOKENS_JSON='{"":"admin","":"operator","":"viewer"}' +uv run uvicorn --factory shadowgate.server.app:create_app --host 127.0.0.1 --port 8080 ``` -## Layout +Replace the placeholders with long random values, e.g. `python -c 'import secrets; print(secrets.token_urlsafe(32))'`. +### Walkthrough + +These examples use the `run.sh` development tokens: + +```bash +# 1. admin mints a one-time enrollment token (optionally bound: -d '{"agent_id":"a1"}') +TOKEN=$(curl -s -X POST localhost:8080/tokens -H 'Authorization: Bearer admin-token' | jq -r .token) + +# 2. the agent enrolls with it and receives its own token (returned once, stored hashed) +AGENT_TOKEN=$(curl -s -X POST localhost:8080/enroll -H 'Content-Type: application/json' \ + -d "{\"agent_id\":\"a1\",\"token\":\"$TOKEN\",\"tags\":\"linux\"}" | jq -r .agent_token) + +# 3. an operator queues a job for that agent +JOB=$(curl -s -X POST localhost:8080/jobs -H 'Authorization: Bearer op-token' \ + -H 'Content-Type: application/json' -d '{"agent_id":"a1","action":"system_info"}' | jq -r .job_id) + +# 4. the agent claims it and reports a result +curl -s -X POST localhost:8080/agent/poll -H "X-ShadowGate-Agent-Token: $AGENT_TOKEN" +curl -s -X POST localhost:8080/agent/result -H "X-ShadowGate-Agent-Token: $AGENT_TOKEN" \ + -H 'Content-Type: application/json' -d "{\"job_id\":\"$JOB\",\"ok\":true}" + +# 5. a viewer checks state and the audit chain +curl -s localhost:8080/jobs -H 'Authorization: Bearer view-token' +curl -s 'localhost:8080/audit?verify=true' -H 'Authorization: Bearer view-token' | jq .verified ``` -src/shadowgate/ - server/ app, store, queue, runs, orchestrator, audit - agent/ executor, long-poll client - plugins/ Action protocol, registry, loader, gate, builtins - crypto/ mTLS CA, ed25519 signing - cli/ `shadowgate` entry point - web/ templates + static -docs/ architecture.md, threat-model.md -examples/ runbooks/*.yaml -tests/ queue concurrency, audit tamper, plugins, signing, runs + +Dashboard: open `http://127.0.0.1:8080/ui`. The browser prompts for HTTP Basic credentials: +any username, and a viewer, operator or admin token as the password. + +**Runbooks.** `POST /runbooks` takes JSON (admin). To submit the YAML example: + +```bash +uv run python -c 'import json,sys,yaml; print(json.dumps(yaml.safe_load(open(sys.argv[1]))))' \ + examples/runbooks/disk-health-audit.yaml | + curl -s -X POST localhost:8080/runbooks -H 'Authorization: Bearer admin-token' \ + -H 'Content-Type: application/json' -d @- +curl -s -X POST localhost:8080/runs -H 'Authorization: Bearer op-token' \ + -H 'Content-Type: application/json' -d '{"runbook":"disk-health-audit"}' ``` -## Plugin example +**Running an agent.** There is no CLI for this yet. From Python: ```python -# inside your package, pyproject.toml: -# [project.entry-points."shadowgate.actions"] -# disk_health = "mypkg:DiskHealthAction" +from shadowgate.agent.executor import Executor +from shadowgate.agent.poll import Poller +from shadowgate.plugins.base import Registry +from shadowgate.plugins.loader import load_builtins + +registry = Registry() +load_builtins(registry) +Poller(Executor(registry, agent_id="a1"), "http://127.0.0.1:8080", + agent_token="").run() ``` -Ship a `shadowgate_plugin.json` manifest signed with the org ed25519 key, and -the gate will load it; otherwise it's dropped before import. +### API summary + +| Method and path | Auth | +|---|---| +| `GET /healthz`, `GET /` (redirects to `/ui`) | public | +| `POST /enroll` | one-time enrollment token in the body | +| `POST /agent/poll`, `POST /agent/result` | `X-ShadowGate-Agent-Token` | +| `GET /agents`, `/jobs`, `/runs/{id}`, `/audit`, `/ui`, `/ui/agents`, `/ui/jobs`, `/ui/runs` | viewer | +| `POST /jobs`, `POST /runs` | operator | +| `POST /tokens`, `POST /runbooks` | admin | + +Operator credentials can be sent as `Authorization: Bearer ` or as HTTP Basic with +the token as the password. + +## Testing + +```bash +uv run --frozen pytest -q # full suite +uv run --frozen ruff check src tests +uv run --frozen mypy # strict +./run.sh --check # uv sync --extra dev (not --frozen), then the same checks +``` + +CI (`.github/workflows/ci.yml`) runs ruff, mypy and pytest on every push and pull request. + +The suite is isolated from your configuration. Each test runs in its own temporary +directory with all `SHADOWGATE_*` variables removed, so shell exports or a `.env` file +don't change the results. `tests/test_env_precedence.py` pins the token precedence +described under [Configuration](#configuration) and [Running](#running), including the +behavior of `run.sh` (exercised with a stub `uv`, so nothing is installed or started). + +## Known limitations + +These are the user-visible issues found during verification. Fixes are planned but not +yet implemented. + +**Not suitable for multi-agent or networked use yet** +- **Concurrent requests:** the server shares one SQLite connection across request threads. + Concurrent agent polls can produce HTTP 500s, leave jobs marked `running` without + delivering them, and occasionally reject a *valid* agent token with 401. The `Poller` + stops permanently on 401. +- **Audit log:** concurrent writes can break the hash chain, so `verify=true` reports + `false` with no tampering. 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. +- **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. + +**Functional gaps** +- **CLI:** `shadowgate server|agent|plugin` print a placeholder; there is no agent CLI. +- **Job results:** + - The `data` payload a job reports is not stored. + - 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. + - A step that matches no agents leaves its run `running` forever. + - Malformed runbooks return HTTP 500. +- **Not used:** third-party plugin loading and the signature gate. + +**Operational** +- **Config:** see the unused settings above. +- **Logging:** the application logs nothing of its own. Uvicorn still prints request and + error logs to the terminal. -## CI +## License -`.github/workflows/ci.yml` runs ruff, mypy --strict, and pytest on every push. +MIT. See [LICENSE](LICENSE). --- diff --git a/docs/architecture.md b/docs/architecture.md index 7a994cc..e08b4f9 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -1,13 +1,13 @@ # Architecture ``` - +-------------------+ HTTPS/mTLS +-------------------+ - operator | shadowgate | <------------------> | shadowgate agent | - dashboard | server (FastAPI) | | (daemon) | - | | | executor | - | Store (sqlite) | | plugin loader | - | qjobs (WAL) | +-------------------+ - | RunEngine | + +-------------------+ HTTP + Agent Token +-------------------+ + operator | shadowgate | <----------------------> | shadowgate agent | + dashboard | server (FastAPI) | (mTLS deferred to T14) | (library; CLI | + | | | not yet wired) | + | Store (sqlite) | | executor | + | qjobs (WAL) | | builtins | + | RunEngine | +-------------------+ | AuditLog (chain) | +-------------------+ ``` @@ -17,40 +17,52 @@ | Module | Responsibility | |---|---| | `server/app.py` | FastAPI surface: tokens, enroll, jobs, poll, result, runs, ui | -| `server/store.py` | One WAL sqlite connection for agents, tokens, queue, runs | -| `server/queue.py` | Atomic exactly-once claim via `UPDATE … RETURNING` | +| `server/store.py` | One WAL sqlite connection shared by agents, tokens, queue and runs (enrollment uses a short-lived dedicated connection). The shared connection is not yet safe under concurrent requests; see Queue concurrency. | +| `server/queue.py` | Atomic per-row claim via `UPDATE … RETURNING`; completion is owner- and status-checked | | `server/runs.py` | DAG materialization, concurrency cap, compensation | -| `server/audit.py` | Append-only SHA-256 hash chain, tamper-evident | +| `server/audit.py` | Append-only SHA-256 hash chain; detects edited or reordered entries (limits below) | | `server/orchestrator.py` | Runbook YAML, validation, cycle rejection, targeting | | `plugins/loader.py` | Builtin + `entry_points` discovery | -| `plugins/gate.py` | ed25519 signature gate for external plugins | -| `crypto/mtls.py` | Local CA, per-agent cert issuance | +| `plugins/gate.py` | ed25519 signature gate for external plugins (not used at runtime yet) | +| `crypto/mtls.py` | Local CA, per-agent cert issuance (not used at runtime yet) | | `crypto/signing.py` | Org key generation, manifest sign/verify | ## Data flow -1. Operator mints a one-time enrollment token → agent burns it once → agent is in `agents`. -2. Operator enqueues a job (`/jobs`) or starts a runbook (`/runs`). -3. Agent long-polls `/agent/poll`; server claims that agent's next queued job atomically and returns it. -4. Agent executes the action through its signed plugin registry, posts `/agent/result`. -5. Server completes the job, updates the run state machine, and every transition is appended to the audit chain. +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.) +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'`). +5. Server completes the job and updates the run state machine; each accepted transition is appended to the audit chain. A retried identical result is acknowledged as `duplicate` without a new audit entry or engine call. ## Queue concurrency `SqlQueue` claims with a single `UPDATE` constrained to `status='queued'` and `RETURNING`, so two workers cannot claim the same row. WAL + `busy_timeout` -make multi-connection reads live. Test: `tests/test_queue.py` runs 8 threads -over 40 jobs and asserts zero duplicates. +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, however, shares **one** connection across FastAPI's request +threads. Under concurrent agent polls this produces sqlite3 errors and HTTP 500s, +can leave jobs `running` without delivering them, and can transiently reject a +valid agent token with 401. Serializing or isolating connection use is planned +work and is not implemented. ## Plugin trust Builtin actions ship with the package and are implicitly trusted. Third-party -actions are discovered via the `shadowgate.actions` entry-point group but are -loaded only after `plugins/gate.make_verifier` validates a signed -`shadowgate_plugin.json` manifest against the pinned org public key. +discovery (`plugins/loader.load_entry_points`) and ed25519 manifest +verification (`plugins/gate.make_verifier` for `shadowgate_plugin.json`) exist +in the codebase, but are not yet wired into an agent CLI. ## Audit integrity -`AuditLog.append` writes `prev = sha256(last_entry)` into each JSONL line, and -`verify_chain()` recomputes the chain. Any edit, deletion, or reorder breaks -the head — tested in `tests/test_audit.py`. +`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). + +Known limits: +- **Tail truncation is not detected.** Removing the newest line(s), or emptying + the file, still verifies, because nothing anchors the head. +- **Concurrent appends fork the chain.** `append` is not serialized, so + `verify=true` can report `false` without any tampering. diff --git a/docs/assessment-2026-11-30.md b/docs/assessment-2026-11-30.md new file mode 100644 index 0000000..98cea7d --- /dev/null +++ b/docs/assessment-2026-11-30.md @@ -0,0 +1,293 @@ +# ShadowGate — Engineering Assessment (2026-11-30) + +Assessment-only. No application source, tests, config, or tracked files were +changed. Commit assessed: `b9f2183` (main, clean working tree). + +> **Historical snapshot.** This describes the code *before* the M7 change set. +> S1, S2, S3 and S6 were fixed in M7. Current status, later findings and the +> roadmap live in [`tracker.md`](tracker.md). + +**Evidence labels** + +- **Verified**: reproduced locally, by running the test suite or a local probe against a temp-dir `TestClient` instance with no network. +- **Static**: read in code and not executed. +- File references are `path:line` relative to the repo root. + +**Probes P1–P11.** These were throwaway local scripts. Each one built a fresh app with +`create_app(Settings(...))` on temporary paths, drove it through FastAPI's `TestClient`, +and checked one finding. They are not part of the repository; each finding below +describes its reproduction. The M7 fixes are now covered by tests in `tests/`: + +| Probe | Finding | Covering test(s) after M7 | +|---|---|---| +| P1 | Launcher token variable ignored | `test_config_auth.py::test_t1e_env_alias_enables_rbac`, `test_env_precedence.py` | +| P2 | Malformed token JSON fails open | `test_config_auth.py::test_t1a_*`, `test_t1b_*`, `test_t1c_*` | +| P3a–c | Anonymous or cross-agent poll and result | `test_agent_auth.py::test_t2h_*`, `test_t2i_*`, `test_t2j_*`, `test_t2m_*`, `test_t2n_*` | +| P3d | Read routes without RBAC | `test_auth.py::test_t3a_*`, `test_t3d_*` | +| P4 | `/enroll` needed an admin bearer | `test_agent_auth.py::test_t2a_*` | +| P11 | Re-enrollment overwrote an agent | `test_agent_auth.py::test_t2c_*` | +| P5–P10 | Runbook, result, and audit defects | Open; reproduction steps in the findings below | +| gate probe | Plugin gate accepts a transplanted manifest | Open (S4); reproduction in S4 below | + +**Method.** Separate passes covered implementation and dependencies, architecture +against the docs, test coverage, code quality and CI, and library documentation. Every +finding included here was either reproduced locally or checked against the source. + +--- + +## 1. Executive summary + +ShadowGate is a small codebase: about 1.3k lines of Python under `src/`. It is +cleanly typed and lint-clean. Ruff, `mypy --strict`, and **17/17 tests** all pass +(Verified). + +The green build hides a structural gap. The project's central security claims are +mTLS agent identity, signed plugins, "agents only pull their own work", and +tamper-evident audit. **None of them holds in the running application.** + +- **Agent endpoints are unauthenticated.** `/agent/poll` and `/agent/result` take an `agent_id` or `job_id` from the request body. Any caller can claim any agent's jobs and forge or overwrite any job's result. (Verified) +- **The bundled launcher turns RBAC off.** `run.sh` exports `SHADOWGATE_API_TOKENS`. The setting is actually read from `SHADOWGATE_API_TOKENS_JSON`, so the server starts in open "dev mode". Malformed token JSON also fails open. (Verified) +- **`crypto/mtls.py` and `plugins/gate.py` are never called.** The plugin gate also does not bind a signature to the plugin's code: a copied signed manifest approves any package. (Verified) +- **The runbook engine has correctness bugs.** It can dispatch dependent steps before their dependencies finish. A failing compensation step re-enqueues itself without limit. A step that matches zero agents hangs the run forever. (All Verified) +- **Job result payloads are discarded.** (Verified) + +The architecture is a sensible base: a single SQLite store, an atomic +`UPDATE … RETURNING` claim, a DAG engine, and a hash-chained audit log. The +problems are in wiring and enforcement, not in the overall design. + +## 2. Architecture + +``` +operator (curl / browser) + │ bearer token (RBAC) — only on some routes + ▼ +FastAPI app (server/app.py, built at import time: app = create_app()) + ├── Store (server/store.py) one sqlite3 conn, WAL, check_same_thread=False + │ ├── tables: agents, enroll_tokens + │ ├── SqlQueue (server/queue.py) table qjobs, atomic claim + │ └── RunEngine (server/runs.py) runbooks, runs, run_steps, run_step_agents, run_jobs + ├── AuditLog (server/audit.py) JSONL file, SHA-256 chain (outside the DB transaction) + ├── orchestrator.py YAML parse/validate/topo/tag-match + └── Jinja2 templates (/ui*) read-only tables; HTMX loaded but unused + ▲ + │ plain HTTP, no agent credential +agent library (not runnable from CLI) + Poller (agent/poll.py) → Executor (agent/executor.py) → Registry (plugins/base.py) + └─ builtins: system_info, disk_health, file_fetch, service_status + +Not used at runtime: crypto/mtls.py, plugins/gate.py, plugins/loader.load_entry_points, +server/models.py (SQLAlchemy async ORM), cli/main.py (stub). +``` + +**Stack** + +- Python ≥3.12, FastAPI 0.142, Uvicorn 0.54, Pydantic 2.13, pydantic-settings, stdlib `sqlite3` +- PyYAML, cryptography 50, httpx, Jinja2 +- Tooling: uv, hatchling, ruff, mypy strict, pytest, GitHub Actions +- These are lockfile versions from `uv.lock`. + +**Unused dependencies** + +- SQLAlchemy and aiosqlite are used only by the dead `models.py`. +- itsdangerous and python-multipart have no consumer. +- Starlette is imported directly but is only a transitive dependency. + +## 3. Feature implementation status + +| Feature | Status | Evidence | +|---|---|---| +| One-time enrollment tokens (mint, single burn) | Implemented and verified | `tests/test_server.py:23`; `store.py:66-78` | +| Token expiry (30 min TTL) | Implemented, unverified | `store.py:55-78`; no test | +| Atomic exactly-once claim | Implemented and verified | `tests/test_queue.py` (8 threads × 40 jobs) | +| Bearer RBAC viewer/operator/admin | Partial: missing on `/agent/*`, `/jobs`, `/runs/{id}`, `/ui*`; fails open | `app.py:63-82,126-218`; probes P1, P2, P3d | +| Rate limiting | Partial: `/tokens` and `/enroll` only; in-memory and unbounded | `app.py:84-93`; `tests/test_auth.py:58` | +| Agent self-enrollment | Not implemented as documented: `/enroll` requires an **admin** bearer token | `app.py:107`; probe P4 | +| mTLS agent identity / cert pinning | Partial: CA and cert generation code only, never called; no TLS config; agent uses a plain `httpx.Client()` | `crypto/mtls.py`; `agent/poll.py:31` | +| Signed third-party plugins | Partial: gate exists but is not wired; signature not bound to code | `plugins/gate.py:47-57`; `loader.py:20-31`; gate probe | +| Builtin actions | Implemented; `system_info` verified, others unverified | `tests/test_plugins.py` | +| Agent poll/execute loop | Implemented, unverified; no tests; no entry point | `agent/poll.py` | +| Job results storage | **Not implemented**: `data` dropped | `queue.py:80-85`; probe P9 | +| Runbook DAG, fan-out, concurrency cap | Implemented with bugs; happy-path test passes | `tests/test_runs.py`; probes P5, P7 | +| Compensation on failure | Implemented with bugs | probe P6 | +| Audit hash chain | Implemented. Detects in-place edits (verified); does **not** detect tail truncation (verified); no append locking | `tests/test_audit.py`; probe P10 | +| Dashboard `/ui` | Partial: three read-only tables, unauthenticated, HTMX unused, `web/static` empty and unmounted | `app.py:204-218`; `templates/` | +| Long polling | Not implemented: short poll with 1 s sleep | `app.py:126-133`; `poll.py:30-37` | +| Re-queue of crashed jobs | Planned ("future" in threat model) | `docs/threat-model.md` | +| CLI `server`/`agent`/`plugin` | Planned: prints "not yet wired" and exits 0 | `cli/main.py:19` | +| `insecure_dev` mode | Planned: setting never read | `config.py:13` | +| Async SQLAlchemy persistence | Dead code | `server/models.py` | +| Multi-worker / production deployment | Unknown: shared sqlite conn across the threadpool with no lock, in-memory rate limiter; not tested | `store.py:24` | + +## 4. Technical findings, bugs, and risks + +Severity reflects ShadowGate's stated purpose: a fleet control plane exposed to +agents over the network. + +### Critical / High: security + +| # | Finding | Evidence | Status | +|---|---|---|---| +| S1 | **Agent endpoints have no authentication or ownership checks.** Anyone who can reach the server can (a) claim any agent's queued jobs by sending its `agent_id`, which leaks job params and denies the real agent the work; (b) post results for any `job_id`; (c) flip a terminal job `done`→`failed`; (d) post results for nonexistent jobs, which are still audited. Through `on_job_result`, a forged failure also fails runbook runs and triggers compensation. | `app.py:126-141`, `queue.py:80-85` | Verified (P3a–c) | +| S2 | **Auth fails open.** (a) `run.sh:6` and `docs/threat-model.md` use `SHADOWGATE_API_TOKENS`, but the field is `api_tokens_json` with prefix `SHADOWGATE_`. The real variable is `SHADOWGATE_API_TOKENS_JSON`, so the launcher runs fully open. (b) Invalid JSON is caught and treated as "no tokens", which means open. (c) Valid JSON of the wrong type (e.g. a list) leads to HTTP 500 (independent review, Verified). | `config.py:7,18`, `app.py:65-73` | Verified (P1, P2) | +| S3 | **Read routes skip RBAC.** `/jobs`, `/runs/{id}`, `/ui`, `/ui/agents`, `/ui/jobs`, and `/ui/runs` return fleet data with no token even when RBAC is on. `/agents` has the same data but is protected. | `app.py:168-218` | Verified (P3d) | +| S4 | **Plugin gate authenticates metadata, not code.** The verifier checks that *some* signed manifest exists in the dist-info. It never compares it to the entry point, the distribution name, or a code digest. Copying any signed manifest into a malicious package passes. The gate is also optional (`allow=None` loads everything) and not called anywhere. | `gate.py:47-57`, `loader.py:20-31` | Verified (gate probe) | +| S5 | **The mTLS claim is not backed by code.** Nothing calls `ensure_ca` or `issue_agent_cert`. Uvicorn is not started with TLS or client-cert verification (Uvicorn defaults to `CERT_NONE`, per the Uvicorn docs). Enrollment returns no cert. | `crypto/mtls.py`, `run.sh:21`, `poll.py:31` | Static | +| S6 | **Re-enrollment overwrites an existing agent.** A new token plus an existing `agent_id` silently replaces its tags, which changes which runbooks target it. This contradicts "agent can't re-enroll". | `store.py:80-86` | Verified (P11) | +| S7 | **Audit chain cannot detect deletion of trailing entries.** No anchor or checkpoint exists. There is no lock around read-last-hash-then-append, so concurrent requests can fork the chain. Each append re-reads the whole file, which makes total append cost O(n²). | `audit.py:35-76` | Verified (P10), race Static | +| S8 | **Builtin hygiene.** `file_fetch` reads the *whole* file into memory before slicing, accepts any path, and returns only a length. `service_status` returns `ok=True` regardless of exit code. `disk_health` accepts any path. Agents act only on server-issued jobs, so with S1 open anyone can direct these actions at agents. | `plugins/builtin/*.py` | Static | + +### High / Medium: correctness + +| # | Finding | Evidence | Status | +|---|---|---|---| +| C1 | **DAG ordering violated.** After any successful result, `_maybe_advance` calls `_schedule` on *every* non-compensation step before checking dependencies. With free capacity, a dependent step starts while its dependency is still running. The existing test passes only because of the order it polls in. | `runs.py:156-160` | Verified (P5) | +| C2 | **Compensation loops and over-triggers.** Each failed tracked job, including a failed *compensation* job, calls `_fail_run` again. That re-enqueues all compensations every time (5/5 polls produced new compensation jobs; 6× `run_failed`). It also compensates steps that never ran, and marks compensation `done` at enqueue time. | `runs.py:139-141,217-250` | Verified (P6) | +| C3 | **Zero-target steps hang runs.** A step matching no agents stays `pending` and the run stays `running` forever. This applies to both root and dependent steps, and to an empty `steps: []` runbook (independent review). | `runs.py:97-103,197-205` | Verified (P7) | +| C4 | **Unknown target keys match everything.** `targets: {tags: linux}` is a typo for `tag`, but it fans out to *all* agents. | `orchestrator.py:125-133` | Static; independently Verified | +| C5 | **Malformed runbooks lead to 500.** Missing `steps`/`name`/`action` or wrong types raise from `parse_runbook` before validation. | `app.py:143-155`, `orchestrator.py:52-72` | Verified (P8: 4/4 → 500) | +| C6 | **In-flight runs follow edited runbooks.** `INSERT OR REPLACE` by name; runs reload the spec by name during advance and compensation. | `runs.py:44-48,149,221` | Static | +| C7 | **Results discarded and work lost.** `complete()` ignores `data`. The Poller ignores the result POST's status. Claimed jobs never expire, so a crashed agent leaves them `running` forever. | `queue.py:80-85`, `poll.py:24-28` | Verified (P9), rest Static | +| C8 | **No transactional boundaries.** Token burn commits before agent insert. Enqueue commits before run tracking rows. One sqlite connection is shared across FastAPI's threadpool with no lock. The audit write is outside the DB. The `store.py` docstring claims the opposite. | `store.py:1-5,24,66-86`, `runs.py:108-122` | Static | +| C9 | **Import-time side effects.** `app = create_app()` at module import creates `shadowgate.db` and `.shadowgate/` in the CWD. That is why both exist in the repo root. `data_dir` does not relocate `db_path`/`audit_log_path`. | `app.py:223`, `config.py:9-15` | Static; independently Verified | + +### Maintainability / technical debt + +- `server/models.py` is a full async ORM with a conflicting `jobs` schema. Nothing uses it, and it pulls in two dependencies. +- No logging anywhere. Broad `except Exception` in the executor, signing, and poller. +- Function-local imports throughout `app.py` and `runs.py`. +- Test `Settings(...)` fixture copied four times; no `conftest.py`. +- 7 of 13 settings do nothing: `insecure_dev`, `org_key_path`, `ca_*`, `host`, `port`, `data_dir` as a base path. +- HTMX is loaded from unpkg with no SRI and is unused. +- CI: mypy excludes `tests/`; no `--frozen`/`uv lock --check`; no coverage; uv pinned to 0.12.22 while the lock was produced locally with 0.13.x. + +## 5. Testing assessment + +**Verified run.** The scratch venv was created with `uv sync --frozen --extra dev`. + +``` +17 passed, 1 warning (Starlette httpx deprecation) +ruff check src tests → All checks passed! +mypy (strict, package) → Success: no issues found in 32 source files +``` + +**Coverage.** This is a static map; no coverage tool is installed. + +| Module | State | +|---|---| +| queue | well covered | +| orchestrator, audit, signing, app, runs | partial | +| `crypto/mtls.py`, `plugins/gate.py`, `agent/poll.py`, `cli/main.py`, `server/models.py` | **no tests at all** | + +**Highest-value missing tests:** + +1. Agent endpoints reject unauthenticated or other-agent callers. Today this would fail, which means it is a finding (S1). +2. A result from agent B for agent A's job is rejected; terminal state is immutable. +3. Plugin gate: unsigned, tampered, and *transplanted* manifests are rejected before `ep.load()`. +4. RBAC on every route, including `/ui*`, `/jobs`, and `/runs/{id}`. Startup fails on missing or invalid token config. +5. Runbook engine: a dependent step does not start before its dependencies are `done` with 2+ agents and spare capacity. Compensation runs once per failed step. A zero-target step and an empty runbook terminate. An unknown selector key is rejected. +6. Malformed runbook → 400 with errors. +7. Audit: reorder, delete-middle, delete-tail, and corrupt-line cases. +8. Token expiry; re-enrolling an existing `agent_id`. + +**Note on the environment.** During this assessment, an agent ran `uv run mypy` +and uv rebuilt the gitignored `.venv` without the dev extras. Plain +`uv run pytest` then fell through to the system pytest and failed to import. +That was caused by the assessment, not the project. Following the README +(`uv sync --extra dev` first) works. To restore your local env, run +`uv sync --extra dev`. + +## 6. Documentation gaps + +- **README** + - says "12 passing"; there are 17. + - Quickstart `curl`s work only because auth is off. + - lists HTMX, `web/static`, and plugin gating as working features. +- **`docs/architecture.md`** + - shows "HTTPS/mTLS" between server and agent, and "long-polls"; neither exists. + - says the agent runs a "signed plugin registry", which isn't wired. +- **`docs/threat-model.md`** + - wrong env var name (`SHADOWGATE_API_TOKENS`). + - "certs pinned at enrollment" and "agents only ever pull work that names their own agent id" are not enforced. + - "idempotent `complete`" is false. + - "Compromised plugin package: signature gate blocks load" is false (S4). +- **`store.py` docstring:** claims shared transactional semantics with the audit chain; it doesn't have them. +- **Missing docs** + - how to run an agent (impossible without writing code) + - configuration reference + - API reference beyond the curl snippet + - deployment and TLS guidance + +## 7. Prioritized recommendations + +| Pri | Recommendation | Addresses | +|---|---|---| +| P0 | Fail-closed auth config, plus authenticated agent identity bound to poll/result and job ownership | S1, S2, S6, part of C7 | +| P0 | RBAC on every non-health route, including `/ui*` | S3 | +| P1 | Fix the run engine: dependency gating inside `_schedule`, single guarded failure transition, compensation only for executed steps and only once, zero-target semantics, spec snapshot per run, selector validation | C1–C4, C6 | +| P1 | Schema-validate runbooks (Pydantic model) → 400 | C5 | +| P1 | Persist result payloads; conditional `complete` (`WHERE status='running' AND agent_id=?`); claim lease and re-queue | C7 | +| P2 | Transactions per logical operation; lock audit append; audit head checkpoint | C8, S7 | +| P2 | Plugin gate: sign `{dist name, version, entry points, file digests}`, verify against installed files, make the gate mandatory, wire it into the agent | S4 | +| P2 | Decide on mTLS (see §9) and either implement it or remove the claims | S5 | +| P3 | Wire the CLI (`server`, `agent`); remove `models.py` and unused deps; logging; `conftest.py`; coverage + `--frozen` in CI; docs corrections | debt, docs | + +## 8. Proposed roadmap + +1. **M7: Trust boundary (P0).** Auth fail-closed, agent credentials, ownership checks, full RBAC, doc corrections for the env var. *About 1–2 days.* +2. **M8: Orchestration correctness (P1).** Run-engine fixes with regression tests for P5–P8, runbook schema, result persistence, conditional completion, claim leases. +3. **M9: Durability and audit (P2).** Transactions, a serialized audit writer, chain head anchoring, per-request connections or a connection lock. +4. **M10: Supply chain and transport (P2).** Bound plugin signatures plus a mandatory gate in the agent; mTLS via a TLS-terminating proxy that forwards a verified client identity, or native Uvicorn `--ssl-cert-reqs 2` plus agent cert issuance at enrollment. +5. **M11: Usability and debt (P3).** Working `shadowgate server|agent` CLI, dashboard auth (session + CSRF if write actions are added), remove dead code and dependencies, logging, CI hardening, README and doc refresh. + +## 9. Next task (recommended): M7 — close the agent trust boundary + +**Why first.** Every other feature depends on knowing *who* is calling: + +- job ownership +- result integrity +- run-state transitions +- compensation triggers +- audit attribution + +Today that trust boundary doesn't exist (S1), and the shipped launcher disables +the operator one (S2). Fixing the run engine first would make the correct state +transitions just as forgeable by any caller. The change is also small and +contained to `app.py`, `store.py`, `queue.py`, and `config.py`, and it is easy to +test. + +**Scope.** Use per-agent credentials now; mTLS is deferred to M10. Uvicorn does +not expose the verified peer certificate to the app, so mTLS needs its own design +decision. + +1. **Fail-closed config.** + - Accept `SHADOWGATE_API_TOKENS_JSON` (and optionally alias `SHADOWGATE_API_TOKENS`). + - Startup **fails** on invalid JSON or a non-`dict[str, role]` value. + - An empty token map is allowed only when `insecure_dev=true`, and then a warning is logged. +2. **Agent credentials.** + - `/enroll` is authorized by the one-time token alone; the admin bearer is no longer required. + - Enrollment returns a random per-agent secret. Only its hash is stored. + - Re-enrolling an existing `agent_id` is rejected unless an admin explicitly revokes it first. +3. **Bound agent endpoints.** + - `/agent/poll` and `/agent/result` require the agent secret. + - The agent id is taken from the credential, not the body. +4. **Ownership.** + - `qjobs` records the claiming agent. + - `complete()` updates only `WHERE id=? AND agent_id=? AND status='running'`. + - Otherwise it returns 404/409 and writes nothing to the audit log or the run engine. +5. **RBAC everywhere.** `viewer` or higher on `/jobs`, `/runs/{id}`, and `/ui*`. +6. **Poller.** Sends the credential and checks the result response status. +7. **Docs.** Fix `run.sh`, the README quickstart, and the threat model's env var and claims. + +**Acceptance criteria** + +- [ ] `run.sh` (default env) starts with RBAC active: `curl -X POST :8080/tokens` without a header → 401. +- [ ] Invalid or ill-typed token JSON → process exits non-zero with a clear error. Empty map without `insecure_dev` → exits non-zero. +- [ ] `/enroll` with a valid one-time token and no bearer → 200 and returns an agent secret. The secret is stored hashed in SQLite. +- [ ] Re-enrolling an existing `agent_id` → 409. +- [ ] `/agent/poll` and `/agent/result` without a credential → 401. Agent B's credential cannot claim or complete agent A's job → 403/404, and qjobs status is unchanged. +- [ ] A second result for a terminal job → 409; status is unchanged and no extra `job_completed` audit entry is written. +- [ ] A result for an unknown `job_id` → 404, with no audit entry. +- [ ] Every route except `/healthz` and `/` returns 401 without a token when RBAC is configured (one parametrized test over `app.routes`). +- [ ] The behaviors behind probes P1–P4 and P11 are covered by tests and no longer reproduce (see the probe table above). +- [ ] Existing tests are updated to authenticate. The full suite, ruff, and `mypy --strict` pass. +- [ ] README, `run.sh`, and `docs/threat-model.md` use the correct variable and describe agent auth accurately. diff --git a/docs/threat-model.md b/docs/threat-model.md index 5d81141..5644b4b 100644 --- a/docs/threat-model.md +++ b/docs/threat-model.md @@ -5,22 +5,38 @@ authorized to administer. It is designed to make unauthorized use hard. ## Assets -- Agent identity keys (`ca.key`, agent certs, org signing key) +- Credentials: one-time enrollment tokens, per-agent tokens (the only agent credential used at runtime), and the operator token map. Signing keys and certificates (`crypto/`) are not generated or used yet. - The job queue and task results (may contain host metadata) - The audit log's integrity ## Trust boundaries -- Agent certs are issued per agent by the local CA and pinned at enrollment; - re-enrollment requires a fresh one-time token. -- Enrollment tokens are single-use and expire; a second use of a burned token is - rejected with 403. -- Operator endpoints are RBAC-gated (`viewer`/`operator`/`admin` bearer - tokens via `SHADOWGATE_API_TOKENS`) and `/tokens` + `/enroll` are rate-limited - per source IP. With no tokens configured the API is open (dev mode) — set - `SHADOWGATE_API_TOKENS` before exposing it. -- Plugin loads are gated by org signature; an unsigned or tampered manifest is - rejected before the action object is even imported. +- **Agent identity:** `/enroll` is authorized by a single-use, expiring enrollment + token (optionally bound to a specific `agent_id`). On success, the server + issues a random per-agent token (`agent_token`) once and stores only its + SHA-256 hash (`secret_hash`). `/agent/poll` and `/agent/result` require + `X-ShadowGate-Agent-Token` and derive `agent_id` from that credential. + *Note: mTLS (`crypto/mtls.py`) is not yet implemented/wired (deferred to T14).* +- **Re-enrollment:** Re-enrolling an existing `agent_id` is rejected with `409` + (unless reclaiming a legacy row with no `secret_hash` using an + `agent_id`-bound token, which preserves its existing tags). +- **Enrollment tokens:** Single-use and expire; a second use of a burned token, + expired token, or token bound to a different `agent_id` is rejected with `403`. +- **Operator RBAC & fail-closed config:** Non-public operator and UI routes + (`viewer`/`operator`/`admin`) are gated via `SHADOWGATE_API_TOKENS_JSON` + (with `SHADOWGATE_API_TOKENS` fallback), accepting `Bearer` tokens or HTTP + Basic auth (token as password) on every role-protected route (viewer, operator and admin), with a + `WWW-Authenticate: Basic` challenge header sent on `/ui*`. A malformed token + map (invalid JSON, unknown role, empty/whitespace/`:` token) aborts startup in + every mode; an *empty* map is accepted only when `SHADOWGATE_INSECURE_DEV=true`, + which leaves operator routes unauthenticated. `/tokens` and `/enroll` are + rate-limited per source IP and per endpoint (behind a reverse proxy, all + clients share the proxy's IP). +- **Transport:** there is no TLS. Bearer, Basic and agent credentials travel in + clear text on every request. Bind to loopback, or terminate TLS in a proxy you + control; do not expose `/ui` or the API beyond a trusted network. +- **Plugin gate:** `plugins/gate.py` and `crypto/signing.py` exist, but + third-party plugin verification is not yet wired into an agent CLI. ## Explicit non-goals / guardrails @@ -28,17 +44,23 @@ authorized to administer. It is designed to make unauthorized use hard. data-fetchers (`system_info`, `disk_health`, `file_fetch`, `service_status`). - **No obfuscation, no traffic hiding, no persistence mechanisms, no exfiltration channel.** Any PR introducing these is rejected. -- Agents only ever pull work that names their own agent id (`claim_next(agent_id=…)`). +- Agents only ever pull work that names their own agent id (`claim_next(agent_id=…)`); + no cross-agent claim has been observed, including under concurrency. Under + concurrent requests a *valid* agent token can transiently be rejected with 401 + (an availability issue, not an isolation one). ## Failure modes | Failure | Handling | |---|---| -| Duplicate HTTP delivery of a result | Queue row already terminal → idempotent `complete` | +| Duplicate HTTP delivery of a result | Same owner + terminal with same `ok` → `200 {"status": "duplicate"}` (no audit/engine side effects); different `ok` or non-`running` → `409`; unknown/other-agent job → `404` | | Worker crash mid-job | Row stays `running`; operator surface for re-queue (future) | -| Audit log tampered | `verify_chain()` returns false; head hash mismatch | -| Compromised plugin package | Signature gate blocks load unless org key also compromised | -| Enrollment token reuse | Burned token rejected; agent can't re-enroll | +| Audit log edited or reordered | `verify_chain()` returns false | +| Audit log truncated or emptied | **Not detected**: still returns true (nothing anchors the head) | +| Concurrent audit writes (no tampering) | `verify_chain()` can return false; `append` is not serialized | +| Concurrent HTTP requests | Shared sqlite connection is not thread-safe: HTTP 500s, jobs left `running` undelivered, occasional spurious 401 for a valid agent token | +| Compromised plugin package | Gate exists in `plugins/gate.py` but is not yet wired into an agent CLI | +| Enrollment token reuse / re-enroll | Burned/expired/wrong-agent token → `403`; existing `agent_id` → `409` (token not burned) | ## Reporting diff --git a/docs/tracker.md b/docs/tracker.md new file mode 100644 index 0000000..70e4204 --- /dev/null +++ b/docs/tracker.md @@ -0,0 +1,1200 @@ +# ShadowGate — Development Tracker + +This is the living tracker. The dated assessment it was built from is +[`assessment-2026-11-30.md`](assessment-2026-11-30.md), which defines finding IDs +S1–S8 and C1–C9 and probes P1–P11. + +- **Baseline:** `b9f2183`, 17/17 tests passing, ruff and `mypy --strict` clean. +- **Last updated:** 2026-11-30 (Blocker 3 fix, license, documentation cleanup; §10) +- **Status values:** `Planned` → `Ready` → `In progress` → `In review` → `Done`, or `Blocked` + +## 0. Status board + +| ID | Task | Pri | Cx | Status | Depends on | +|---|---|---|---|---|---| +| **M7** | **Trust boundary change set = T1 + T2 + T3** | **P0** | **High** | **Verified: PASS WITH ISSUES (§8). B1, B3 and B6 resolved (§10); release still NOT READY because of B2, B4 and B5 (§9)** | none | +| T1 | Fail-closed operator auth config, plus app factory | P0 | Med | In review (M7) | none | +| T2 | Agent identity and job ownership | P0 | High | In review (M7) | T1 | +| T3 | RBAC on every non-public route, including the dashboard | P0 | Med | In review (M7) | T1, T2 | +| T4 | Dependency-gated scheduling | P1 | Med | Planned | M7, T8 | +| T5 | Single failure transition; bounded compensation | P1 | High | Planned | T4 | +| T6 | Zero-target steps and empty runbooks terminate | P1 | Med | Planned | T4 | +| T7 | Runbook schema validation → 400; strict selectors | P1 | Med | Planned | none (serialize with T8 on `app.py`) | +| T8 | Per-run runbook spec snapshot | P1 | Med | Planned | T7 | +| T9 | Result persistence, claim attempt and lease, re-queue | P1 | High | Planned | M7, T5 | +| T10 | Working `shadowgate server` / `shadowgate agent` CLI | P1 | Med | Planned | M7 | +| T23 | Enqueue validation (target agent must exist) | P1 | Low | Planned | M7 | +| T11 | Transaction boundaries and connection serialization | P2 | High | Planned | M7 | +| T12 | Serialized, anchored, O(1) audit log | P2 | High | Planned | T11 | +| T13 | Artifact-bound, mandatory plugin verification | P2 | High | Planned | T10 | +| T14 | Transport identity (TLS / mTLS) decision and implementation | P2 | Med | Planned: **owner decision** | M7 | +| T15 | `data_dir` as base path; no CWD side effects | P2 | Med | Planned | T1 | +| T16 | Builtin action hardening | P2 | Med | Planned | none | +| T17 | Documentation truth sweep | P2 | Med | Planned | after T10, T13, T14 | +| T24 | Agent credential rotation / revocation (admin) | P2 | Med | Planned | M7 | +| T18 | Remove dead `models.py` and unused dependencies | P3 | Low | Planned | none | +| T19 | Structured logging with secret redaction | P3 | Med | Planned | M7 | +| T20 | Test infrastructure and reproducible CI | P3 | Med | Planned | none (conftest part pulled into M7) | +| T21 | Dashboard asset cleanup (HTMX, static) | P3 | Low | Planned | T3 | +| T22 | Bounded rate limiter, Retry-After, long-poll | P3 | High | Planned | T9, T11 | + +**Changes from the assessment's draft roadmap:** +- **T1, T2 and T3 are now one change set, M7.** Independent review showed that T2 on its own can be bypassed in the default open config: an anonymous caller can mint a token, enroll, and queue jobs, so an authenticated agent runs attacker jobs. +- **T15's import-time `app = create_app()` removal moved into T1.** Without it, fail-closed config would make every import of the module fail. +- **T20's `tests/conftest.py` moved into M7,** so the test fixture isn't copied a fifth time. +- **T23 and T24 were added** from review findings. + +### Owner decisions needed + +| # | Decision | Recommendation | +|---|---|---| +| OD1 | How do pre-existing agents (no credential after migration) get a credential? | **Admin mints an enrollment token bound to that `agent_id`; enrolling with it claims the row once.** Unbound tokens can only create *new* agents. (Rejected: "any token may claim a legacy id", which reopens S6.) | +| OD2 | How does a browser reach `/ui` once it needs auth? | **Accept the viewer token as the HTTP Basic password on `/ui*`** (browser-native prompt; read-only GETs, so no CSRF surface). Alternative: bearer-only, which leaves the dashboard unusable from a plain browser. | +| OD3 | Default credentials in `run.sh` (`admin-token`, …) | Keep them for loopback-only local dev and document them clearly. Alternative: generate random tokens into `.shadowgate/` (gitignored). | +| OD4 | T14 scope: implement mTLS, or remove the claim and require server-side TLS + agent tokens | Decide before T17. It does not block M7. | + +--- + +## 1. Prioritized backlog: task details + +Each task lists: + +- Problem +- Evidence +- Expected behavior +- Files +- Dependencies +- Approach +- Tests and validation +- Acceptance +- Risks +- Complexity + +The full M7 plan (T1–T3) is in §2. + +### P0 — Critical security + +**T1 · Fail-closed operator auth config** + +- **Problem:** The launcher's env var is ignored, and bad or empty token config opens every operator route. +- **Evidence:** `config.py:7,18`; `run.sh:6`; `app.py:65-73`; probes P1 and P2. +- **Expected:** + - `SHADOWGATE_API_TOKENS_JSON` (alias `SHADOWGATE_API_TOKENS`) is honored. + - Invalid JSON, a non-object, an unknown role, or a blank key aborts startup. + - An empty map is allowed only with `insecure_dev=true`, with a warning. + - Importing the module creates no files. +- **Files:** `config.py`, `server/app.py`, `run.sh`, `README.md`, `docs/threat-model.md`, tests. +- **Deps:** none. +- **Approach:** see §2. +- **Tests:** see §2 (T1-a … T1-f). +- **Acceptance:** see §4. +- **Risks:** + - Anything using `shadowgate.server.app:app` must switch to `--factory … :create_app`. + - Tests that relied on implicit open mode must set `insecure_dev=True`. +- **Cx:** Med. + +**T2 · Agent identity and job ownership** + +- **Problem:** Agent routes are anonymous; agent id and job id come from the request body; results can be forged, flipped, or sent for nonexistent jobs; re-enrollment overwrites existing agents. +- **Evidence:** `app.py:107-141`; `queue.py:80-85`; `store.py:80-86`; probes P3a–c, P4, P11. +- **Expected:** + - Each agent gets a credential that is shown once and stored hashed. + - Poll and result calls are bound to that credential. + - Completion is conditional on owner and state; retries are idempotent. + - Re-enrollment can't take over an agent. +- **Files:** `server/store.py`, `server/queue.py`, `server/app.py`, `agent/poll.py`, tests, docs. +- **Deps:** T1 (ships in the same change set). +- **Approach:** see §2. +- **Tests:** see §2 (T2-a … T2-p). +- **Acceptance:** see §4. +- **Risks:** + - Existing agents get 401 until re-provisioned (OD1). + - The `Poller` constructor changes. + - Five existing tests need updating. + - The shared-connection transaction hazard, which §2 avoids. +- **Cx:** High. + +**T3 · RBAC on every non-public route** + +- **Problem:** `/jobs`, `/runs/{id}` and `/ui*` are readable anonymously, and FastAPI's `/docs` and `/openapi.json` are public. +- **Evidence:** `app.py:168-218`; probe P3d. +- **Expected:** Every route needs a role except `/healthz`, `/`, `/enroll` (token-authorized) and `/agent/*` (agent-authorized). Docs are disabled unless `insecure_dev`. +- **Files:** `server/app.py`, tests. +- **Deps:** T1, T2. +- **Approach:** see §2. +- **Tests:** see §2 (T3-a … T3-d). +- **Acceptance:** see §4. +- **Risks:** + - Browser access to the dashboard (OD2). + - Route-inventory test upkeep. +- **Cx:** Med. + +### P1 — Essential functionality + +**T4 · Dependency-gated scheduling** + +- **Problem:** A dependent step is dispatched while its dependency is still running. +- **Evidence:** `runs.py:156-160` (refill loop schedules every step); probe P5. +- **Expected:** A step is scheduled only when all its `depends_on` steps are `done`. The cap holds across parallel branches. +- **Files:** `server/runs.py`, `tests/test_runs.py`. +- **Deps:** M7, T8 (both edit `runs.py`; serialize as T8 → T4 → T5 → T6). +- **Approach:** + - Move the readiness check into `_schedule` (deps done and step not terminal). + - Close finished steps before refilling. + - Compute capacity once per advance. +- **Tests:** + - P5 regression with 2 agents and spare capacity. + - Diamond DAG. + - `max_concurrent=1` with 3 agents. +- **Acceptance:** No successor job can be claimed while any predecessor target is pending or running. P5 reports "not reproduced". +- **Risks:** Changes the order of existing happy-path tests; `test_runs.py:55-65` may need reordering. +- **Cx:** Med. + +**T5 · Single failure transition; bounded compensation** + +- **Problem:** + - Every failed tracked job, including compensation jobs, re-runs `_fail_run`, which loops forever. + - Compensation runs for steps that never executed. + - Compensation is marked `done` when it is enqueued. +- **Evidence:** `runs.py:139-141,217-250`; probe P6. +- **Expected:** + - Exactly one `running→failed` transition (guarded `UPDATE … WHERE status='running'`). + - Compensation is enqueued once per (run, compensating step, agent), and only for targets that reported a result. + - Compensation results update compensation state and never re-fail the run. +- **Files:** `server/runs.py`, `tests/test_runs.py`. +- **Deps:** T4. +- **Approach:** + - Add a `compensations(run_id, step, agent_id, status)` table with a unique key. + - Branch `on_job_result` on whether the job is a compensation job. + - Cancel still-queued ordinary jobs of the failed run. +- **Tests:** + - Failing compensator. + - Two concurrent failures. + - A target that never executed. + - A late ordinary result after the run has failed. +- **Acceptance:** P6 reports "not reproduced". There is exactly one `run_failed` audit event per run, and compensation enqueue counts are bounded. +- **Risks:** Semantics of "executed" when an action may have partial side effects. Document that any reported attempt counts. +- **Cx:** High. + +**T6 · Zero-target steps and empty runbooks terminate** + +- **Problem:** A step matching no agents stays `pending`, and its run never finishes. +- **Evidence:** `runs.py:97-103,197-205`; probe P7. +- **Expected:** An eligible step with zero targets becomes `done` with zero executions. The run finalizes at a fixed point, including at start. +- **Files:** `server/runs.py`, `server/app.py` (the `/runs` response returns the persisted status), tests. +- **Deps:** T4. +- **Approach:** Add an `_advance_until_stable` loop called from `start_run` and `on_job_result`. +- **Tests:** + - `steps: []`. + - Unmatched root step. + - Unmatched middle step with a matched successor. + - No enrolled agents. +- **Acceptance:** P7 and P7b report "not reproduced". No phantom queue rows. +- **Risks:** An operator may expect a step with no matching agents to fail rather than succeed. Document the choice. +- **Cx:** Med. + +**T7 · Runbook schema validation** + +- **Problem:** + - Malformed runbooks return 500. + - An unknown selector key (e.g. the typo `tags:` instead of `tag:`) matches every agent. +- **Evidence:** `app.py:143-155`; `orchestrator.py:52-72,125-133`; probe P8. +- **Expected:** + - A Pydantic model with `extra="forbid"` validates the runbook before graph checks. + - Errors return 400 with field paths. + - `targets` allows only `tag`. +- **Files:** `server/orchestrator.py`, `server/app.py` (`/runbooks`), `tests/test_orchestrator.py`. +- **Deps:** none. Serialize the `app.py` edit after M7. +- **Approach:** Add `RunbookModel` / `StepModel`; `parse_runbook` returns the validated model converted to dataclasses. +- **Tests:** + - Missing fields. + - Wrong types. + - The `tags` typo. + - Valid example `examples/runbooks/disk-health-audit.yaml` still accepted. + - A rejected spec is not persisted. +- **Acceptance:** P8 returns 400 on all four cases. C4 typo is rejected. +- **Risks:** Rejects runbooks that are accepted today (intended). +- **Cx:** Med. + +**T8 · Per-run spec snapshot** + +- **Problem:** In-flight runs re-read a runbook definition that may have been replaced. +- **Evidence:** `runs.py:44-48,149,221`. +- **Expected:** `runs.spec` stores the spec accepted at start; scheduling and compensation read only the snapshot. +- **Files:** `server/runs.py`, tests. +- **Deps:** T7. +- **Approach:** + - Add a column via the same `PRAGMA table_info` migration pattern as M7. + - Legacy runs fall back to the named spec and are flagged. +- **Tests:** + - Re-register during an active run. + - Two runs of the same name with different specs. +- **Acceptance:** Editing a runbook doesn't change any active run. +- **Risks:** A legacy active run has no snapshot. +- **Cx:** Med. + +**T9 · Result persistence, attempts, leases** + +- **Problem:** + - Result `data` is dropped. + - Claimed jobs never expire. + - The Poller loses results on transport errors. +- **Evidence:** `queue.py:80-85`; `poll.py:23-37`; probe P9. +- **Expected:** + - `qjobs` gains `result`, `error`, `completed_at`, `attempt`, `lease_expires_at`. + - Completion is fenced by `attempt`. + - Expired leases are re-queued, up to a retry cap. + - Results are readable by viewers. +- **Files:** `server/queue.py`, `server/app.py`, `agent/poll.py`, `server/runs.py`, tests. +- **Deps:** M7, T5 (and T11 for atomicity). +- **Approach:** + - The claim returns `attempt`, and the result echoes it. + - A lease sweep runs on each poll. + - Bound the payload size. +- **Tests:** + - Payload stored. + - Stale-attempt result rejected. + - Expiry and re-queue. + - Dropped acknowledgement then retry. +- **Acceptance:** P9 reports "not reproduced". A late result from an older attempt cannot overwrite a newer one. +- **Risks:** Re-running actions that are not idempotent. Mark actions as retry-safe. +- **Cx:** High. + +**T10 · Working CLI** + +- **Problem:** Every subcommand prints "not yet wired" and exits 0, so the agent can't be run. +- **Evidence:** `cli/main.py:19`. +- **Expected:** + - `shadowgate server` starts the factory app with validated settings. + - `shadowgate agent` reads its id, server URL and credential from a 0600 config file, loads the builtins only, and runs the Poller. + - Placeholders exit non-zero. +- **Files:** `cli/main.py`, `agent/poll.py`, `run.sh`, tests. +- **Deps:** M7. +- **Approach:** Keep argparse; inject the uvicorn runner and the Poller so tests can replace them; no external plugin loading until T13. +- **Tests:** + - Dispatch with monkeypatched `uvicorn.run` and `Poller.run`. + - Missing credential file exits non-zero. + - `--version`. +- **Acceptance:** An end-to-end local smoke test works: server, enroll, agent, job, result. +- **Risks:** Secret handling: never pass the credential as an argument. +- **Cx:** Med. + +**T23 · Enqueue validation** + +- **Problem:** `/jobs` accepts any `agent_id`, so a typo produces a job nobody can ever claim. +- **Evidence:** `app.py:116-124`; `qjobs` has no foreign key (`queue.py:36-42`). +- **Expected:** 404 for an unknown agent. +- **Files:** `server/app.py`, `server/store.py`, tests. +- **Deps:** M7. +- **Approach:** Check that the agent exists before enqueueing. +- **Tests:** unknown agent → 404; known agent → 200. +- **Acceptance:** As tested. +- **Risks:** Minimal. +- **Cx:** Low. + +### P2 — Important improvements + +**T11 · Transaction boundaries** + +- **Problem:** + - One sqlite connection is shared across the threadpool with no lock. + - Business operations are split across several commits. + - The audit log is written outside the database. +- **Evidence:** `store.py:24`; `runs.py:108-122`; sqlite3 docs on `check_same_thread`. +- **Expected:** A store-wide `RLock` or per-operation connections; one transaction per business operation; no nested helper commits. +- **Files:** `store.py`, `queue.py`, `runs.py`, `audit.py`. +- **Deps:** M7. +- **Approach:** A unit-of-work context manager; helpers take a connection or cursor and don't commit. +- **Tests:** + - Inject a failure between the old commit points. + - Multithreaded `TestClient` load. +- **Acceptance:** No orphan jobs, no partial enrollments, no `cannot start a transaction` errors. +- **Risks:** Wide refactor; deadlocks if the lock is held during audit file I/O. +- **Cx:** High. + +**T12 · Audit integrity and performance** + +- **Problem:** + - Deleting the newest entries goes undetected. + - Concurrent appends can fork the chain. + - Each append is O(n). +- **Evidence:** `audit.py:35-76`; probe P10. +- **Expected:** + - A single serialized writer with the head cached. + - A periodic signed head checkpoint stored separately. + - `verify` reports how far it verified, and any corruption. +- **Files:** `server/audit.py`, `server/app.py` (`/audit`), tests. +- **Deps:** T11. +- **Approach:** A lock plus head state recovered at startup; checkpoints signed with the org ed25519 key. +- **Tests:** + - 8-thread concurrent appends. + - Tail, middle and reorder deletion. + - A corrupt line. +- **Acceptance:** P10 reports "not reproduced" up to the latest checkpoint. +- **Risks:** Truncation after the last checkpoint is still undetectable. Document it. +- **Cx:** High. + +**T13 · Artifact-bound plugin verification** + +- **Problem:** + - A signed manifest isn't bound to the package's code. + - The gate is optional and never called. +- **Evidence:** `gate.py:47-57`; `loader.py:20-31`; gate probe. +- **Expected:** + - The manifest signs the distribution name, version, entry points, and a sha256 of each installed file. + - Verification happens before `ep.load()`. + - The gate is mandatory and wired into the agent. +- **Files:** `crypto/signing.py`, `plugins/gate.py`, `plugins/loader.py`, `cli/main.py`, tests. +- **Deps:** T10. +- **Approach:** A versioned manifest schema; remove the default `allow=None`. +- **Tests:** + - Unsigned manifest. + - Tampered manifest. + - **Transplanted** manifest. + - Modified file. + - Extra module. + - Changed entry point. +- **Acceptance:** The gate probe returns False. Rejected plugins never reach `ep.load`. +- **Risks:** Packaging layouts (wheels vs editable installs). +- **Cx:** High. + +**T14 · Transport identity (OD4)** + +- **Problem:** The docs promise mTLS but there is no TLS at all. +- **Evidence:** `crypto/mtls.py` is unused; `run.sh:21`. Per the Uvicorn docs, its client-cert requirement defaults to `CERT_NONE`, and ASGI peer-cert exposure is not guaranteed. +- **Expected:** + - **Option A:** server-authenticated HTTPS plus T2 agent tokens; mTLS claims removed. + - **Option B:** mTLS at a TLS-terminating proxy, which forwards a verified identity bound to `agents.cert_fingerprint`. +- **Files:** `crypto/mtls.py`, `agent/poll.py`, docs, config. +- **Deps:** M7. +- **Approach:** Per decision. `require_agent` is the single place to change. +- **Tests:** + - Plaintext rejected for non-loopback. + - Untrusted server cert rejected. +- **Acceptance:** The docs match the delivered transport. +- **Risks:** Deployment complexity. +- **Cx:** Med. + +**T15 · Paths and CWD side effects** + +- **Problem:** `data_dir` doesn't relocate the database or audit log; relative paths depend on the working directory. +- **Evidence:** `config.py:9-15`. +- **Expected:** Default paths resolve under `data_dir`; explicit absolute paths are honored. +- **Files:** `config.py`, `store.py`, tests. +- **Deps:** T1. +- **Approach:** A Pydantic `model_validator` derives the paths. +- **Tests:** + - Custom `data_dir`. + - Read-only CWD. + - Legacy CWD database detected and warned about. +- **Acceptance:** Starting from any directory uses the same data. +- **Risks:** Existing `./shadowgate.db` is orphaned; warn about it. +- **Cx:** Med. + +**T16 · Builtin action hardening** + +- **Problem:** + - `file_fetch` reads the whole file and accepts any path. + - `service_status` always reports `ok`. + - `disk_health` takes any path and can divide by zero. +- **Evidence:** `plugins/builtin/*.py`. +- **Expected:** + - Configured allowed roots. + - Bounded reads. + - Unit names validated. + - Errors distinguished from "inactive". +- **Files:** `plugins/builtin/*`, `agent/executor.py`, tests. +- **Deps:** none. +- **Approach:** A shared param validation helper; `open()` plus `read(limit)`. +- **Tests:** + - Boundary limits. + - Escape via symlink. + - Mocked subprocess outcomes. +- **Acceptance:** As tested. +- **Risks:** Behavior change for current callers. +- **Cx:** Med. + +**T17 · Documentation truth sweep** + +- **Problem:** README, architecture and threat model claim features that don't exist. +- **Evidence:** Assessment §6. +- **Expected:** Every claim matches the delivered code; deferred items are labelled. +- **Files:** `README.md`, `docs/*.md`, the `store.py` docstring. +- **Deps:** after T10, T13, T14. Small contract docs ship with each task. +- **Approach:** Doc review against the tracker. +- **Tests:** Run the quickstart commands as a local smoke test. +- **Acceptance:** No statement contradicts the code. +- **Risks:** none. +- **Cx:** Med. + +**T24 · Credential rotation and revocation** + +- **Problem:** After M7 a leaked agent credential can't be revoked without editing the database by hand. +- **Evidence:** Independent review of the T2 plan. +- **Expected:** Admin `POST /agents/{id}/revoke` sets the hash to NULL and audits it; re-provisioning uses a bound token (OD1). +- **Files:** `app.py`, `store.py`, tests. +- **Deps:** M7. +- **Approach:** A conditional update plus an audit event. +- **Tests:** Revoke → 401 on poll; bound re-enroll works. +- **Acceptance:** As tested. +- **Risks:** none significant. +- **Cx:** Med. + +### P3 — Optional enhancements + +**T18 · Dead code and dependencies** + +- **Problem:** `server/models.py` is unused and has a conflicting schema. Four dependencies are unused (SQLAlchemy, aiosqlite, itsdangerous, python-multipart). +- **Evidence:** `models.py`; `pyproject.toml:9-22`. +- **Expected:** Removed; Starlette declared directly or imported via FastAPI. +- **Files:** `models.py`, `pyproject.toml`, `uv.lock`. +- **Deps:** none. +- **Approach:** Delete and re-lock. +- **Tests:** Clean wheel install, then the suite. +- **Acceptance:** Green, with smaller dependencies. +- **Risks:** Breaks any external import of `models`. +- **Cx:** Low. + +**T19 · Logging** + +- **Problem:** There is no logging anywhere, and exceptions are swallowed. +- **Evidence:** `grep logging src` finds nothing. +- **Expected:** Standard loggers; startup mode, auth failures and recovery problems are logged; secrets redacted. +- **Files:** `app.py`, `poll.py`, `executor.py`, `runs.py`. +- **Deps:** M7. +- **Approach:** A module logger per file, configured in the CLI. +- **Tests:** `caplog` checks for redaction. +- **Acceptance:** No secret appears in logs. +- **Risks:** Low. +- **Cx:** Med. + +**T20 · Test infrastructure and CI** + +- **Problem:** The fixture is copied four times; tests aren't type-checked; CI has no `--frozen` and no coverage. +- **Evidence:** `tests/*`; `ci.yml`. +- **Expected:** `conftest.py` (lands in M7); mypy covers tests; `uv sync --frozen`; coverage reported. +- **Files:** `tests/conftest.py`, `pyproject.toml`, `ci.yml`. +- **Deps:** none. +- **Approach:** Incremental. +- **Tests:** CI green from a fresh checkout. +- **Acceptance:** As described. +- **Risks:** none. +- **Cx:** Med. + +**T21 · Dashboard assets** + +- **Problem:** HTMX is loaded from unpkg without SRI and never used; `web/static` is empty and not mounted. +- **Evidence:** `base.html:6`. +- **Expected:** The script is removed and the static claim dropped. +- **Files:** `templates/base.html`, `README.md`. +- **Deps:** T3. +- **Approach:** Deletion. +- **Tests:** Pages render under viewer auth with no external script. +- **Acceptance:** As tested. +- **Risks:** none. +- **Cx:** Low. + +**T22 · Rate limiter and long-poll** + +- **Problem:** The rate limiter's memory grows without bound and 429s carry no Retry-After; polling is short-poll. +- **Evidence:** `app.py:84-93`; `poll.py:30-37`. +- **Expected:** + - Bounded keys, with Retry-After on 429. + - Optional capped wait on poll. +- **Files:** `app.py`, `poll.py`, `config.py`. +- **Deps:** T9, T11. +- **Approach:** An LRU-bounded window; the wait happens outside the database transaction. +- **Tests:** + - Key churn. + - 429 includes Retry-After. + - Wait and cancel. +- **Acceptance:** As tested. +- **Risks:** Threadpool exhaustion from long waits. +- **Cx:** High. + +--- + +## 2. First task: M7 trust boundary (T1 + T2 + T3), detailed plan + +### Why this first + +1. **Everything else depends on it.** Job ownership, result integrity, run transitions, compensation triggers and audit attribution all assume the caller is known. Today nobody is authenticated: S1 on agent routes, S2 and S3 on operator routes. +2. **It has to ship as one change set.** Independent review showed that shipping T2 without T1 and T3 can be bypassed end to end in the default config (anonymous `/tokens` → `/enroll` → `/jobs`). Shipping T1 without T2 still leaves `/agent/*` anonymous. +3. **Fixing the run engine first would protect nothing.** T4–T6 would only produce correct state transitions that anyone can still forge. +4. **It is contained.** It touches 6 source files and 6 test files, needs no new dependencies (stdlib `secrets`, `hashlib`, `hmac`), and is fully testable with `TestClient`. + +### Order of work inside M7 (one owner per file at a time) + +T1 → T2 → T3. All three edit `server/app.py`, so they are serial edits by one implementer. + +### T1 — Fail-closed operator configuration + +1. **`config.py`** + - `api_tokens_json: str = Field("", validation_alias=AliasChoices("SHADOWGATE_API_TOKENS_JSON", "SHADOWGATE_API_TOKENS"))`. + - Use full names; with an alias, pydantic-settings does not apply `env_prefix` (verified against the pydantic-settings docs). + - Add `populate_by_name=True` so `Settings(api_tokens_json=…)` in tests still works. +2. **`app.py`: `_parse_token_roles(settings) -> dict[str, str]`** + - `json.loads`; require a dict with non-blank `str` keys and values in `{viewer, operator, admin}`. + - Otherwise raise `ValueError` without echoing token values. + - An empty map is allowed only if `settings.insecure_dev`; emit `warnings.warn` / logging. + - `create_app` calls it **before** creating any files. +3. **Remove the module-level `app = create_app()`** at `app.py:223`. + - `run.sh` uses `uvicorn --factory shadowgate.server.app:create_app`. + - `run.sh` exports `SHADOWGATE_API_TOKENS_JSON` (OD3: keep the loopback dev tokens). +4. **Agent authentication stays enforced** even in `insecure_dev`. + +### T2 — Agent identity and job ownership + +**Contract** + +| Element | Decision | +|---|---| +| **Credential** | `secrets.token_urlsafe(32)` (256 bits), returned once as `agent_token`. The DB stores `sha256(token)` hex in `agents.secret_hash`, with a unique index (SQLite allows multiple NULLs). No KDF: the value is high-entropy and random, not a password (Python `hashlib`/`secrets` docs). | +| **Header** | `X-ShadowGate-Agent-Token`. Operator `Authorization: Bearer` never satisfies agent auth, and the agent header never satisfies operator auth. | +| **Owner** | `qjobs.agent_id`, with no new column. Claims are already scoped to it. T9 adds `attempt` for fencing. | + +**Enrollment tokens and OD1** + +- `POST /tokens` (admin) accepts an optional body `{"agent_id": "..."}` and stores it in the existing `enroll_tokens.agent_id` column at mint time. +- **Unbound token:** can only **insert** a new agent. If the id exists → 409. +- **Bound token:** the request `agent_id` must equal the bound id, otherwise 403. Then: + - id absent → insert; + - id present with `secret_hash IS NULL` (legacy) → `UPDATE … WHERE id=? AND secret_hash IS NULL`, tags unchanged unless supplied; + - id has a credential → 409. + +**`/enroll` (`require_role("admin")` removed; rate limit kept)** + +- Runs `Store.enroll_agent(agent_id, token, tags) -> EnrollOutcome` on a **dedicated short-lived connection**: `sqlite3.connect(path, timeout=5)`, `BEGIN IMMEDIATE`, then commit or rollback, then close. +- Order inside the transaction: + 1. Validate and burn the token (`UPDATE … WHERE token=? AND burned_at IS NULL AND expires_at>?`). On failure → `invalid_token`, **403**, checked before any id lookup so nothing about agent existence leaks. + 2. Check the binding. + 3. Insert, or conditionally update, the agent. + 4. On conflict → roll back, so the token is **not** burned → **409**. +- Success → 200 `{status, agent_id, agent_token}`, with `Cache-Control: no-store`. +- Audit `agent_enrolled` with detail `{"tags", "bound": bool}`. Never include the secret. +- The audit write happens after commit. + +**Store changes** + +- `PRAGMA busy_timeout` moves before `_setup()`. +- `CREATE TABLE agents` gains `secret_hash TEXT`. +- Migration: if `PRAGMA table_info(agents)` lacks the column → `ALTER TABLE … ADD COLUMN`, create the index, commit. +- New `authenticate_agent(token) -> str | None`: look up by sha256 digest. +- `upsert_agent` is removed; its only caller was `/enroll`. + +**`require_agent` dependency** + +- Missing, empty, or unknown header → 401 `{"detail": "invalid agent credential"}`. +- No audit entry on success, so the exact event list asserted at `test_server.py:52` is unchanged. + +**`/agent/poll`** + +- The body is optional and `PollRequest.agent_id` is removed (Pydantic ignores unknown fields, so old bodies still parse). +- Claims via `claim_next(agent_id=)`. +- The audit actor is the authenticated id. + +**`SqlQueue.claim_next(agent_id: str)`** + +- The scoped branch is the only one; the unscoped `agent_id=None` branch is **deleted**. + +**`SqlQueue.complete(job_id, *, agent_id, success, data) -> CompletionOutcome`** + +- The enum values are `accepted`, `duplicate`, `not_found` and `conflict`. The name avoids clashing with `ResultRequest.ok`. +- First: `UPDATE qjobs SET status=? WHERE id=? AND agent_id=? AND status='running'`. rowcount 1 → `accepted`. +- Otherwise read `agent_id, status` for that id: + - missing, or another owner → `not_found`; + - own job, terminal, same outcome → `duplicate`; + - own job, terminal, different outcome, or still `queued` → `conflict`. + +**`/agent/result`** + +| Outcome | HTTP | Side effects | +|---|---|---| +| `accepted` | 200 `recorded` | Audit `job_completed` (actor = agent), then `engine.on_job_result` | +| `duplicate` | 200 `duplicate` | None | +| `not_found` | 404 | None. Unknown and foreign jobs return the same code. | +| `conflict` | 409 | None | + +Rejected results get no audit entry in M7. An audit event for rejected results is deferred to T19/T12 to avoid audit volume on the O(n) appender. + +**`agent/poll.py`** + +- `Poller(executor, server_url, agent_token, poll_interval=1.0)`, keyword `agent_token` required. +- `httpx.Client(headers={"X-ShadowGate-Agent-Token": …})`. +- The poll body is `{}`. +- Check the result response: + - 200 → done; + - 401/403 → raise `AgentAuthError`, and `run()` stops; + - other errors → keep the result and retry the POST with backoff before polling again. + +**No changes needed:** `server/runs.py`, which only sees accepted results; `pyproject.toml`, which needs no new dependencies. + +### T3 — Route authorization + +- Use `APIRouter(dependencies=[Depends(require_role("viewer"))])` for all read routes: `/agents`, `/jobs`, `/runs/{id}`, `/audit`, `/ui*`. Keep explicit higher roles on mutations. +- Public routes: `/healthz` and `/` (redirect only). +- `/enroll` is token-authorized; `/agent/*` is agent-authorized. +- `FastAPI(docs_url=None, redoc_url=None, openapi_url=None)` unless `insecure_dev`. +- **OD2:** `require_role` also accepts `Authorization: Basic` where the password is a configured token. On `/ui*` only, a 401 response carries `WWW-Authenticate: Basic realm="shadowgate"` so the browser prompts. +- The route inventory test enumerates `app.routes` so new routes are covered automatically. + +### Files (single owner during M7) + +| File | Change | +|---|---| +| `src/shadowgate/config.py` | Token alias, `populate_by_name` | +| `src/shadowgate/server/app.py` | Token parsing, factory, `require_agent`, `/tokens`, `/enroll`, `/agent/*`, routers, docs off, Basic auth on `/ui` | +| `src/shadowgate/server/store.py` | Migration, `enroll_agent`, `authenticate_agent`, `mint_token(agent_id=None)`, busy_timeout order | +| `src/shadowgate/server/queue.py` | Scoped-only `claim_next`; `complete` returns an outcome | +| `src/shadowgate/agent/poll.py` | Header, response handling, `AgentAuthError` | +| `run.sh` | Correct env var, `--factory` | +| `tests/conftest.py` (new) | `settings`/`client` fixtures, `admin_h`/`op_h`/`view_h`, `enroll()` → token | +| `tests/test_agent_auth.py` (new) | T2 cases | +| `tests/test_config_auth.py` (new) | T1 cases | +| `tests/test_auth.py` | T3 route inventory, cross-domain credential cases | +| `tests/test_server.py`, `tests/test_runs.py`, `tests/test_queue.py` | Adapt to credentials and the new signatures | +| `README.md`, `docs/threat-model.md`, `docs/architecture.md` | Env var, enroll response, agent header, factory launch; state that agent auth depends on fail-closed operator auth | + +### Tests and validation procedure + +**Existing tests that change** (independent plan review; 5 of 17 would otherwise fail): + +- `test_server.py::test_job_lifecycle_and_audit` and `::test_poll_only_claims_own_jobs`: send the agent header; keep the exact event list. +- `test_runs.py::_enroll`: returns the token. `::test_run_fanout_ordering_and_audit` and `::test_failure_triggers_compensation`: send the agent header. +- `test_queue.py::test_concurrent_claim_exactly_once`: one agent id per worker (or a shared id with scoped claims); `complete(..., agent_id=…)`; add a wrong-owner check. +- Fixtures that relied on open mode set `insecure_dev=True` explicitly. + +**New tests, T1** (`tests/test_config_auth.py`) + +| ID | Test | +|---|---| +| T1-a | invalid JSON → `create_app` raises | +| T1-b | `'["a"]'` and `'{"t":"root"}'` → raise | +| T1-c | empty map with `insecure_dev=False` → raises; with `True` → starts and warns | +| T1-d | env `SHADOWGATE_API_TOKENS_JSON` → RBAC on; anonymous `POST /tokens` → 401 | +| T1-e | env alias `SHADOWGATE_API_TOKENS` → same result | +| T1-f | importing `shadowgate.server.app` in an empty temp CWD creates no files | + +**New tests, T2** (`tests/test_agent_auth.py`) + +| ID | Test | +|---|---| +| T2-a | enroll with a valid token and no bearer → 200 plus `agent_token`; `Cache-Control: no-store` | +| T2-b | the database stores `sha256(token)`; the plaintext appears in neither the database file nor `audit.log` | +| T2-c | re-enroll an existing credentialed id → 409; that token is still unburned and usable for a new id | +| T2-d | garbage token for an existing id → 403, not 409 (no existence oracle) | +| T2-e | bound token used with a different id → 403 | +| T2-f | legacy migration: old-schema DB with one agent → `Store()` adds the column; the agent gets 401 on poll; a bound token reclaims it; an unbound token → 409 | +| T2-g | two concurrent enrolls for the same id (threads) → exactly one 200 and one 409 | +| T2-h | poll or result without a header → 401; no `job_claimed` / `job_completed` audit entries | +| T2-i | agent B's credential polls → never receives A's job; A's job stays `queued` | +| T2-j | B posts a result for A's running job → 404; status still `running`; no audit entry | +| T2-k | forged failure by B for A's runbook job → run still `running`; no `compensation_enqueued` | +| T2-l | A posts a result twice with the same `ok` → 200 `recorded` then 200 `duplicate`; exactly one `job_completed` | +| T2-m | A posts `ok:true` then `ok:false` → 409; status stays `done` | +| T2-n | result for an unknown job id → 404; audit count unchanged | +| T2-o | operator bearer used as the agent header → 401; agent token used as the operator bearer → 401 | +| T2-p | Poller with `httpx.MockTransport`: sends the header; treats `duplicate` as success; raises `AgentAuthError` on 401; retries the result after a 500 (no network) | + +**New tests, T3** (`tests/test_auth.py`) + +| ID | Test | +|---|---| +| T3-a | parametrized over `app.routes` with RBAC configured: everything except `/healthz`, `/`, `/enroll` and `/agent/*` → 401 without credentials | +| T3-b | viewer can GET all reads; viewer → 403 on `POST /jobs`, `/runbooks`, `/tokens`; operator → 403 on `/tokens`, `/runbooks` | +| T3-c | `/ui` with Basic `:` → 200; anonymous → 401 with `WWW-Authenticate: Basic` | +| T3-d | `/docs` and `/openapi.json` → 404 when not `insecure_dev` | + +**Validation procedure** (coordinator; no installs into the repo's `.venv`) + +1. `git stash list` and `git status` show no unrelated changes. Record the baseline: 17 passed. +2. Write the new failing tests first, then run them on unmodified `b9f2183`. They must fail for the stated reason; record the output. +3. Apply T1, then T2, then T3. Run the full suite after each. +4. `ruff check src tests` and `mypy` (strict) are clean, run from the isolated venv. +5. Re-run the assessment probes for P1, P2, P3a–d, P4 and P11 (now covered by tests; see the probe table in the assessment). They must report "not reproduced"; P5–P10 are unchanged (later tasks). +6. Smoke test against a local loopback server: + - `run.sh`; + - anonymous `/tokens` → 401; + - admin mints a token, enroll, use the agent token; + - operator enqueues a job; + - poll and result with the header; + - `/audit?verify=true` → `verified: true`. +7. An independent reviewer checks the diff. Findings are resolved or recorded here. + +--- + +## 3. Working practice + +M7 was built with a few rules that are worth keeping for later tasks: + +| Role | Responsibility | Writes | +|---|---|---| +| Coordinator | Sequencing, running the validation steps, keeping this tracker | `docs/tracker.md` | +| Implementation | Source changes, in the order T1 → T2 → T3 | `src/shadowgate/**`, `run.sh` | +| Tests | New and adapted tests, written **before** the source changes | `tests/**` | +| Documentation | Contract docs, after the code freeze | `README.md`, `docs/architecture.md`, `docs/threat-model.md` | +| Independent review | Plan review before coding; diff review for regressions and maintainability | read-only | +| Reference research | Checking library behavior against official documentation | read-only | + +**Rules:** +- One writer per file at a time. +- Tests first: new tests must fail on the baseline for the stated reason. +- Every finding needs evidence: an executed check, or a `path:line` citation. +- The order is: tests, confirm they fail on the baseline, implementation, full validation, docs, independent review, tracker update. + +--- + +## 4. Test and acceptance checklist: M7 + +**T1** + +- [ ] With default env, `run.sh` gives anonymous `POST /tokens` → 401. +- [ ] Invalid, ill-typed, or unknown-role token config makes startup fail with a clear error that contains no secrets. +- [ ] An empty token map starts only with `insecure_dev=true`, and logs a warning. +- [ ] Importing `shadowgate.server.app` creates no files. + +**T2** + +- [ ] `/enroll` works with a valid one-time token and no bearer. It returns `agent_token` once, with `no-store`. +- [ ] Only the sha256 of the token is stored. The plaintext is absent from the database and the audit log. +- [ ] Credentialed id → 409 with the token unburned. Invalid token → 403 regardless of id. A bound token with the wrong id → 403. +- [ ] Legacy database migrates. Legacy agents get 401 until a bound token reclaims them. Unbound tokens cannot reclaim. +- [ ] The concurrent same-id enroll race yields exactly one success. +- [ ] `/agent/poll` and `/agent/result` return 401 without a valid agent header. Operator and agent credentials are not interchangeable. +- [ ] No agent can claim, complete, or fail another agent's job (404, state unchanged, no audit entry, no run effect). +- [ ] A same-owner identical retry → 200 `duplicate` with no side effects. A conflicting retry → 409. Unknown job → 404. +- [ ] The Poller sends the header, handles `duplicate`, stops on 401/403, and retries the result after transient errors. + +**T3** + +- [ ] Every route except `/healthz`, `/`, `/enroll` and `/agent/*` returns 401 without credentials (route-inventory test). +- [ ] Role boundaries hold: viewer < operator < admin. +- [ ] The dashboard is reachable in a browser via the Basic prompt with a viewer token. +- [ ] `/docs` and `/openapi.json` are disabled outside `insecure_dev`. + +**Change set** + +- [ ] P1, P2, P3a–d, P4 and P11 report "not reproduced". P5–P10 are unchanged and tracked to T4–T12. +- [ ] Full suite green (17 existing tests, adapted, plus new), ruff clean, `mypy --strict` clean. +- [ ] Docs updated: env var, enroll contract, agent header, factory launch. + +--- + +## 5. Definition of Done (every task) + +1. **Scope:** only the files listed for the task changed. No unrelated edits. No writes to the repo's `.venv` or lockfile unless the task says so. +2. **Test first:** a regression test fails on the pre-change commit for the cited reason (finding or probe ID) and passes afterwards. +3. **Negative cases:** at least one negative and one boundary case. Assertions check the HTTP status, the database state, and the exact audit events, not just "no exception". +4. **Existing tests:** adapted where the contract intentionally changed, never deleted to make the suite pass. +5. **Green:** the full pytest suite, `ruff check src tests`, and strict `mypy` pass in a venv built with `uv sync --frozen --extra dev`. +6. **Security hygiene:** no secret in logs, audit details, exception messages, or URLs. New routes have an explicit auth decision covered by the route-inventory test. +7. **Migration:** any schema change works on both a fresh and a pre-existing database, with a test. +8. **Docs:** any changed contract (env var, endpoint, status code, header, schema) is documented in the same change set. +9. **Review:** an independent review is complete. Blocking findings are fixed; others are recorded in this tracker. +10. **Tracker:** the status moves to `Done` with a note of the evidence (test names, probe results). Nothing is committed or pushed without the owner's explicit instruction. + +--- + +## 7. M7 implementation record (2026-11-30) + +**Status:** implemented and verified in the working tree on top of `b9f2183`. **Not committed.** + +### Files + +**Modified** +- `src/shadowgate/config.py` +- `src/shadowgate/server/app.py` +- `src/shadowgate/server/store.py` +- `src/shadowgate/server/queue.py` +- `src/shadowgate/agent/poll.py` +- `run.sh` +- `tests/test_auth.py`, `tests/test_server.py`, `tests/test_runs.py`, `tests/test_queue.py` +- `README.md`, `docs/architecture.md`, `docs/threat-model.md` + +**New** +- `tests/conftest.py` +- `tests/test_agent_auth.py` +- `tests/test_config_auth.py` + +### Evidence (Verified, run in an isolated venv built with `uv sync --frozen --extra dev`) + +| Check | Result | +|---|---| +| pytest | **61 passed** (baseline 17; 7 warnings = the intended `insecure_dev` warning plus the upstream Starlette/httpx deprecation) | +| `ruff check src tests` | clean | +| `mypy --strict` | clean (32 files) | +| `bash -n run.sh` | ok | +| Test-first check | New tests copied onto a pristine `b9f2183` source tree. **T1:** 5 of 6 fail; T1-d passes on both, as a regression guard for the already-correct variable name. **T2:** the module can't import on the baseline (`AgentAuthError` doesn't exist). **T3:** a, c and d fail; b passes on both, as a guard for existing role boundaries. The 5 adapted legacy tests fail on the baseline. | +| Probes | M7 re-run of the trust-boundary probes: **18/18 "not reproduced"** (P1, P2, P2b, P3a/a′, P3b/b′/b″, P3c, P3d ×7, P4, P11). The same behaviors are pinned by the T1–T3 tests. | +| Smoke test | Real Uvicorn `--factory` server on 127.0.0.1. Anonymous `/tokens` → 401 · enroll → `agent_token` with `Cache-Control: no-store` · poll and result with the agent header → `recorded`, then `duplicate` on retry · anonymous `/ui` → 401 with `WWW-Authenticate: Basic` · Basic with viewer token → 200 · `/audit?verify=true` → `True` · only the SHA-256 is stored · startup with invalid token JSON → exit 1 | + +### Review + +- **Architecture review:** architecturally consistent. Agent auth is isolated in `require_agent` and `Store.authenticate_agent`, ready for T14. +- **Independent review (first pass):** GO, with 1 blocking finding. + - **F1, fixed:** the Poller's handling of 200 and non-JSON responses. + - **Also fixed:** F4 (reclaim preserves tags), F6 (`:` and whitespace in token keys rejected), F9–F11 (non-vacuous tests), docs drift, and the `{}` mint. + - The strengthened T3-a test exposed that FastAPI 0.142 nests included routers (`_IncludedRouter`). The original inventory test had never covered the read routes; it now walks them recursively. +- **Independent review (second pass):** all fixes confirmed, no new blocking issue. + - **Obs. 1, fixed:** the reclaim audit entry now records the stored tags and `reclaimed`. + - **Obs. 3, fixed:** a malformed `job` from the server is ignored instead of crashing the Poller. + +### Known limitations and follow-ups (not fixed in M7) + +| # | Item | Goes to | +|---|---|---| +| F2 | If the audit append fails after the enrollment commit, the caller gets a 500 and the one-time secret is lost. The id is then credentialed but unrecoverable. | T11 / T12 (+ T24) | +| F3 | `db_path=":memory:"` breaks enrollment, because enrollment opens a second connection. | T15 | +| F5 | No rotation or revocation of agent credentials. | T24 | +| F7 | No minimum operator-token length (conflicts with the OD3 dev tokens). | T1 follow-up, decide with OD3 | +| F8 | Operator tokens are compared with a dict lookup, not in constant time. | T19 / T1 follow-up | +| R-obs 2 | `poll_once` returns `True` while a failed result is still pending. | T9 | +| R-obs 4 | Non-401/403 4xx results are dropped, including transient 408/429. | T9 / T22 | +| Engine gap | If `engine.on_job_result` raises after the job is marked terminal, a retried result returns `duplicate` and the run never advances. Pre-existing; now more visible. | T4 / T5 / T11 | +| Lifecycle | The shared Store connection is never closed (ResourceWarning in tests). Pre-existing. | T15 | +| Transport | Agent tokens travel as bearer secrets over plain HTTP outside loopback. | T14 (OD4) | + +### Acceptance checklist (§4) + +All items are met and verified by the tests above. + +**T1** +- Anonymous `/tokens` → 401 with the `run.sh` defaults. (smoke test, T1-d/e) +- Invalid, ill-typed, unknown-role, or blank/colon/space token keys abort startup. (T1-a/b, smoke test) +- An empty map runs only with `insecure_dev`, and warns. (T1-c) +- Importing the module creates no files. (T1-f) + +**T2** +- `agent_token` is returned once, with `no-store`. (T2-a) +- Only the hash is stored; it is absent from the DB, WAL and audit log. (T2-b) +- 409 leaves the token unburned; invalid token → 403 before any id lookup; bound token with the wrong id → 403. (T2-c/d/e) +- Legacy migration and bound reclaim; unbound tokens cannot reclaim; tags are preserved. (T2-f) +- Enrollment races (unbound and bound) yield exactly one winner. (T2-g/g2) +- Agent routes require a credential; operator and agent credentials aren't interchangeable. (T2-h/o) +- No cross-agent claim, completion, or run failure. (T2-i/j/k) +- Duplicate result → 200 `duplicate`; conflicting result → 409; unknown job → 404. (T2-l/m/n) +- Poller behavior. (T2-p) +- Expired token → 403; `{}` mint works; malformed result → 422. (T2-q/r/s) + +**T3** +- The route inventory, including nested routers, returns 401 everywhere expected. (T3-a) +- Role boundaries hold. (T3-b) +- Basic auth on the dashboard, with the challenge header. (T3-c) +- Docs are disabled outside `insecure_dev`. (T3-d) + +**Change set** +- Probes are fixed. Suite, ruff and mypy are green. Docs are updated. + +## 8. M7 verification record: Phase 4 (2026-11-30) + +**Status: PASS WITH ISSUES.** +- Every M7 acceptance item (§4) passes, and no security-boundary bypass was found. +- One M7-introduced **High** reliability defect (V1) and three Medium issues (V2–V4) remain. They are non-blocking for a commit, because no runnable agent ships yet (T10). +- They **must** be fixed before any multi-agent deployment. +- Two pre-existing High defects (E1, E2) were confirmed with stronger evidence. Their priority should rise. + +### Scope verified + +| Item | Detail | +|---|---| +| **Base** | `b9f2183` plus the uncommitted working tree | +| **Changed (tracked)** | 13 files: `README.md`, `docs/architecture.md`, `docs/threat-model.md`, `run.sh`, `src/shadowgate/{agent/poll.py, config.py, server/app.py, server/queue.py, server/store.py}`, `tests/{test_auth, test_queue, test_runs, test_server}.py` | +| **New (untracked)** | `tests/{conftest, test_agent_auth, test_config_auth}.py`, `docs/tracker.md`, `docs/assessment-2026-11-30.md` | +| **Unchanged** | `pyproject.toml`, `uv.lock`, `.github/` (no dependency or CI changes) | +| **Integrity** | The repo tree's SHA-256 snapshot was identical before and after verification. No reviewer modified the repo. | + +### Test and check execution (all Verified, i.e. actually executed) + +| Check | Result | +|---|---| +| pytest, scratch venv, 3 consecutive runs (test review) | 61 passed ×3. No flakiness. 61 collected. | +| **CI-equivalent in a clean copy** (`uv sync --frozen --extra dev`, then `uv run ruff check src tests`, `uv run mypy`, `uv run pytest -q`) | ruff clean · mypy clean (30 files) · **61 passed** | +| **`bash run.sh --check`** (the project's documented check command) | **6 failed, 55 passed** → V2 | +| mypy in the repo | clean, 32 files. The extra 2 are pre-existing empty dirs `server/api` and `web/static` (from 2026-10-04), counted as namespace packages. Informational. | +| Mutation testing on a copy (test review) | 9/10 mutants killed. M9 survived (the `WWW-Authenticate` scope isn't pinned by any test). | +| `run.sh` launch plus the README quickstart, verbatim, in the clean copy | All steps OK: anonymous `/tokens` 401; enroll gives `agent_token`; operator job; agent poll; lowercase header accepted; Basic `/ui` 200; `/` → 307 `/ui`. `uv.lock` unchanged. | +| Regression comparison against `b9f2183` (independent review, identical scripts on both trees) | Runbook, compensation, dashboard HTML (byte-identical), audit verify, rate limit, and response shapes are unchanged for authorized callers. Only the documented contract changes differ. | +| Python 3.12 (the CI version) | **Not executed.** No 3.12 interpreter locally. Documentation research confirmed and syntax review that no 3.13-only API is used (`StrEnum` exists since 3.11). | + +### Acceptance criteria (§4) + +All T1, T2 and T3 items PASS. The test review mapped each item to its tests: + +| Test IDs | Covers | +|---|---| +| T1-a…f | Fail-closed config | +| T2-a…s, incl. g2 | Enrollment, credentials, ownership, Poller | +| T3-a…d | Route authorization | + +The change-set items also pass: probes 18/18 (§7), suite, ruff, mypy, docs. + +**Coverage gaps (Low):** +- Basic auth is tested only on `/ui`. +- The `run.sh` default path is untested. +- Settings source precedence (initializer > environment > `.env`) is not pinned by a test. + +### Findings introduced by M7 (require source or test changes, so **not fixed; awaiting approval**) + +**V1 · High · Verified: valid agents get spurious 401s under concurrent load, and the Poller then stops permanently.** + +| | | +|---|---| +| **Where** | `server/store.py:113-116` (`authenticate_agent` on the shared `Store._conn`); `agent/poll.py` (`AgentAuthError` ends `run()`) | +| **Repro** | 5 enrolled agents, 40 jobs, 5 threads concurrently `POST /agent/poll` with **valid** tokens. `401 {"detail":"invalid agent credential"}` appeared in 3 of 6 runs. The same tokens all returned 200 when used sequentially afterwards. Reproduce: one `TestClient` app with RBAC on; enroll 5 agents; queue 8 jobs each; poll concurrently from 5 threads with each agent's own token; count 401 responses. | +| **Expected** | A valid credential is always accepted. | +| **Actual** | A transient race on the shared connection (E1) returns `None` from the lookup. The client treats that 401 as fatal, so a healthy agent would shut down for good. | +| **Correction** | Primary: serialize or isolate shared-connection access (T11 core: a store-wide lock, or per-thread connections). Defense in depth: the Poller should retry 401 with backoff a bounded number of times before giving up. | +| **Severity note** | Latent today: no runnable agent ships until T10. It must be fixed before T10. | + +**V2 · Medium · Verified: the test suite isn't isolated from the environment, so `run.sh --check` fails.** + +| | | +|---|---| +| **Where** | `tests/conftest.py` (`open_client`), `tests/test_server.py`, `tests/test_runs.py`, `tests/test_agent_auth.py::test_t2f_legacy_db_migration_and_reclaim` | +| **Repro** | Run the suite with `SHADOWGATE_API_TOKENS_JSON` set, or the legacy `SHADOWGATE_API_TOKENS` set, or a `.env` file in the working directory, or via `run.sh --check` → 6 failed (`KeyError: 'token'`). | +| **Expected** | Tests are deterministic regardless of the developer's environment. | +| **Actual** | Open-mode fixtures don't pin `api_tokens_json`, so they inherit environment tokens. Source precedence is correct: an explicit `Settings(api_tokens_json="")` beats the environment (Verified). | +| **Why it's new** | On the baseline, `run.sh` exported a variable name the app ignored. | +| **Correction** | An autouse conftest fixture that deletes `SHADOWGATE_*` env vars and changes into `tmp_path`, plus pinning `api_tokens_json=""` in open-mode fixtures. Tests only. | + +**V3 · Medium · Verified (implementation review): `run.sh` overrides a token map configured in `.env` with its built-in dev tokens.** + +| | | +|---|---| +| **Where** | `run.sh:6-8`, `config.py:8` | +| **Repro** | Put a token map in `.env`, unset the shell variables, apply `run.sh`'s exports → Settings now resolves the built-in `admin-token` map instead. | +| **Expected** | An explicit `.env` configuration wins over the dev fallback. | +| **Actual** | The process environment (set by `run.sh`) outranks `.env` in pydantic-settings, so the predictable dev admin token is used. Loopback-only, hence Medium. | +| **Why it's new** | The baseline exported an ignored variable name. | +| **Correction** | Only export the dev default when neither environment variable is set **and** `.env` defines neither key; or move the dev defaults behind an explicit `--dev` flag. | + +**V4 · Medium · Verified (independent review): agent tags can no longer be changed through any API.** + +| | | +|---|---| +| **Where** | `store.py:100-107` (reclaim preserves tags; `upsert_agent` removed) | +| **Repro** | Enroll `a1` with `linux`, then re-enroll with a new token (unbound or bound) and `windows` → 409, tags stay `linux`. | +| **Expected** | Operators can re-target an agent through an authorized path. | +| **Actual** | Only direct SQLite edits can change tags. On the baseline, re-enroll overwrote them, which was the S6 flaw. | +| **Correction** | Owner decision: an admin-only, audited tag update (fits with T24), **or** record tag immutability as intended in §7 and `docs/architecture.md`. | + +**Low (non-blocking):** + +| ID | Finding | +|---|---| +| V5 | Enrollment during SQLite writer contention raises an unclassified `OperationalError` (500 after 5 s). The token stays usable, and a retry succeeds (implementation review, Verified). Correction: map busy/locked to 503 with `Retry-After`. | +| V6 | Concurrent first start of a multi-worker deployment against a pre-M7 DB fails with `duplicate column name: secret_hash` in some workers (independent review, Verified). Correction: catch it and re-check `PRAGMA table_info`. | +| V7 | `test_t3a_route_inventory_requires_auth` walks FastAPI's internal `_IncludedRouter.original_router` (documentation research). The expected-subset assertion makes it fail loudly rather than silently, but it's coupled to framework internals. Correction: isolate it in a version-adapter helper. | +| V8 | In `tests/test_queue.py`, an assertion inside a worker thread can't fail the suite (independent review, Verified: a thread `assert False` still → passed). Correction: collect outcomes and assert after `join()`. | +| V9 | Surviving mutant M9: no test asserts `WWW-Authenticate` is absent on non-`/ui` 401s. Basic auth is not tested on non-`/ui` routes (test review). | +| V10 | Tests import helpers `from conftest` (fragile under `--import-mode=importlib`). | +| V11 | `/ui*` handlers close over `store` instead of using `Depends(get_store)` (architecture review). | +| V12 | Docs and metadata drift: the stale `store.py` docstring; this tracker's §2 text still says "tags unchanged unless supplied" and the audit detail as `{tags, bound}`; `pyproject.toml` description still claims mTLS and signed plugins; the `AND ?` boolean in the reclaim SQL is unclear. | + +### Pre-existing defects confirmed (not M7 regressions; identical on `b9f2183`) + +| ID | Sev | Finding | Evidence | Track | +|---|---|---|---|---| +| E1 | **High** | One shared sqlite3 connection is used from FastAPI's threadpool (C8): HTTP 500s, sqlite3 misuse errors (`SQL statements in progress`, `bad parameter or other API misuse`, `SystemError`), and jobs left `running` without ever being delivered. | Store-level: 20×40 jobs → **515 stranded (M7) vs 551 (baseline)**. HTTP-level: 7–12 HTTP 500s and stranded jobs per run (three independent reproductions). | **T11. Recommend promoting P2 → P0 next.** | +| E2 | **High** | The audit chain forks under concurrent appends; `verify_chain()` then reports tampering. | 4 threads × 10 appends → **20/20 chains fail verification on both trees**. Through the app: `verified:false` in 2 of 3 concurrent-poll runs (independent review). | **T12. Recommend P2 → P1, at least the append lock.** | + +### Independent reviews (summaries) + +- **Implementation review (correctness):** + - Found E1 (reported as High; reproduced on both trees, so pre-existing), V3 and V5. + - Confirmed enrollment, result outcomes and Poller retry behavior with direct scripts. + - Its own full-suite run timed out in its environment; the 61 passes were confirmed by the other runs. +- **Architecture review:** implementation matches every §2 design decision; docs match the code; no scope creep; one Low (V11). +- **Test review:** 61 passed ×3; complete acceptance-to-test mapping; mutation 9/10; Low gaps V9 and `run.sh`. +- **Regression and quality review:** + - No unintended regression against the baseline. + - Found V4, E1, E2, V6, V8, V10 and V12. + - Verdict: mergeable; fix E1 and E2 before relying on it for multi-agent fleets. +- **Reference research:** + - Confirmed the sqlite3 legacy-transaction, `RETURNING`, pydantic-settings precedence, httpx predicate, Uvicorn `--factory` and `StrEnum` assumptions against official docs. + - Found V7, plus untested settings precedence. +- **Coordinator:** clean-copy CI run, `run.sh --check` (V2), README and launcher flow, V1 discovery and reproduction, E1 and E2 reproduction on both trees, tree-integrity check. + +### Readiness + +- **Security scope of M7:** achieved and verified (probes, tests, regression comparison). +- **Commit readiness:** acceptable after the owner decides on V2/V3 (small test/launcher fixes) and V4 (a policy decision). +- **Deployment readiness (multi-agent): not ready.** Blocked by E1 → V1 and by E2. +- **Recommended next task:** T11's connection serialization (fixes E1 and V1), together with the T12 append lock (E2). It is small, and everything else depends on it. + +## 9. Release readiness: Phase 5 (2026-11-30) + +**Status: NOT READY for release.** The M7 change set is a sound, verified development milestone, but the project cannot be published or tagged as a release yet. The evidence is below. + +### Git state (Verified) + +| Item | State | +|---|---| +| Branch | `main`, tracking `origin/main` at `b9f2183`; 0 ahead / 0 behind | +| Remote | `github.com/5aranx/ShadowGate` | +| Tracked changes | 13 modified: `README.md`, `docs/architecture.md`, `docs/threat-model.md`, `run.sh`, 5 source files, 4 test files | +| Untracked | `tests/conftest.py`, `tests/test_agent_auth.py`, `tests/test_config_auth.py` (part of M7); `docs/assessment-2026-11-30.md`, `docs/tracker.md` (process docs) | +| Ignored local artefacts present | `.venv/`, caches, `shadowgate.db`, `.shadowgate/audit.log` (from 2026-10-04; correctly gitignored) | +| Empty local-only dirs | `src/shadowgate/server/api/`, `src/shadowgate/web/static/` (from 2026-10-04; not tracked by git) | +| Secrets scan (tracked + untracked) | No real credentials. Only the documented public dev placeholders (`admin-token`, `op-token`, `view-token`) in `run.sh` and `README.md`. | +| Local or internal references | At the time, the process docs (`assessment`, `tracker`) referred to local scripts, temporary paths and tool-specific names that are not in the repo. Cleaned up in §10. | +| Nothing staged, committed, pushed or tagged | Confirmed | + +### Build and test (Verified, executed this phase) + +| Check | Result | +|---|---| +| Clean copy of the working tree, `uv sync --frozen --extra dev` (test review and coordinator) | ruff clean · mypy clean (30 files) · pytest **61 passed ×3** · `uv.lock` unchanged | +| Suite with the token env vars unset / set | 61 passed / **6 failed** (V2 reproduced) | +| Import side effects | none (`import shadowgate.server.app` in an empty dir creates no files) | +| README commands, executed verbatim against `./run.sh` in the clean copy | All pass: mint → enroll → job → poll → result → stats → `audit?verify=true` = true; Basic `/ui` 200; YAML runbook pipeline → run created; the Python `Poller` snippet processed the run to `done` | +| CLI | `shadowgate --version` → 0.1.0; `shadowgate server` prints a placeholder and **exits 0** | +| Dependencies (documentation research) | No public advisory found affecting the locked versions (not an exhaustive scan). 4 declared dependencies are unused: SQLAlchemy, aiosqlite, itsdangerous, python-multipart. The build backend `hatchling` is unpinned. CI pins uv 0.12.22 against a lockfile produced by 0.13.x (compatibility unverified). Starlette TestClient httpx deprecation warning. | +| Python 3.12 (the CI version) | **Not executed locally.** No 3.12 interpreter; compatibility checked against documentation only. | + +### Documentation changes in this phase (docs only; no source, test or config change) + +**`README.md`, rewritten.** It covers purpose, a status banner, what exists today, architecture, technologies, prerequisites, installation, a configuration table (all 11 settings, with the 5 unused ones marked), running (`run.sh`, direct, walkthrough, runbook, Python agent), an API/auth summary, testing (with the V2 caveat), and complete user-visible known limitations. Every command in it was executed. + +**`docs/architecture.md`, corrected:** +- audit integrity: truncation isn't detected, and concurrent appends fork the chain; +- "exactly-once" changed to "per-row atomic claim"; +- the shared-connection concurrency defect; +- the queue test runs on separate connections; +- "duplicate" results are not re-audited; +- mTLS and the plugin gate are marked as not used at runtime. + +**`docs/threat-model.md`, corrected:** +- assets (only runtime credentials); +- fail-closed wording (a malformed map fails in every mode; only an empty map plus insecure dev mode opens routes); +- a transport section (no TLS); +- per-IP, per-endpoint rate limiting; +- audit and concurrency failure-mode rows; +- the availability caveat on the agent-isolation statement. + +**Reviews:** +- Documentation review: D1–D6, D11–D14, D16 and D18 all fixed, with no new inaccuracy; its two remaining nits were also fixed. +- Architecture review covered the project structure. +- Integration review covered (config surface, CLI exit codes, `data_dir` semantics, negative rate limit). Its points are documented. + +### Release blockers (each needs an owner decision or approved code work) + +| # | Blocker | Evidence | Needed | +|---|---|---|---| +| B1 | `pyproject.toml` declares MIT, but there is **no `LICENSE` file** | Documentation review D7 | **Resolved (§10):** MIT `LICENSE` added, `Copyright (c) 2026 5aranx` | +| B2 | Concurrent use is unreliable: stranded jobs and 500s (E1); valid agents get spurious 401, and the `Poller` stops (V1); the audit chain forks (E2) | Phase 4 §8 | T11 connection serialization + T12 append lock + Poller 401 handling (approval) | +| B3 | The documented check `./run.sh --check` fails 6 tests (V2); `run.sh` overrides `.env` tokens (V3) | Phase 4 §8; clean-copy test run | **Resolved (§10)** | +| B4 | There is no runnable agent: the CLI subcommands are placeholders that exit 0 | Integration and test review | T10 (approval) | +| B5 | Package metadata is stale: `pyproject` description claims mTLS and signed plugins; no CHANGELOG; the version is defined twice; unused dependencies | Documentation review D8–D10/D17; dependency review | Owner-approved metadata change (and T18) | +| B6 | The process docs are untracked and contain local or internal references | Architecture review; coordinator | **Resolved (§10):** sanitized, to be committed | + +### Not blocking, documented + +- **V4:** tags are immutable after enrollment. +- **V5:** enrollment returns 500 when SQLite is busy. +- **V6:** startup race with multiple workers against an old database. +- **F2:** the one-time secret is lost if the audit write fails after commit. +- **R-obs 4:** the Poller drops results on 408/429. +- **Engine gap:** a retried result doesn't re-trigger the run engine. +- **Unused settings:** `host`, `port`, `org_key_path`, `ca_*`. +- **`data_dir`:** doesn't relocate the database or audit log. +- **Logging:** none. +- **Dev-only items:** V7–V12, F3, F7, F8. + +All user-visible items are listed in the README's Known limitations. + +### Readiness by scope + +| Scope | Assessment | +|---|---| +| Commit M7 to `main` as a reviewed milestone (not a release) | Reasonable once the owner decides B3 (or accepts it as documented) and B6. Security goals are verified, and CI-equivalent checks are green. | +| Tagged pre-release / public publication | **Not ready**: B1, B3, B5 | +| Multi-agent or networked deployment | **Not ready**: B2, B4, plus no TLS (T14) | + +## 10. Blocker 3 fix, license and documentation cleanup (2026-11-30) + +**Scope (owner-approved):** fix B3, sanitize the process docs (B6), add an MIT license (B1), verify, and prepare the commit. T11 was not started. + +### B3: root causes and fixes + +| Issue | Root cause | Fix | +|---|---|---| +| **V2:** 6 tests failed under `./run.sh --check` (`test_server.py` ×3, `test_runs.py` ×2, `test_agent_auth.py::test_t2f_legacy_db_migration_and_reclaim`) | Their open-mode fixtures set `insecure_dev=True` but never pinned `api_tokens_json`. `Settings` therefore inherited `SHADOWGATE_API_TOKENS(_JSON)` from the environment (exported by `run.sh`) or from a `.env` in the working directory, which switched RBAC on, so `POST /tokens` without a header → 401 → `KeyError: 'token'`. The source was correct: explicit `Settings(...)` arguments already beat the environment. | `tests/conftest.py`: an autouse fixture removes every `SHADOWGATE_*` variable (any case), changes into the test's temporary directory (so no outside `.env` is read), and clears the `get_settings()` cache. The open-mode fixtures also pin `api_tokens_json=""` explicitly. No test was skipped, removed or weakened. | +| **V3:** `run.sh` overrode tokens configured in `.env` | `run.sh` exported its dev map whenever the shell had no token variable. Process environment beats `.env` in pydantic-settings, so `.env` was ignored. | The dev map is now exported only if no token variable is set in the shell **and** `.env` defines neither name. Names are matched case-insensitively, like the server. Explicit empty values are still respected (the server then fails closed). | +| Related | `--check` exported the dev tokens into the test run, which is what triggered V2 in the first place | `--check` exports no tokens | +| Related | `run.sh` exported `SHADOWGATE_DATA_DIR=.shadowgate`, which equals the built-in default and also overrode `.env` | Export removed; no behavior change by default | + +**Command-line interface:** `./run.sh` and `./run.sh --check` keep the same arguments and output, except that the token line now says which source is in use. + +### New regression tests: `tests/test_env_precedence.py` (16 tests) + +**Settings source precedence (5 tests):** +- the `_JSON` name beats the legacy name; +- `.env` is read (both names); +- the environment beats `.env`; +- an explicit argument beats both. + +**The real `run.sh` with a stub `uv` (nothing installed or launched), 10 tests:** +- no configuration → dev map; +- `.env` (`_JSON`, legacy with `export`, lowercase with spaces and a trailing comment) is not overridden; +- a commented-out `.env` line still gets the dev map; +- shell `_JSON` beats `.env`; +- the shell legacy name and a lowercase name are respected; +- an explicit empty value is respected and the server fails closed; +- `--check` runs the four steps and exports no tokens. + +**Suite isolation (1 test):** the six formerly failing tests are re-run in a subprocess with both token variables exported and a `.env` present. + +**Test-first check:** run against the pre-fix tree, the V2/V3 cases fail (6: the two `.env` cases, lowercase shell name, lowercase `.env`, `--check`, suite isolation), while the guards pass on both trees. + +### Verification (Verified; all executed) + +| Check | Result | +|---|---| +| `./run.sh --check` in the repo, plain | ruff clean · mypy clean · **77 passed** · exit 0 | +| `./run.sh --check` with `SHADOWGATE_API_TOKENS_JSON` exported (the old failure scenario) | **77 passed** · exit 0 | +| Clean copy: `uv sync --frozen --extra dev`, `uv run --frozen pytest -q`, `ruff check src tests`, `mypy` and `mypy --strict` | 77 passed · clean · clean · clean | +| README commands verbatim against `./run.sh` in the clean copy | All pass (mint → enroll → job → poll → result → stats → `audit?verify=true` true; Basic `/ui` 200; YAML runbook; Python `Poller` snippet completed the run's jobs) | +| V3 end to end: `.env` with a custom admin token, `./run.sh` | prints "from the environment or .env"; dev `admin-token` → **401**; `.env` token → **200** | +| `uv build --offline` | wheel and sdist both contain `LICENSE`; metadata `License: MIT`, `License-File: LICENSE`, `Author: 5aranx`; templates included | +| `uv.lock` | unchanged | + +### Documentation cleanup (B6) + +`docs/assessment-2026-11-30.md` and this tracker no longer contain machine-specific paths, references to local scripts, or names of the tools and agents used during development: +- Review attributions are now neutral roles (implementation, test, architecture, documentation/reference, independent review, coordinator). +- The former "agent assignment matrix" is now §3 "Working practice". +- The assessment's probes are mapped to the repo tests that now cover them. Concurrency reproductions are described in prose. +- All finding IDs and the phase history are preserved. + +### License (B1) + +`LICENSE` is the standard MIT text, `Copyright (c) 2026 5aranx` (holder and year confirmed by the owner). It agrees with `pyproject.toml` (`license = { text = "MIT" }`, `authors = 5aranx`) and is included by the build (above). The README has a License section. + +### Independent review of this change set + +No Critical or High findings. Resolved: +- the stale tracker state; +- the dangling §10 reference; +- inexact test IDs; +- the case-sensitive shell check in `run.sh` (fixed and tested); +- the README `--frozen` wording; +- a brittle subprocess assertion; +- missing `.env` edge-case tests. + +Not changed: adding PEP 639 `license-files` to `pyproject.toml`, since the build already includes `LICENSE`. + +### New observation (pre-existing; not fixed) + +**N1 · Low:** a `.env` file may contain only ShadowGate settings. Any other key, even without the `SHADOWGATE_` prefix (e.g. `UNRELATED_VAR=1`), makes `Settings` fail with `extra_forbidden`, so the server won't start. The baseline `b9f2183` behaves identically. It's documented in the README Configuration section. A fix (e.g. `extra="ignore"` in `SettingsConfigDict`) is a source change and needs approval. + +## 6. Change log + +| Date | Change | +|---|---| +| 2026-11-30 | Tracker created from the Phase 1 assessment and Phase 2 planning. Inputs: implementation requirements, architecture review, test plan and definition of done, reference verification, and an independent T2 plan review (go-with-changes, R1–R9 incorporated). M7 marked Ready pending owner approval of OD1–OD3. | +| 2026-11-30 | Phase 3 started: owner approved the plan; M7 in progress. Decisions taken as the plan's recommendations: OD1 = bound enrollment tokens; OD2 = HTTP Basic (token as password) on `/ui*`; OD3 = keep loopback dev tokens in `run.sh`; OD4 deferred. Intended changes = §2 file table. Order: tests written first (must fail on baseline) → implementation T1 → T2 → T3 → contract docs and consistency check → independent review. | +| 2026-11-30 | M7 implemented and verified (61 tests, ruff and mypy clean, 18/18 probes fixed, smoke test passed). Independent review: F1 blocking, fixed; second pass clean. Status → In review, awaiting owner acceptance. Nothing committed. Follow-ups recorded in §7. | +| 2026-11-30 | Phase 4 verification of M7: **PASS WITH ISSUES** (§8). All §4 acceptance items pass; CI-equivalent clean-copy run passed; `run.sh --check` fails (V2). New: V1 (High: spurious 401 → agent stops), V2–V4 (Medium), V5–V12 (Low). Pre-existing E1 (shared connection: stranded jobs) and E2 (audit chain fork) reproduced on the baseline too; recommend promoting T11/T12. No source changed during verification; fixes await owner approval. | +| 2026-11-30 | Phase 5 release readiness: **NOT READY** (§9). Docs only: README rewritten (all commands executed verbatim); architecture and threat-model corrected for the audit, concurrency and transport findings (documentation review recheck: all fixed). Clean frozen build green (61 ×3); V2 reproduced. Blockers B1–B6 await owner decisions. Nothing staged, committed, pushed or tagged. | +| 2026-11-30 | B3 fixed (test isolation, `run.sh` token precedence), 16 regression tests added (77 total), MIT LICENSE added, process docs sanitized; independent review clean (no Critical/High). N1 recorded (pre-existing `.env` strictness). Prepared for commit (§10). | diff --git a/run.sh b/run.sh index 9471336..68b8f08 100755 --- a/run.sh +++ b/run.sh @@ -3,9 +3,6 @@ set -euo pipefail cd "$(dirname "$0")" -export SHADOWGATE_API_TOKENS="${SHADOWGATE_API_TOKENS:-{\"admin-token\":\"admin\",\"op-token\":\"operator\",\"view-token\":\"viewer\"}}" -export SHADOWGATE_DATA_DIR="${SHADOWGATE_DATA_DIR:-.shadowgate}" - if [[ "${1:-}" == "--check" ]]; then uv sync --extra dev uv run ruff check src tests @@ -14,8 +11,27 @@ if [[ "${1:-}" == "--check" ]]; then exit 0 fi +# Operator tokens, highest precedence first: +# 1. SHADOWGATE_API_TOKENS_JSON or SHADOWGATE_API_TOKENS already set in the shell +# (an empty value is respected and makes the server refuse to start); +# 2. either name defined in ./.env, which the server reads itself; +# 3. the public development map below -- loopback use only. +dev_tokens='{"admin-token":"admin","op-token":"operator","view-token":"viewer"}' + +# Names are matched case-insensitively, as the server's settings loader does. +tokens_configured() { + env | grep -Eqi '^SHADOWGATE_API_TOKENS(_JSON)?=' && return 0 + [[ -f .env ]] && grep -Eqi \ + '^[[:space:]]*(export[[:space:]]+)?SHADOWGATE_API_TOKENS(_JSON)?[[:space:]]*=' .env +} + uv sync --extra dev echo "ShadowGate on http://127.0.0.1:8080 (dashboard: /ui)" -echo "tokens: admin-token / op-token / view-token" +if tokens_configured; then + echo "operator tokens: from the environment or .env" +else + export SHADOWGATE_API_TOKENS_JSON="$dev_tokens" + echo "operator tokens: development defaults admin-token / op-token / view-token" +fi echo "stop with Ctrl-C" -exec uv run uvicorn shadowgate.server.app:app --host 127.0.0.1 --port 8080 +exec uv run uvicorn --factory shadowgate.server.app:create_app --host 127.0.0.1 --port 8080 diff --git a/src/shadowgate/agent/poll.py b/src/shadowgate/agent/poll.py index dc28da8..782e8c0 100644 --- a/src/shadowgate/agent/poll.py +++ b/src/shadowgate/agent/poll.py @@ -7,31 +7,75 @@ from shadowgate.agent.executor import Executor +class AgentAuthError(Exception): + """The server rejected the agent credential.""" + + class Poller: - def __init__(self, executor: Executor, server_url: str, poll_interval: float = 1.0) -> None: + def __init__( + self, executor: Executor, server_url: str, *, agent_token: str, + poll_interval: float = 1.0, result_retries: int = 3, retry_backoff: float = 1.0, + ) -> None: self.executor = executor self.server_url = server_url.rstrip("/") + self.agent_token = agent_token self.poll_interval = poll_interval + self.result_retries = result_retries + self.retry_backoff = retry_backoff + self._pending: dict[str, object] | None = None + + def make_client(self, transport: httpx.BaseTransport | None = None) -> httpx.Client: + return httpx.Client(headers={"X-ShadowGate-Agent-Token": self.agent_token}, + transport=transport) + + def _deliver(self, client: httpx.Client) -> None: + for attempt in range(self.result_retries + 1): + if attempt: + time.sleep(self.retry_backoff) + try: + response = client.post(f"{self.server_url}/agent/result", json=self._pending) + except httpx.TransportError: + continue + if response.status_code in (401, 403): + raise AgentAuthError("invalid agent credential") + if response.is_success or response.is_client_error: + self._pending = None + return def poll_once(self, client: httpx.Client) -> bool: - r = client.post(f"{self.server_url}/agent/poll", json={"agent_id": self.executor.agent_id}) - if r.status_code != 200: + if self._pending is not None: + self._deliver(client) + if self._pending is not None: + return False + response = client.post(f"{self.server_url}/agent/poll", json={}) + if response.status_code in (401, 403): + raise AgentAuthError("invalid agent credential") + if response.status_code != 200: + return False + try: + payload = response.json() + except ValueError: + return False + if not isinstance(payload, dict): return False - job = r.json().get("job") - if job is None: + job = payload.get("job") + if ( + not isinstance(job, dict) + or not isinstance(job.get("id"), str) + or not isinstance(job.get("action"), str) + ): return False result = self.executor.run(job["id"], job["action"], job.get("params", {})) - client.post( - f"{self.server_url}/agent/result", - json={"job_id": job["id"], "ok": result.ok, "data": result.data, "error": result.error}, - ) + self._pending = {"job_id": job["id"], "ok": result.ok, "data": result.data, + "error": result.error} + self._deliver(client) return True def run(self) -> None: - with httpx.Client() as client: + with self.make_client() as client: while True: try: if not self.poll_once(client): time.sleep(self.poll_interval) - except httpx.HTTPError: + except (httpx.HTTPError, ValueError): time.sleep(self.poll_interval) diff --git a/src/shadowgate/config.py b/src/shadowgate/config.py index 436226d..3c5b7cd 100644 --- a/src/shadowgate/config.py +++ b/src/shadowgate/config.py @@ -1,10 +1,13 @@ from functools import lru_cache +from pydantic import AliasChoices, Field from pydantic_settings import BaseSettings, SettingsConfigDict class Settings(BaseSettings): - model_config = SettingsConfigDict(env_prefix="SHADOWGATE_", env_file=".env") + model_config = SettingsConfigDict( + env_prefix="SHADOWGATE_", env_file=".env", populate_by_name=True + ) db_path: str = "shadowgate.db" data_dir: str = ".shadowgate" @@ -15,7 +18,10 @@ class Settings(BaseSettings): org_key_path: str = ".shadowgate/org_ed25519.key" ca_key_path: str = ".shadowgate/ca.key" ca_cert_path: str = ".shadowgate/ca.crt" - api_tokens_json: str = "" # e.g. '{"tok-admin":"admin","tok-op":"operator"}' + api_tokens_json: str = Field( + default="", + validation_alias=AliasChoices("SHADOWGATE_API_TOKENS_JSON", "SHADOWGATE_API_TOKENS"), + ) rate_limit_per_minute: int = 60 diff --git a/src/shadowgate/server/app.py b/src/shadowgate/server/app.py index 73d529c..512e397 100644 --- a/src/shadowgate/server/app.py +++ b/src/shadowgate/server/app.py @@ -1,19 +1,22 @@ from __future__ import annotations +import base64 import json import time +import warnings from collections import defaultdict from collections.abc import Callable from contextlib import asynccontextmanager from pathlib import Path from typing import Any -from fastapi import Depends, FastAPI, HTTPException, Request +from fastapi import APIRouter, Depends, FastAPI, HTTPException, Request, Response from pydantic import BaseModel, Field from shadowgate.config import Settings, get_settings from shadowgate.server.audit import AuditLog -from shadowgate.server.store import Store +from shadowgate.server.queue import CompletionOutcome +from shadowgate.server.store import EnrollOutcome, Store class EnrollRequest(BaseModel): @@ -22,8 +25,8 @@ class EnrollRequest(BaseModel): tags: str = "" -class PollRequest(BaseModel): - agent_id: str +class MintRequest(BaseModel): + agent_id: str | None = Field(default=None, min_length=1) class ResultRequest(BaseModel): @@ -43,10 +46,29 @@ class RunRequest(BaseModel): runbook: str +def _parse_token_roles(settings: Settings) -> dict[str, str]: + try: + roles = json.loads(settings.api_tokens_json.strip() or "{}") + except ValueError: + raise ValueError("invalid operator token configuration") from None + if not isinstance(roles, dict) or any( + not token + or ":" in token + or any(char.isspace() for char in token) + or role not in ("viewer", "operator", "admin") + for token, role in roles.items() + ): + raise ValueError("invalid operator token configuration") + if not roles: + if not settings.insecure_dev: + raise ValueError("operator tokens required outside insecure development mode") + warnings.warn("operator authorization disabled in insecure development mode", stacklevel=2) + return roles def create_app(settings: Settings | None = None) -> FastAPI: settings = settings or get_settings() + token_roles = _parse_token_roles(settings) data_dir = Path(settings.data_dir) data_dir.mkdir(parents=True, exist_ok=True) audit = AuditLog(settings.audit_log_path) @@ -56,31 +78,42 @@ def create_app(settings: Settings | None = None) -> FastAPI: async def lifespan(app: FastAPI): # type: ignore[no-untyped-def] yield - app = FastAPI(title="ShadowGate", lifespan=lifespan) + app = FastAPI(title="ShadowGate", lifespan=lifespan, + openapi_url="/openapi.json" if settings.insecure_dev else None) app.state.store = store app.state.audit = audit ROLE_ORDER = {"viewer": 0, "operator": 1, "admin": 2} - try: - token_roles: dict[str, str] = json.loads(settings.api_tokens_json or "{}") - except json.JSONDecodeError: - token_roles = {} - def require_role(role: str) -> Callable[[Request], None]: def dep(request: Request) -> None: if not token_roles: return # dev mode: no tokens configured, open header = request.headers.get("authorization", "") scheme, _, token = header.partition(" ") - if scheme.lower() != "bearer" or token not in token_roles: - raise HTTPException(status_code=401, detail="missing or invalid bearer token") + if scheme.lower() == "basic": + try: + decoded = base64.b64decode(token, validate=True).decode() + except ValueError: + decoded = "" + _, _, token = decoded.partition(":") + elif scheme.lower() != "bearer": + token = "" + if token not in token_roles: + headers = ( + {"WWW-Authenticate": 'Basic realm="shadowgate"'} + if request.url.path.startswith("/ui") else None + ) + raise HTTPException(status_code=401, detail="invalid operator credential", + headers=headers) actual = token_roles[token] if ROLE_ORDER.get(actual, -1) < ROLE_ORDER[role]: raise HTTPException(status_code=403, detail=f"requires role {role}") return dep + reads = APIRouter(dependencies=[Depends(require_role("viewer"))]) + rate_hits: dict[str, list[float]] = defaultdict(list) def rate_limited(request: Request) -> None: @@ -100,18 +133,29 @@ def get_audit() -> AuditLog: audit: AuditLog = app.state.audit return audit - @app.post("/tokens", dependencies=[Depends(rate_limited), Depends(require_role("admin"))]) - def mint_token(store: Store = Depends(get_store)) -> dict[str, str]: - return {"token": store.mint_token()} + def require_agent(request: Request, store: Store = Depends(get_store)) -> str: + token = request.headers.get("X-ShadowGate-Agent-Token", "") + agent_id = store.authenticate_agent(token) if token.strip() else None + if agent_id is None: + raise HTTPException(status_code=401, detail="invalid agent credential") + return agent_id - @app.post("/enroll", dependencies=[Depends(rate_limited), Depends(require_role("admin"))]) - def enroll(req: EnrollRequest, store: Store = Depends(get_store)) -> dict[str, str]: - if not store.burn_token(req.token, req.agent_id): + @app.post("/tokens", dependencies=[Depends(rate_limited), Depends(require_role("admin"))]) + def mint_token(req: MintRequest | None = None, + store: Store = Depends(get_store)) -> dict[str, str]: + return {"token": store.mint_token(agent_id=req.agent_id if req else None)} + + @app.post("/enroll", dependencies=[Depends(rate_limited)]) + def enroll(req: EnrollRequest, response: Response, + store: Store = Depends(get_store)) -> dict[str, str]: + outcome, secret = store.enroll_agent(req.agent_id, req.token, req.tags) + if outcome == EnrollOutcome.INVALID_TOKEN: raise HTTPException(status_code=403, detail="invalid or burned token") - store.upsert_agent(req.agent_id, req.tags) - store.audit.append("agent_enrolled", actor=req.agent_id, target="server", - detail={"tags": req.tags}) - return {"status": "enrolled", "agent_id": req.agent_id} + if outcome == EnrollOutcome.CONFLICT: + raise HTTPException(status_code=409, detail="agent already enrolled") + assert secret is not None + response.headers["Cache-Control"] = "no-store" + return {"status": "enrolled", "agent_id": req.agent_id, "agent_token": secret} @app.post("/jobs", dependencies=[Depends(require_role("operator"))]) def create_job(req: JobRequest, store: Store = Depends(get_store)) -> dict[str, str]: @@ -124,18 +168,26 @@ def create_job(req: JobRequest, store: Store = Depends(get_store)) -> dict[str, return {"job_id": job_id, "status": "queued"} @app.post("/agent/poll") - def agent_poll(req: PollRequest, store: Store = Depends(get_store)) -> dict[str, Any]: - job = store.queue.claim_next(agent_id=req.agent_id) + def agent_poll(agent_id: str = Depends(require_agent), + store: Store = Depends(get_store)) -> dict[str, Any]: + job = store.queue.claim_next(agent_id=agent_id) if job is None: return {"job": None} - store.audit.append("job_claimed", actor=req.agent_id, target=job.id, + store.audit.append("job_claimed", actor=agent_id, target=job.id, detail={"action": job.action}) return {"job": {"id": job.id, "action": job.action, "params": job.params}} @app.post("/agent/result") - def agent_result(req: ResultRequest, store: Store = Depends(get_store)) -> dict[str, str]: - store.queue.complete(req.job_id, req.ok, req.data) - store.audit.append("job_completed", actor="agent", target=req.job_id, + def agent_result(req: ResultRequest, agent_id: str = Depends(require_agent), + store: Store = Depends(get_store)) -> dict[str, str]: + outcome = store.queue.complete(req.job_id, agent_id=agent_id, success=req.ok, data=req.data) + if outcome == CompletionOutcome.NOT_FOUND: + raise HTTPException(status_code=404, detail="unknown job") + if outcome == CompletionOutcome.CONFLICT: + raise HTTPException(status_code=409, detail="job not in running state") + if outcome == CompletionOutcome.DUPLICATE: + return {"status": "duplicate"} + store.audit.append("job_completed", actor=agent_id, target=req.job_id, detail={"ok": req.ok, "error": req.error}) store.engine.on_job_result(req.job_id, req.ok) return {"status": "recorded"} @@ -165,22 +217,22 @@ def start_run(req: RunRequest, store: Store = Depends(get_store)) -> dict[str, A run_id = store.engine.start_run(runbook, store.list_agents()) return {"run_id": run_id, "status": "running"} - @app.get("/runs/{run_id}") + @reads.get("/runs/{run_id}") def run_status(run_id: str, store: Store = Depends(get_store)) -> dict[str, Any]: status = store.engine.run_status(run_id) if status is None: raise HTTPException(status_code=404, detail="unknown run") return status - @app.get("/agents", dependencies=[Depends(require_role("viewer"))]) + @reads.get("/agents") def agents(store: Store = Depends(get_store)) -> dict[str, Any]: return {"agents": store.list_agents()} - @app.get("/jobs") + @reads.get("/jobs") def jobs(store: Store = Depends(get_store)) -> dict[str, Any]: return {"stats": store.queue.stats()} - @app.get("/audit", dependencies=[Depends(require_role("viewer"))]) + @reads.get("/audit") def audit_log(audit: AuditLog = Depends(get_audit), verify: bool = False) -> dict[str, Any]: return {"entries": audit.entries(), "verified": audit.verify_chain() if verify else None} @@ -201,23 +253,21 @@ def root() -> Any: def render(request: Request, name: str, context: dict[str, Any]) -> Any: return templates.TemplateResponse(request, name, context) - @app.get("/ui") + @reads.get("/ui") def ui(request: Request) -> Any: return render(request, "agents.html", {"agents": store.list_agents()}) - @app.get("/ui/agents") + @reads.get("/ui/agents") def ui_agents(request: Request) -> Any: return render(request, "agents.html", {"agents": store.list_agents()}) - @app.get("/ui/jobs") + @reads.get("/ui/jobs") def ui_jobs(request: Request) -> Any: return render(request, "jobs.html", {"stats": store.queue.stats()}) - @app.get("/ui/runs") + @reads.get("/ui/runs") def ui_runs(request: Request) -> Any: return render(request, "runs.html", {"runs": store.engine.list_runs()}) + app.include_router(reads) return app - - -app = create_app() diff --git a/src/shadowgate/server/queue.py b/src/shadowgate/server/queue.py index 667ffc6..a8a4e7f 100644 --- a/src/shadowgate/server/queue.py +++ b/src/shadowgate/server/queue.py @@ -5,9 +5,17 @@ import json import sqlite3 from dataclasses import dataclass +from enum import StrEnum from typing import Any +class CompletionOutcome(StrEnum): + ACCEPTED = "accepted" + DUPLICATE = "duplicate" + NOT_FOUND = "not_found" + CONFLICT = "conflict" + + @dataclass class ClaimedJob: id: str @@ -52,37 +60,41 @@ def enqueue(self, job_id: str, agent_id: str, action: str, params: dict[str, Any ) self._conn.commit() - def claim_next(self, agent_id: str | None = None) -> ClaimedJob | None: - if agent_id is None: - cur = self._conn.execute( - """ - UPDATE qjobs SET status='running' - WHERE id = (SELECT id FROM qjobs WHERE status='queued' ORDER BY rowid LIMIT 1) - RETURNING id, action, params - """ - ) - else: - cur = self._conn.execute( - """ - UPDATE qjobs SET status='running' - WHERE id = (SELECT id FROM qjobs WHERE status='queued' - AND agent_id=? ORDER BY rowid LIMIT 1) - RETURNING id, action, params - """, - (agent_id,), - ) + def claim_next(self, agent_id: str) -> ClaimedJob | None: + cur = self._conn.execute( + """ + UPDATE qjobs SET status='running' + WHERE id = (SELECT id FROM qjobs WHERE status='queued' + AND agent_id=? ORDER BY rowid LIMIT 1) + RETURNING id, action, params + """, + (agent_id,), + ) row = cur.fetchone() self._conn.commit() if row is None: return None return ClaimedJob(id=row[0], action=row[1], params=json.loads(row[2])) - def complete(self, job_id: str, ok: bool, data: dict[str, Any]) -> None: - self._conn.execute( - "UPDATE qjobs SET status=? WHERE id=?", - ("done" if ok else "failed", job_id), - ) + def complete( + self, job_id: str, *, agent_id: str, success: bool, data: dict[str, Any] + ) -> CompletionOutcome: + status = "done" if success else "failed" + updated = self._conn.execute( + "UPDATE qjobs SET status=? WHERE id=? AND agent_id=? AND status='running'", + (status, job_id, agent_id), + ).rowcount self._conn.commit() + if updated: + return CompletionOutcome.ACCEPTED + row = self._conn.execute( + "SELECT status FROM qjobs WHERE id=? AND agent_id=?", (job_id, agent_id) + ).fetchone() + if row is None: + return CompletionOutcome.NOT_FOUND + if row[0] == status: + return CompletionOutcome.DUPLICATE + return CompletionOutcome.CONFLICT def stats(self) -> dict[str, int]: rows = self._conn.execute("SELECT status, COUNT(*) FROM qjobs GROUP BY status").fetchall() diff --git a/src/shadowgate/server/store.py b/src/shadowgate/server/store.py index d002410..39b0d9b 100644 --- a/src/shadowgate/server/store.py +++ b/src/shadowgate/server/store.py @@ -6,10 +6,12 @@ from __future__ import annotations +import hashlib import secrets import sqlite3 from contextlib import closing from datetime import UTC, datetime, timedelta +from enum import StrEnum from pathlib import Path from typing import Any @@ -17,6 +19,12 @@ from shadowgate.server.queue import SqlQueue +class EnrollOutcome(StrEnum): + ENROLLED = "enrolled" + INVALID_TOKEN = "invalid_token" + CONFLICT = "conflict" + + class Store: def __init__(self, path: str, audit: AuditLog | None = None) -> None: self.path = path @@ -24,10 +32,10 @@ def __init__(self, path: str, audit: AuditLog | None = None) -> None: self._conn = sqlite3.connect(path, check_same_thread=False) self._conn.execute("PRAGMA journal_mode=WAL") self._conn.execute("PRAGMA foreign_keys=ON") + self._conn.execute("PRAGMA busy_timeout=5000") self._setup() self.queue = SqlQueue(path, conn=self._conn) self.audit: AuditLog = audit or AuditLog(str(Path(path).parent / "audit.log")) - self._conn.execute("PRAGMA busy_timeout=5000") from shadowgate.server.runs import RunEngine self.engine = RunEngine(self._conn, self.queue, self.audit) @@ -39,7 +47,8 @@ def _setup(self) -> None: CREATE TABLE IF NOT EXISTS agents( id TEXT PRIMARY KEY, tags TEXT NOT NULL DEFAULT '', - enrolled_at TEXT NOT NULL + enrolled_at TEXT NOT NULL, + secret_hash TEXT ); CREATE TABLE IF NOT EXISTS enroll_tokens( token TEXT PRIMARY KEY, @@ -50,40 +59,61 @@ def _setup(self) -> None: ); """ ) + if "secret_hash" not in {row[1] for row in cur.execute("PRAGMA table_info(agents)")}: + cur.execute("ALTER TABLE agents ADD COLUMN secret_hash TEXT") + cur.execute("CREATE UNIQUE INDEX IF NOT EXISTS idx_agents_secret_hash " + "ON agents(secret_hash)") self._conn.commit() - def mint_token(self, ttl_minutes: int = 30) -> str: + def mint_token(self, ttl_minutes: int = 30, agent_id: str | None = None) -> str: token = secrets.token_urlsafe(24) minted = datetime.now(UTC) expires = minted + timedelta(minutes=ttl_minutes) self._conn.execute( - "INSERT INTO enroll_tokens(token,minted_at,expires_at) VALUES(?,?,?)", - (token, minted.isoformat(), expires.isoformat()), + "INSERT INTO enroll_tokens(token,minted_at,expires_at,agent_id) VALUES(?,?,?,?)", + (token, minted.isoformat(), expires.isoformat(), agent_id), ) self._conn.commit() return token - def burn_token(self, token: str, agent_id: str) -> bool: - cur = self._conn.execute( - "UPDATE enroll_tokens SET burned_at=?, agent_id=? " - "WHERE token=? AND burned_at IS NULL AND expires_at > ?", - ( - datetime.now(UTC).isoformat(), - agent_id, - token, - datetime.now(UTC).isoformat(), - ), - ) - self._conn.commit() - return cur.rowcount == 1 + def enroll_agent( + self, agent_id: str, token: str, tags: str + ) -> tuple[EnrollOutcome, str | None]: + with closing(sqlite3.connect(self.path, timeout=5)) as conn, conn: + conn.execute("BEGIN IMMEDIATE") + now = datetime.now(UTC).isoformat() + invitation = conn.execute( + "UPDATE enroll_tokens SET burned_at=? WHERE token=? AND burned_at IS NULL " + "AND expires_at>? AND (agent_id IS NULL OR agent_id=?) RETURNING agent_id", + (now, token, now, agent_id), + ).fetchone() + if invitation is None: + conn.rollback() + return EnrollOutcome.INVALID_TOKEN, None + bound = invitation[0] is not None + secret = secrets.token_urlsafe(32) + digest = hashlib.sha256(secret.encode()).hexdigest() + inserted = conn.execute( + "INSERT INTO agents(id,tags,enrolled_at,secret_hash) VALUES(?,?,?,?) " + "ON CONFLICT(id) DO NOTHING", (agent_id, tags, now, digest), + ).rowcount + if not inserted: + row = conn.execute( + "UPDATE agents SET secret_hash=? WHERE id=? AND secret_hash IS NULL AND ? " + "RETURNING tags", (digest, agent_id, bound), + ).fetchone() + if row is None: + conn.rollback() + return EnrollOutcome.CONFLICT, None + tags = row[0] + self.audit.append("agent_enrolled", actor=agent_id, target="server", + detail={"tags": tags, "bound": bound, "reclaimed": not inserted}) + return EnrollOutcome.ENROLLED, secret - def upsert_agent(self, agent_id: str, tags: str = "") -> None: - self._conn.execute( - "INSERT INTO agents(id,tags,enrolled_at) VALUES(?,?,?) " - "ON CONFLICT(id) DO UPDATE SET tags=excluded.tags", - (agent_id, tags, datetime.now(UTC).isoformat()), - ) - self._conn.commit() + def authenticate_agent(self, token: str) -> str | None: + digest = hashlib.sha256(token.encode()).hexdigest() + row = self._conn.execute("SELECT id FROM agents WHERE secret_hash=?", (digest,)).fetchone() + return str(row[0]) if row else None def list_agents(self) -> list[dict[str, Any]]: rows = self._conn.execute("SELECT id,tags,enrolled_at FROM agents").fetchall() diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..0843e78 --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,140 @@ +from __future__ import annotations + +import hashlib +import os +import sqlite3 +from collections import namedtuple +from collections.abc import Callable +from pathlib import Path +from typing import Any + +import pytest +from fastapi.testclient import TestClient + +from shadowgate.config import Settings, get_settings +from shadowgate.server.app import create_app + +TOKENS = '{"tok-admin":"admin","tok-op":"operator","tok-view":"viewer"}' +AGENT_HEADER = "X-ShadowGate-Agent-Token" + +EnrollResult = namedtuple("EnrollResult", "agent_token token status_code") + + +@pytest.fixture(autouse=True) +def _isolate_settings_sources(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> Any: + """Keep every test independent of the caller's configuration. + + ``Settings`` reads ``SHADOWGATE_*`` environment variables and a ``.env`` file in the + working directory. Without this fixture, a developer shell (or ``run.sh``) that + exports operator tokens silently switches open-mode tests to RBAC mode. + """ + for name in list(os.environ): + if name.upper().startswith("SHADOWGATE_"): + monkeypatch.delenv(name) + monkeypatch.chdir(tmp_path) + get_settings.cache_clear() + yield + get_settings.cache_clear() + + +def _paths(tmp_path: Path, **overrides: Any) -> dict[str, Any]: + base: dict[str, Any] = { + "db_path": str(tmp_path / "sg.db"), + "data_dir": str(tmp_path / "data"), + "audit_log_path": str(tmp_path / "audit.log"), + "org_key_path": str(tmp_path / "org.key"), + "ca_key_path": str(tmp_path / "ca.key"), + "ca_cert_path": str(tmp_path / "ca.crt"), + } + base.update(overrides) + return base + + +def sha256_hex(value: str) -> str: + return hashlib.sha256(value.encode()).hexdigest() + + +def fetchall(path: str | Path, sql: str, params: tuple[Any, ...] = ()) -> list[tuple[Any, ...]]: + conn = sqlite3.connect(str(path)) + try: + return conn.execute(sql, params).fetchall() + finally: + conn.close() + + +@pytest.fixture +def settings_factory(tmp_path: Path) -> Callable[..., Settings]: + def make(**overrides: Any) -> Settings: + return Settings(**_paths(tmp_path, **overrides)) + + return make + + +@pytest.fixture +def open_client(tmp_path: Path) -> Any: + settings = Settings(**_paths(tmp_path, insecure_dev=True, api_tokens_json="")) + with TestClient(create_app(settings)) as client: + yield client + + +@pytest.fixture +def rbac_client(tmp_path: Path) -> Any: + settings = Settings(**_paths(tmp_path, api_tokens_json=TOKENS)) + with TestClient(create_app(settings)) as client: + yield client + + +@pytest.fixture +def admin_h() -> dict[str, str]: + return {"Authorization": "Bearer tok-admin"} + + +@pytest.fixture +def op_h() -> dict[str, str]: + return {"Authorization": "Bearer tok-op"} + + +@pytest.fixture +def view_h() -> dict[str, str]: + return {"Authorization": "Bearer tok-view"} + + +@pytest.fixture +def agent_h() -> Callable[[str], dict[str, str]]: + def make(token: str) -> dict[str, str]: + return {AGENT_HEADER: token} + + return make + + +@pytest.fixture +def mint() -> Callable[..., str]: + def make(client: Any, admin_header: dict[str, str], agent_id: str | None = None) -> str: + body = {"agent_id": agent_id} if agent_id is not None else None + resp = client.post("/tokens", headers=admin_header, json=body) + assert resp.status_code == 200, resp.text + return resp.json()["token"] + + return make + + +@pytest.fixture +def enroll() -> Callable[..., EnrollResult]: + def make( + client: Any, + admin_header: dict[str, str], + agent_id: str, + tags: str = "", + token: str | None = None, + ) -> EnrollResult: + if token is None: + resp = client.post("/tokens", headers=admin_header) + assert resp.status_code == 200, resp.text + token = resp.json()["token"] + resp = client.post( + "/enroll", json={"agent_id": agent_id, "token": token, "tags": tags} + ) + agent_token = resp.json().get("agent_token") if resp.status_code == 200 else None + return EnrollResult(agent_token=agent_token, token=token, status_code=resp.status_code) + + return make diff --git a/tests/test_agent_auth.py b/tests/test_agent_auth.py new file mode 100644 index 0000000..69437f2 --- /dev/null +++ b/tests/test_agent_auth.py @@ -0,0 +1,482 @@ +from __future__ import annotations + +import sqlite3 +import threading +from typing import Any + +import httpx +import pytest +from conftest import AGENT_HEADER, fetchall, sha256_hex + +from shadowgate.agent.executor import Executor +from shadowgate.agent.poll import AgentAuthError, Poller +from shadowgate.plugins.base import Registry +from shadowgate.plugins.loader import load_builtins +from shadowgate.server.app import create_app +from shadowgate.server.store import Store + +RUNBOOK = { + "name": "demo", + "max_concurrent": 2, + "steps": [ + {"name": "inventory", "action": "system_info", "targets": {"tag": "linux"}}, + { + "name": "disk", + "action": "disk_health", + "targets": {"tag": "linux"}, + "depends_on": ["inventory"], + }, + { + "name": "compensate-disk", + "action": "disk_health", + "targets": {"tag": "linux"}, + "compensate_for": "disk", + }, + ], +} + + +def _ah(token: str) -> dict[str, str]: + return {AGENT_HEADER: token} + + +def _audit_entries(client: Any) -> list[dict[str, Any]]: + resp = client.get("/audit", headers={"Authorization": "Bearer tok-view"}) + return resp.json()["entries"] + + +def _audit_events(client: Any) -> list[str]: + return [e["event"] for e in _audit_entries(client)] + + +def test_t2a_enroll_returns_agent_token_once(rbac_client, admin_h, mint): + token = mint(rbac_client, admin_h) + resp = rbac_client.post( + "/enroll", json={"agent_id": "a1", "token": token, "tags": "linux"} + ) + assert resp.status_code == 200 + body = resp.json() + assert body["status"] == "enrolled" + assert body["agent_id"] == "a1" + assert body["agent_token"] + assert resp.headers.get("Cache-Control") == "no-store" + + entry = next(e for e in _audit_entries(rbac_client) if e["event"] == "agent_enrolled") + assert entry["detail"]["tags"] == "linux" + assert entry["detail"]["reclaimed"] is False + assert entry["detail"]["bound"] is False + + +def test_t2b_only_hash_stored_and_no_plaintext(rbac_client, admin_h, mint, tmp_path): + token = mint(rbac_client, admin_h) + agent_token = rbac_client.post( + "/enroll", json={"agent_id": "a1", "token": token} + ).json()["agent_token"] + + rows = fetchall(tmp_path / "sg.db", "SELECT secret_hash FROM agents WHERE id='a1'") + assert rows and rows[0][0] == sha256_hex(agent_token) + + conn = sqlite3.connect(str(tmp_path / "sg.db")) + conn.execute("PRAGMA wal_checkpoint(FULL)") + conn.close() + blob = b"" + for name in ("sg.db", "sg.db-wal", "sg.db-shm"): + candidate = tmp_path / name + if candidate.exists(): + blob += candidate.read_bytes() + assert agent_token.encode() not in blob + assert agent_token not in (tmp_path / "audit.log").read_text() + + +def test_t2c_conflict_keeps_token_unburned(rbac_client, admin_h, mint): + first = mint(rbac_client, admin_h) + assert rbac_client.post( + "/enroll", json={"agent_id": "a1", "token": first} + ).status_code == 200 + + second = mint(rbac_client, admin_h) + conflict = rbac_client.post("/enroll", json={"agent_id": "a1", "token": second}) + assert conflict.status_code == 409 + + reuse = rbac_client.post("/enroll", json={"agent_id": "a2", "token": second}) + assert reuse.status_code == 200 + + +def test_t2d_garbage_token_for_existing_id_is_403(rbac_client, admin_h, mint): + token = mint(rbac_client, admin_h) + rbac_client.post("/enroll", json={"agent_id": "a1", "token": token}) + resp = rbac_client.post("/enroll", json={"agent_id": "a1", "token": "garbage"}) + assert resp.status_code == 403 + + +def test_t2e_bound_token_wrong_id_is_403(rbac_client, admin_h, mint): + token = mint(rbac_client, admin_h, agent_id="a1") + resp = rbac_client.post("/enroll", json={"agent_id": "a2", "token": token}) + assert resp.status_code == 403 + + +def test_t2f_legacy_db_migration_and_reclaim(tmp_path, settings_factory): + db = tmp_path / "legacy.db" + conn = sqlite3.connect(db) + conn.execute( + "CREATE TABLE agents(id TEXT PRIMARY KEY, tags TEXT NOT NULL DEFAULT '', " + "enrolled_at TEXT NOT NULL)" + ) + conn.execute("INSERT INTO agents VALUES('legacy','linux','2020-01-01')") + conn.commit() + conn.close() + + settings = settings_factory(db_path=str(db), insecure_dev=True, api_tokens_json="") + store = Store(str(db)) + assert "secret_hash" in [r[1] for r in store._conn.execute("PRAGMA table_info(agents)")] + + from fastapi.testclient import TestClient + + with TestClient(create_app(settings)) as client: + assert client.post("/agent/poll", json={}).status_code == 401 + + bound = client.post("/tokens", json={"agent_id": "legacy"}).json()["token"] + reclaim = client.post( + "/enroll", json={"agent_id": "legacy", "token": bound, "tags": "newtag"} + ) + assert reclaim.status_code == 200 + agent_token = reclaim.json()["agent_token"] + tags = fetchall(tmp_path / "legacy.db", "SELECT tags FROM agents WHERE id='legacy'") + assert tags[0][0] == "linux" + entry = next(e for e in _audit_entries(client) if e["event"] == "agent_enrolled") + assert entry["detail"]["tags"] == "linux" + assert entry["detail"]["reclaimed"] is True + assert entry["detail"]["bound"] is True + assert client.post("/agent/poll", headers=_ah(agent_token), json={}).status_code == 200 + + unbound = client.post("/tokens").json()["token"] + assert client.post( + "/enroll", json={"agent_id": "legacy", "token": unbound} + ).status_code == 409 + + +def test_t2g_concurrent_same_id_enroll_one_wins(tmp_path, settings_factory): + from shadowgate.server.store import EnrollOutcome + + store = Store(settings_factory(insecure_dev=True).db_path) + t1 = store.mint_token() + t2 = store.mint_token() + outcomes: list[EnrollOutcome] = [] + barrier = threading.Barrier(2) + + def worker(token: str) -> None: + barrier.wait() + outcome, _ = store.enroll_agent("race", token, "") + outcomes.append(outcome) + + threads = [threading.Thread(target=worker, args=(t,)) for t in (t1, t2)] + for t in threads: + t.start() + for t in threads: + t.join() + + assert sorted(o.value for o in outcomes) == ["conflict", "enrolled"] + + +def test_t2g2_concurrent_bound_reclaim_one_wins(tmp_path, settings_factory): + from shadowgate.server.store import EnrollOutcome + + db = tmp_path / "legacy.db" + conn = sqlite3.connect(db) + conn.execute( + "CREATE TABLE agents(id TEXT PRIMARY KEY, tags TEXT NOT NULL DEFAULT '', " + "enrolled_at TEXT NOT NULL)" + ) + conn.execute("INSERT INTO agents VALUES('legacy','linux','2020-01-01')") + conn.commit() + conn.close() + + store = Store(str(db)) + t1 = store.mint_token(agent_id="legacy") + t2 = store.mint_token(agent_id="legacy") + outcomes: list[EnrollOutcome] = [] + barrier = threading.Barrier(2) + + def worker(token: str) -> None: + barrier.wait() + outcome, _ = store.enroll_agent("legacy", token, "") + outcomes.append(outcome) + + threads = [threading.Thread(target=worker, args=(t,)) for t in (t1, t2)] + for t in threads: + t.start() + for t in threads: + t.join() + + assert sorted(o.value for o in outcomes) == ["conflict", "enrolled"] + + +def test_t2h_agent_routes_require_header(rbac_client, admin_h, op_h, enroll): + agent_token = enroll(rbac_client, admin_h, "a1").agent_token + jid = rbac_client.post( + "/jobs", json={"agent_id": "a1", "action": "system_info"}, headers=op_h + ).json()["job_id"] + + before = _audit_events(rbac_client) + assert rbac_client.post("/agent/poll", json={}).status_code == 401 + assert rbac_client.post( + "/agent/result", json={"job_id": jid, "ok": True} + ).status_code == 401 + assert _audit_events(rbac_client) == before + assert agent_token + + +def test_t2i_other_agent_cannot_claim(rbac_client, admin_h, op_h, enroll, agent_h, tmp_path): + enroll(rbac_client, admin_h, "a1") + a2 = enroll(rbac_client, admin_h, "a2").agent_token + jid = rbac_client.post( + "/jobs", json={"agent_id": "a1", "action": "system_info"}, headers=op_h + ).json()["job_id"] + + poll = rbac_client.post("/agent/poll", headers=agent_h(a2), json={}) + assert poll.json()["job"] is None + rows = fetchall(tmp_path / "sg.db", "SELECT status FROM qjobs WHERE id=?", (jid,)) + assert rows[0][0] == "queued" + + +def test_t2j_other_agent_cannot_complete(rbac_client, admin_h, op_h, enroll, agent_h, tmp_path): + a1 = enroll(rbac_client, admin_h, "a1").agent_token + a2 = enroll(rbac_client, admin_h, "a2").agent_token + jid = rbac_client.post( + "/jobs", json={"agent_id": "a1", "action": "system_info"}, headers=op_h + ).json()["job_id"] + rbac_client.post("/agent/poll", headers=agent_h(a1), json={}) + + before = _audit_events(rbac_client) + resp = rbac_client.post( + "/agent/result", headers=agent_h(a2), json={"job_id": jid, "ok": True} + ) + assert resp.status_code == 404 + rows = fetchall(tmp_path / "sg.db", "SELECT status FROM qjobs WHERE id=?", (jid,)) + assert rows[0][0] == "running" + assert _audit_events(rbac_client) == before + + +def test_t2k_forged_failure_does_not_fail_run( + rbac_client, admin_h, op_h, enroll, agent_h +): + a1 = enroll(rbac_client, admin_h, "a1", tags="linux").agent_token + a2 = enroll(rbac_client, admin_h, "a2", tags="linux").agent_token + rbac_client.post("/runbooks", json=RUNBOOK, headers=admin_h) + run_id = rbac_client.post("/runs", json={"runbook": "demo"}, headers=op_h).json()["run_id"] + + job = rbac_client.post("/agent/poll", headers=agent_h(a1), json={}).json()["job"] + assert job["action"] == "system_info" + + resp = rbac_client.post( + "/agent/result", headers=agent_h(a2), json={"job_id": job["id"], "ok": False} + ) + assert resp.status_code == 404 + assert rbac_client.get(f"/runs/{run_id}", headers=op_h).json()["status"] == "running" + assert "compensation_enqueued" not in _audit_events(rbac_client) + assert a2 + + +def test_t2l_duplicate_result_is_idempotent(rbac_client, admin_h, op_h, enroll, agent_h): + a1 = enroll(rbac_client, admin_h, "a1").agent_token + jid = rbac_client.post( + "/jobs", json={"agent_id": "a1", "action": "system_info"}, headers=op_h + ).json()["job_id"] + rbac_client.post("/agent/poll", headers=agent_h(a1), json={}) + + first = rbac_client.post( + "/agent/result", headers=agent_h(a1), json={"job_id": jid, "ok": True} + ) + second = rbac_client.post( + "/agent/result", headers=agent_h(a1), json={"job_id": jid, "ok": True} + ) + assert first.json()["status"] == "recorded" + assert second.json()["status"] == "duplicate" + assert _audit_events(rbac_client).count("job_completed") == 1 + + +def test_t2m_conflicting_result_is_409(rbac_client, admin_h, op_h, enroll, agent_h, tmp_path): + a1 = enroll(rbac_client, admin_h, "a1").agent_token + jid = rbac_client.post( + "/jobs", json={"agent_id": "a1", "action": "system_info"}, headers=op_h + ).json()["job_id"] + rbac_client.post("/agent/poll", headers=agent_h(a1), json={}) + rbac_client.post("/agent/result", headers=agent_h(a1), json={"job_id": jid, "ok": True}) + + resp = rbac_client.post( + "/agent/result", headers=agent_h(a1), json={"job_id": jid, "ok": False} + ) + assert resp.status_code == 409 + rows = fetchall(tmp_path / "sg.db", "SELECT status FROM qjobs WHERE id=?", (jid,)) + assert rows[0][0] == "done" + + +def test_t2n_unknown_job_is_404(rbac_client, admin_h, enroll, agent_h): + a1 = enroll(rbac_client, admin_h, "a1").agent_token + before = _audit_events(rbac_client) + resp = rbac_client.post( + "/agent/result", headers=agent_h(a1), json={"job_id": "nope", "ok": True} + ) + assert resp.status_code == 404 + assert _audit_events(rbac_client) == before + + +def test_t2o_credentials_not_interchangeable(rbac_client, admin_h, enroll, agent_h): + agent_token = enroll(rbac_client, admin_h, "a1").agent_token + as_bearer = {"Authorization": f"Bearer {agent_token}"} + assert rbac_client.get("/agents", headers=as_bearer).status_code == 401 + assert rbac_client.post("/agent/poll", headers=_ah("tok-op"), json={}).status_code == 401 + + +class _Handler: + def __init__(self) -> None: + self.requests: list[httpx.Request] = [] + self.poll_mode = "job" + self.result_mode = "recorded" + self.result_calls = 0 + + def __call__(self, request: httpx.Request) -> httpx.Response: + self.requests.append(request) + if request.url.path == "/agent/poll": + if self.poll_mode == "job": + return httpx.Response( + 200, json={"job": {"id": "j1", "action": "system_info", "params": {}}} + ) + if self.poll_mode == "nonjson": + return httpx.Response(200, text="not json") + if self.poll_mode == "garbage": + return httpx.Response(200, json={"job": "garbage"}) + if self.poll_mode == "badid": + return httpx.Response(200, json={"job": {"id": 1, "action": "system_info"}}) + return httpx.Response(200, json={"job": None}) + if request.url.path == "/agent/result": + self.result_calls += 1 + mode = self.result_mode + if mode == "500": + return httpx.Response(500) + if mode == "422": + return httpx.Response(422) + if mode == "401": + return httpx.Response(401) + if mode == "duplicate": + return httpx.Response(200, json={"status": "duplicate"}) + if mode == "unknown": + return httpx.Response(200, json={"x": 1}) + if mode == "nonjson": + return httpx.Response(200, text="not json") + return httpx.Response(200, json={"status": "recorded"}) + return httpx.Response(404) + + +def _executor() -> Executor: + registry = Registry() + load_builtins(registry) + return Executor(registry, agent_id="a1") + + +def test_t2p_poller_sends_header_and_handles_duplicate(): + handler = _Handler() + poller = Poller(_executor(), "http://server", agent_token="secret", retry_backoff=0) + client = poller.make_client(transport=httpx.MockTransport(handler)) + + assert poller.poll_once(client) is True + assert any(r.headers.get(AGENT_HEADER) == "secret" for r in handler.requests) + result_reqs = [r for r in handler.requests if r.url.path == "/agent/result"] + assert result_reqs and result_reqs[0].headers.get(AGENT_HEADER) == "secret" + + handler.result_mode = "duplicate" + assert poller.poll_once(client) is True + + +def test_t2p_poller_raises_on_401(): + handler = _Handler() + handler.result_mode = "401" + poller = Poller(_executor(), "http://server", agent_token="secret", retry_backoff=0) + client = poller.make_client(transport=httpx.MockTransport(handler)) + with pytest.raises(AgentAuthError): + poller.poll_once(client) + + +def test_t2p_poller_retries_result_after_500(): + handler = _Handler() + handler.result_mode = "500" + poller = Poller( + _executor(), + "http://server", + agent_token="secret", + result_retries=2, + retry_backoff=0, + ) + client = poller.make_client(transport=httpx.MockTransport(handler)) + poller.poll_once(client) + assert handler.result_calls == 3 + + +@pytest.mark.parametrize("mode", ["unknown", "nonjson"]) +def test_t2p_result_2xx_clears_pending(mode): + handler = _Handler() + handler.result_mode = mode + poller = Poller(_executor(), "http://server", agent_token="secret", retry_backoff=0) + client = poller.make_client(transport=httpx.MockTransport(handler)) + + assert poller.poll_once(client) is True + handler.poll_mode = "idle" + before = handler.result_calls + assert poller.poll_once(client) is False + assert handler.result_calls == before + + +def test_t2p_result_422_drops_pending(): + handler = _Handler() + handler.result_mode = "422" + poller = Poller(_executor(), "http://server", agent_token="secret", retry_backoff=0) + client = poller.make_client(transport=httpx.MockTransport(handler)) + + assert poller.poll_once(client) is True + handler.poll_mode = "idle" + before = handler.result_calls + assert poller.poll_once(client) is False + assert handler.result_calls == before + + +def test_t2p_poll_nonjson_returns_false(): + handler = _Handler() + handler.poll_mode = "nonjson" + poller = Poller(_executor(), "http://server", agent_token="secret", retry_backoff=0) + client = poller.make_client(transport=httpx.MockTransport(handler)) + assert poller.poll_once(client) is False + + +@pytest.mark.parametrize("mode", ["garbage", "badid"]) +def test_t2p_poll_invalid_job_returns_false(mode): + handler = _Handler() + handler.poll_mode = mode + poller = Poller(_executor(), "http://server", agent_token="secret", retry_backoff=0) + client = poller.make_client(transport=httpx.MockTransport(handler)) + assert poller.poll_once(client) is False + + +def test_t2q_expired_token_is_403(rbac_client, tmp_path): + store = Store(str(tmp_path / "sg.db")) + expired = store.mint_token(ttl_minutes=-1) + resp = rbac_client.post("/enroll", json={"agent_id": "a1", "token": expired}) + assert resp.status_code == 403 + + +def test_t2r_tokens_empty_body_unbound(rbac_client, admin_h): + resp = rbac_client.post("/tokens", headers=admin_h, json={}) + assert resp.status_code == 200 + token = resp.json()["token"] + enroll = rbac_client.post("/enroll", json={"agent_id": "fresh", "token": token}) + assert enroll.status_code == 200 + assert enroll.json()["agent_token"] + + +def test_t2s_result_missing_job_id_is_422(rbac_client, admin_h, enroll, agent_h): + agent_token = enroll(rbac_client, admin_h, "a1").agent_token + before = _audit_events(rbac_client) + resp = rbac_client.post( + "/agent/result", headers=agent_h(agent_token), json={"ok": True} + ) + assert resp.status_code == 422 + assert _audit_events(rbac_client) == before diff --git a/tests/test_auth.py b/tests/test_auth.py index ef8f784..2c2cbe5 100644 --- a/tests/test_auth.py +++ b/tests/test_auth.py @@ -1,3 +1,6 @@ +import base64 +import re + import pytest from fastapi.testclient import TestClient @@ -72,3 +75,82 @@ def test_rate_limit_on_tokens(tmp_path): assert c.post("/tokens", headers=_h("tok-admin")).status_code == 200 r = c.post("/tokens", headers=_h("tok-admin")) assert r.status_code == 429 + + +_PUBLIC = {"/healthz", "/", "/enroll"} +_DOCS = {"/openapi.json", "/docs", "/docs/oauth2-redirect", "/redoc"} +_EXPECTED_PROTECTED = { + "/agents", + "/jobs", + "/runs/{run_id}", + "/audit", + "/ui", + "/ui/agents", + "/ui/jobs", + "/ui/runs", + "/tokens", + "/runbooks", + "/runs", +} + + +def _iter_routes(routes): + for route in routes: + original = getattr(route, "original_router", None) + if original is not None: + yield from _iter_routes(original.routes) + else: + yield route + + +def test_t3a_route_inventory_requires_auth(rbac_client): + app = rbac_client.app + checked = 0 + checked_paths: set[str] = set() + for route in _iter_routes(app.routes): + path = getattr(route, "path", None) + methods = getattr(route, "methods", None) + if not path or not methods: + continue + if path in _PUBLIC or path.startswith("/agent/") or path in _DOCS: + continue + url = re.sub(r"{[^}]+}", "x", path) + for method in methods: + if method in {"HEAD", "OPTIONS"}: + continue + resp = rbac_client.request(method, url) + assert resp.status_code == 401, f"{method} {path} -> {resp.status_code}" + checked += 1 + checked_paths.add(path) + assert checked > 0 + assert checked_paths >= _EXPECTED_PROTECTED, _EXPECTED_PROTECTED - checked_paths + + +def test_t3b_role_boundaries(rbac_client, view_h, op_h): + for path in ("/agents", "/jobs", "/audit", "/ui", "/ui/agents", "/ui/jobs", "/ui/runs"): + assert rbac_client.get(path, headers=view_h).status_code == 200 + assert rbac_client.get("/runs/x", headers=view_h).status_code in (200, 404) + + assert rbac_client.post( + "/jobs", json={"agent_id": "a1", "action": "system_info"}, headers=view_h + ).status_code == 403 + assert rbac_client.post("/runbooks", json={}, headers=view_h).status_code == 403 + assert rbac_client.post("/tokens", headers=view_h).status_code == 403 + + assert rbac_client.post("/tokens", headers=op_h).status_code == 403 + assert rbac_client.post("/runbooks", json={}, headers=op_h).status_code == 403 + + +def test_t3c_dashboard_basic_auth(rbac_client): + anon = rbac_client.get("/ui") + assert anon.status_code == 401 + assert "Basic" in anon.headers.get("WWW-Authenticate", "") + + cred = base64.b64encode(b":tok-view").decode() + resp = rbac_client.get("/ui", headers={"Authorization": f"Basic {cred}"}) + assert resp.status_code == 200 + + +def test_t3d_docs_disabled(rbac_client): + assert rbac_client.get("/docs").status_code == 404 + assert rbac_client.get("/openapi.json").status_code == 404 diff --git a/tests/test_config_auth.py b/tests/test_config_auth.py new file mode 100644 index 0000000..06600f5 --- /dev/null +++ b/tests/test_config_auth.py @@ -0,0 +1,79 @@ +from __future__ import annotations + +import os +import subprocess +import sys + +import pytest +from conftest import TOKENS +from fastapi.testclient import TestClient + +from shadowgate.config import Settings +from shadowgate.server.app import create_app + + +def test_t1a_invalid_json_raises(settings_factory): + settings = settings_factory(api_tokens_json="{not json") + with pytest.raises(ValueError): + create_app(settings) + + +@pytest.mark.parametrize( + "bad", + [ + '["a"]', + '{"t":"root"}', + '{"":"admin"}', + '{"a b":"admin"}', + '{"a:b":"admin"}', + '{"t": 1}', + ], +) +def test_t1b_ill_typed_token_map_raises(settings_factory, bad): + settings = settings_factory(api_tokens_json=bad) + with pytest.raises(ValueError): + create_app(settings) + + +def test_t1c_empty_map_requires_insecure_dev(settings_factory): + with pytest.raises(ValueError): + create_app(settings_factory(api_tokens_json="", insecure_dev=False)) + + with pytest.warns(UserWarning): + app = create_app(settings_factory(api_tokens_json="", insecure_dev=True)) + assert app is not None + + +def test_t1d_env_json_enables_rbac(monkeypatch, tmp_path): + monkeypatch.setenv("SHADOWGATE_API_TOKENS_JSON", TOKENS) + settings = Settings( + db_path=str(tmp_path / "sg.db"), + data_dir=str(tmp_path / "data"), + audit_log_path=str(tmp_path / "audit.log"), + ) + with TestClient(create_app(settings)) as client: + assert client.post("/tokens").status_code == 401 + + +def test_t1e_env_alias_enables_rbac(monkeypatch, tmp_path): + monkeypatch.setenv("SHADOWGATE_API_TOKENS", TOKENS) + settings = Settings( + db_path=str(tmp_path / "sg.db"), + data_dir=str(tmp_path / "data"), + audit_log_path=str(tmp_path / "audit.log"), + ) + with TestClient(create_app(settings)) as client: + assert client.post("/tokens").status_code == 401 + + +def test_t1f_import_creates_no_files(tmp_path): + env = dict(os.environ) + result = subprocess.run( + [sys.executable, "-c", "import shadowgate.server.app"], + cwd=tmp_path, + capture_output=True, + text=True, + env=env, + ) + assert result.returncode == 0, result.stderr + assert list(tmp_path.iterdir()) == [] diff --git a/tests/test_env_precedence.py b/tests/test_env_precedence.py new file mode 100644 index 0000000..0b6e451 --- /dev/null +++ b/tests/test_env_precedence.py @@ -0,0 +1,243 @@ +"""Regression tests for operator-token configuration precedence (Blocker 3 / V2, V3). + +Precedence, highest first: + explicit ``Settings(...)`` arguments + > shell environment (``SHADOWGATE_API_TOKENS_JSON``, then legacy ``SHADOWGATE_API_TOKENS``) + > ``.env`` in the working directory + > ``run.sh`` development defaults (only when nothing above is configured). +""" + +from __future__ import annotations + +import os +import shutil +import stat +import subprocess +import sys +from pathlib import Path + +import pytest + +from shadowgate.config import Settings +from shadowgate.server.app import create_app + +REPO = Path(__file__).resolve().parent.parent +DEV_TOKENS = '{"admin-token":"admin","op-token":"operator","view-token":"viewer"}' +SHELL_JSON = '{"shell-json-token":"admin"}' +SHELL_LEGACY = '{"shell-legacy-token":"admin"}' +DOTENV_JSON = '{"dotenv-json-token":"admin"}' +DOTENV_LEGACY = '{"dotenv-legacy-token":"admin"}' +UNSET = "" + + +# --- Settings source precedence (pydantic-settings) -------------------------------- + + +def test_json_name_wins_over_legacy_name(monkeypatch): + monkeypatch.setenv("SHADOWGATE_API_TOKENS_JSON", SHELL_JSON) + monkeypatch.setenv("SHADOWGATE_API_TOKENS", SHELL_LEGACY) + assert Settings().api_tokens_json == SHELL_JSON + + +def test_dotenv_is_read_when_environment_is_empty(monkeypatch, tmp_path): + monkeypatch.chdir(tmp_path) + (tmp_path / ".env").write_text(f"SHADOWGATE_API_TOKENS_JSON='{DOTENV_JSON}'\n") + assert Settings().api_tokens_json == DOTENV_JSON + + +def test_dotenv_legacy_name_is_read(monkeypatch, tmp_path): + monkeypatch.chdir(tmp_path) + (tmp_path / ".env").write_text(f"SHADOWGATE_API_TOKENS='{DOTENV_LEGACY}'\n") + assert Settings().api_tokens_json == DOTENV_LEGACY + + +def test_environment_wins_over_dotenv(monkeypatch, tmp_path): + monkeypatch.chdir(tmp_path) + (tmp_path / ".env").write_text(f"SHADOWGATE_API_TOKENS_JSON='{DOTENV_JSON}'\n") + monkeypatch.setenv("SHADOWGATE_API_TOKENS_JSON", SHELL_JSON) + assert Settings().api_tokens_json == SHELL_JSON + + +def test_explicit_argument_wins_over_environment_and_dotenv(monkeypatch, tmp_path): + monkeypatch.chdir(tmp_path) + (tmp_path / ".env").write_text(f"SHADOWGATE_API_TOKENS_JSON='{DOTENV_JSON}'\n") + monkeypatch.setenv("SHADOWGATE_API_TOKENS_JSON", SHELL_JSON) + assert Settings(api_tokens_json="").api_tokens_json == "" + + +# --- run.sh launcher (real script, stubbed `uv`; nothing is installed or started) --- + + +def _run_launcher( + tmp_path: Path, env_extra: dict[str, str], dotenv: str | None, *args: str +) -> tuple[list[dict[str, str]], Path]: + project = tmp_path / "project" + project.mkdir() + shutil.copy2(REPO / "run.sh", project / "run.sh") + if dotenv is not None: + (project / ".env").write_text(dotenv) + + stub_dir = tmp_path / "bin" + stub_dir.mkdir() + log = tmp_path / "uv-calls.log" + stub = stub_dir / "uv" + stub.write_text( + "#!/bin/sh\n" + f'{{ echo "ARGS=$*"; echo "JSON=${{SHADOWGATE_API_TOKENS_JSON-{UNSET}}}"; ' + f'echo "LEGACY=${{SHADOWGATE_API_TOKENS-{UNSET}}}"; echo "--"; }} >> "{log}"\n' + ) + stub.chmod(stub.stat().st_mode | stat.S_IEXEC) + + env = {k: v for k, v in os.environ.items() if not k.upper().startswith("SHADOWGATE_")} + env["PATH"] = f"{stub_dir}{os.pathsep}{env.get('PATH', '')}" + env.update(env_extra) + result = subprocess.run( + ["bash", str(project / "run.sh"), *args], + env=env, + capture_output=True, + text=True, + timeout=30, + ) + assert result.returncode == 0, result.stderr + + calls: list[dict[str, str]] = [] + current: dict[str, str] = {} + for line in log.read_text().splitlines(): + if line == "--": + calls.append(current) + current = {} + else: + key, _, value = line.partition("=") + current[key] = value + return calls, project + + +def _effective_tokens( + monkeypatch: pytest.MonkeyPatch, project: Path, server_call: dict[str, str] +) -> str: + """Resolve Settings the way the launched server would: its env plus ./.env.""" + monkeypatch.chdir(project) + for name, key in (("SHADOWGATE_API_TOKENS_JSON", "JSON"), ("SHADOWGATE_API_TOKENS", "LEGACY")): + if server_call[key] == UNSET: + monkeypatch.delenv(name, raising=False) + else: + monkeypatch.setenv(name, server_call[key]) + return Settings().api_tokens_json + + +@pytest.mark.parametrize( + ("env_extra", "dotenv", "exported_json", "effective"), + [ + pytest.param({}, None, DEV_TOKENS, DEV_TOKENS, id="nothing-configured-uses-dev-defaults"), + pytest.param( + {}, + f"SHADOWGATE_API_TOKENS_JSON='{DOTENV_JSON}'\n", + UNSET, + DOTENV_JSON, + id="dotenv-json-not-overridden", + ), + pytest.param( + {}, + f"export SHADOWGATE_API_TOKENS='{DOTENV_LEGACY}'\n", + UNSET, + DOTENV_LEGACY, + id="dotenv-legacy-not-overridden", + ), + pytest.param( + {"SHADOWGATE_API_TOKENS_JSON": SHELL_JSON}, + f"SHADOWGATE_API_TOKENS_JSON='{DOTENV_JSON}'\n", + SHELL_JSON, + SHELL_JSON, + id="shell-wins-over-dotenv", + ), + pytest.param( + {"shadowgate_api_tokens_json": SHELL_JSON}, + None, + UNSET, + SHELL_JSON, + id="shell-lowercase-name-respected", + ), + pytest.param( + {}, + f"shadowgate_api_tokens_json = '{DOTENV_JSON}' # comment\n", + UNSET, + DOTENV_JSON, + id="dotenv-lowercase-spaced-not-overridden", + ), + pytest.param( + {}, + f"# SHADOWGATE_API_TOKENS_JSON='{DOTENV_JSON}'\n #export SHADOWGATE_API_TOKENS=x\n", + DEV_TOKENS, + DEV_TOKENS, + id="dotenv-commented-out-uses-dev-defaults", + ), + pytest.param( + {"SHADOWGATE_API_TOKENS": SHELL_LEGACY}, + None, + None, # whether run.sh copies the legacy name is an implementation detail + SHELL_LEGACY, + id="shell-legacy-name-respected", + ), + ], +) +def test_launcher_token_precedence( + monkeypatch, tmp_path, env_extra, dotenv, exported_json, effective +): + calls, project = _run_launcher(tmp_path, env_extra, dotenv) + server_call = calls[-1] + for name, value in env_extra.items(): # inherited by the server process unchanged + monkeypatch.setenv(name, value) + assert server_call["ARGS"].startswith("run uvicorn --factory shadowgate.server.app:create_app") + if exported_json is not None: + assert server_call["JSON"] == exported_json + assert _effective_tokens(monkeypatch, project, server_call) == effective + + +def test_launcher_respects_explicit_empty_tokens_and_server_fails_closed(monkeypatch, tmp_path): + calls, project = _run_launcher(tmp_path, {"SHADOWGATE_API_TOKENS_JSON": ""}, None) + assert calls[-1]["JSON"] == "" + settings = Settings( + db_path=str(tmp_path / "sg.db"), + data_dir=str(tmp_path / "data"), + audit_log_path=str(tmp_path / "audit.log"), + api_tokens_json=_effective_tokens(monkeypatch, project, calls[-1]), + ) + with pytest.raises(ValueError): + create_app(settings) + + +def test_launcher_check_mode_exports_no_tokens(tmp_path): + calls, _ = _run_launcher(tmp_path, {}, None, "--check") + assert [c["ARGS"] for c in calls] == [ + "sync --extra dev", + "run ruff check src tests", + "run mypy", + "run pytest -q", + ] + assert all(c["JSON"] == UNSET and c["LEGACY"] == UNSET for c in calls) + + +# --- the suite itself must not depend on the caller's configuration --------------- + + +def test_suite_is_isolated_from_caller_token_configuration(tmp_path): + """The six tests that failed under `run.sh --check` must pass with tokens configured.""" + (tmp_path / ".env").write_text(f"SHADOWGATE_API_TOKENS_JSON='{DOTENV_JSON}'\n") + env = dict(os.environ) + env["SHADOWGATE_API_TOKENS_JSON"] = DEV_TOKENS + env["SHADOWGATE_API_TOKENS"] = DEV_TOKENS + targets = [ + f"{REPO}/tests/test_server.py", + f"{REPO}/tests/test_runs.py", + f"{REPO}/tests/test_agent_auth.py::test_t2f_legacy_db_migration_and_reclaim", + ] + result = subprocess.run( + [sys.executable, "-m", "pytest", "-q", "-p", "no:cacheprovider", *targets], + cwd=tmp_path, + env=env, + capture_output=True, + text=True, + timeout=120, + ) + assert result.returncode == 0, result.stdout[-2000:] + assert " passed" in result.stdout and " failed" not in result.stdout diff --git a/tests/test_queue.py b/tests/test_queue.py index f5a7684..e51ecdc 100644 --- a/tests/test_queue.py +++ b/tests/test_queue.py @@ -1,6 +1,6 @@ import threading -from shadowgate.server.queue import SqlQueue +from shadowgate.server.queue import CompletionOutcome, SqlQueue def test_concurrent_claim_exactly_once(tmp_path): @@ -16,12 +16,15 @@ def test_concurrent_claim_exactly_once(tmp_path): def worker(): local_q = SqlQueue(str(tmp_path / "q.db")) while True: - job = local_q.claim_next() + job = local_q.claim_next("agent-a") if job is None: return with lock: claimed.append(job.id) - local_q.complete(job.id, True, {}) + outcome = local_q.complete( + job.id, agent_id="agent-a", success=True, data={} + ) + assert outcome == CompletionOutcome.ACCEPTED threads = [threading.Thread(target=worker) for _ in range(n_workers)] for t in threads: @@ -32,3 +35,25 @@ def worker(): assert len(claimed) == n_jobs, f"expected {n_jobs} claims, got {len(claimed)}" assert len(set(claimed)) == n_jobs, f"duplicate claims: {len(claimed) - len(set(claimed))}" assert q.stats().get("done") == n_jobs + + +def test_scoped_claim_and_wrong_owner(tmp_path): + q = SqlQueue(str(tmp_path / "q.db")) + q.enqueue("j1", "a1", "system_info", {}) + + assert q.claim_next("a2") is None + + job = q.claim_next("a1") + assert job is not None and job.id == "j1" + + wrong = q.complete("j1", agent_id="a2", success=True, data={}) + assert wrong == CompletionOutcome.NOT_FOUND + + right = q.complete("j1", agent_id="a1", success=True, data={}) + assert right == CompletionOutcome.ACCEPTED + + dup = q.complete("j1", agent_id="a1", success=True, data={}) + assert dup == CompletionOutcome.DUPLICATE + + conflict = q.complete("j1", agent_id="a1", success=False, data={}) + assert conflict == CompletionOutcome.CONFLICT diff --git a/tests/test_runs.py b/tests/test_runs.py index 4537f14..c69b50d 100644 --- a/tests/test_runs.py +++ b/tests/test_runs.py @@ -1,8 +1,11 @@ import pytest +from conftest import AGENT_HEADER from fastapi.testclient import TestClient -from shadowgate.config import Settings -from shadowgate.server.app import create_app + +def _ah(token: str) -> dict[str, str]: + return {AGENT_HEADER: token} + RUNBOOK = { "name": "demo", @@ -27,6 +30,9 @@ @pytest.fixture def client(tmp_path): + from shadowgate.config import Settings + from shadowgate.server.app import create_app + settings = Settings( db_path=str(tmp_path / "sg.db"), data_dir=str(tmp_path / "data"), @@ -34,6 +40,8 @@ def client(tmp_path): org_key_path=str(tmp_path / "org.key"), ca_key_path=str(tmp_path / "ca.key"), ca_cert_path=str(tmp_path / "ca.crt"), + insecure_dev=True, + api_tokens_json="", ) app = create_app(settings) with TestClient(app) as c: @@ -42,27 +50,39 @@ def client(tmp_path): def _enroll(client, agent_id, tags): token = client.post("/tokens").json()["token"] - client.post("/enroll", json={"agent_id": agent_id, "token": token, "tags": tags}) + resp = client.post( + "/enroll", json={"agent_id": agent_id, "token": token, "tags": tags} + ) + assert resp.status_code == 200 + return resp.json()["agent_token"] def test_run_fanout_ordering_and_audit(client): - _enroll(client, "a1", "linux") - _enroll(client, "a2", "linux") + a1 = _enroll(client, "a1", "linux") + a2 = _enroll(client, "a2", "linux") r = client.post("/runbooks", json=RUNBOOK) assert r.status_code == 200 run_id = client.post("/runs", json={"runbook": "demo"}).json()["run_id"] # first wave: inventory for a1 and a2 (max_concurrent=2, so no more) - for agent in ("a1", "a2"): - job = client.post("/agent/poll", json={"agent_id": agent}).json()["job"] + for agent_token in (a1, a2): + job = client.post("/agent/poll", headers=_ah(agent_token), json={}).json()["job"] assert job is not None and job["action"] == "system_info" - client.post("/agent/result", json={"job_id": job["id"], "ok": True}) + client.post( + "/agent/result", + headers=_ah(agent_token), + json={"job_id": job["id"], "ok": True}, + ) # disk step should now be enqueued for both - for agent in ("a1", "a2"): - job = client.post("/agent/poll", json={"agent_id": agent}).json()["job"] + for agent_token in (a1, a2): + job = client.post("/agent/poll", headers=_ah(agent_token), json={}).json()["job"] assert job is not None and job["action"] == "disk_health" - client.post("/agent/result", json={"job_id": job["id"], "ok": True}) + client.post( + "/agent/result", + headers=_ah(agent_token), + json={"job_id": job["id"], "ok": True}, + ) status = client.get(f"/runs/{run_id}").json() assert status["status"] == "done" @@ -77,23 +97,27 @@ def test_run_fanout_ordering_and_audit(client): def test_failure_triggers_compensation(client): - _enroll(client, "a1", "linux") + a1 = _enroll(client, "a1", "linux") client.post("/runbooks", json=RUNBOOK) run_id = client.post("/runs", json={"runbook": "demo"}).json()["run_id"] - job = client.post("/agent/poll", json={"agent_id": "a1"}).json()["job"] - client.post("/agent/result", json={"job_id": job["id"], "ok": True}) + job = client.post("/agent/poll", headers=_ah(a1), json={}).json()["job"] + client.post( + "/agent/result", headers=_ah(a1), json={"job_id": job["id"], "ok": True} + ) # disk step now queued; fail it - job = client.post("/agent/poll", json={"agent_id": "a1"}).json()["job"] + job = client.post("/agent/poll", headers=_ah(a1), json={}).json()["job"] assert job["action"] == "disk_health" - client.post("/agent/result", json={"job_id": job["id"], "ok": False}) + client.post( + "/agent/result", headers=_ah(a1), json={"job_id": job["id"], "ok": False} + ) status = client.get(f"/runs/{run_id}").json() assert status["status"] == "failed" # compensation job for disk should be claimable - job = client.post("/agent/poll", json={"agent_id": "a1"}).json()["job"] + job = client.post("/agent/poll", headers=_ah(a1), json={}).json()["job"] assert job is not None and job["action"] == "disk_health" events = [e["event"] for e in client.get("/audit").json()["entries"]] diff --git a/tests/test_server.py b/tests/test_server.py index 7c975f6..9280f48 100644 --- a/tests/test_server.py +++ b/tests/test_server.py @@ -1,64 +1,63 @@ -import pytest -from fastapi.testclient import TestClient +from conftest import AGENT_HEADER -from shadowgate.config import Settings -from shadowgate.server.app import create_app - -@pytest.fixture -def client(tmp_path): - settings = Settings( - db_path=str(tmp_path / "sg.db"), - data_dir=str(tmp_path / "data"), - audit_log_path=str(tmp_path / "audit.log"), - org_key_path=str(tmp_path / "org.key"), - ca_key_path=str(tmp_path / "ca.key"), - ca_cert_path=str(tmp_path / "ca.crt"), - ) - app = create_app(settings) - with TestClient(app) as c: - yield c +def _ah(token: str) -> dict[str, str]: + return {AGENT_HEADER: token} -def test_enroll_token_burned_once(client): - token = client.post("/tokens").json()["token"] - r1 = client.post("/enroll", json={"agent_id": "a1", "token": token, "tags": "linux,lab"}) +def test_enroll_token_burned_once(open_client): + token = open_client.post("/tokens").json()["token"] + r1 = open_client.post( + "/enroll", json={"agent_id": "a1", "token": token, "tags": "linux,lab"} + ) assert r1.status_code == 200 - r2 = client.post("/enroll", json={"agent_id": "a2", "token": token}) + assert r1.json()["agent_token"] + r2 = open_client.post("/enroll", json={"agent_id": "a2", "token": token}) assert r2.status_code == 403 -def test_job_lifecycle_and_audit(client): - token = client.post("/tokens").json()["token"] - client.post("/enroll", json={"agent_id": "a1", "token": token, "tags": "linux"}) - jid = client.post("/jobs", json={"agent_id": "a1", "action": "system_info"}).json()["job_id"] +def test_job_lifecycle_and_audit(open_client): + token = open_client.post("/tokens").json()["token"] + enrolled = open_client.post( + "/enroll", json={"agent_id": "a1", "token": token, "tags": "linux"} + ) + agent_token = enrolled.json()["agent_token"] + jid = open_client.post( + "/jobs", json={"agent_id": "a1", "action": "system_info"} + ).json()["job_id"] - poll = client.post("/agent/poll", json={"agent_id": "a1"}).json() + poll = open_client.post("/agent/poll", headers=_ah(agent_token), json={}).json() assert poll["job"] is not None assert poll["job"]["id"] == jid assert poll["job"]["action"] == "system_info" - res = client.post( - "/agent/result", json={"job_id": jid, "ok": True, "data": {"system": "Linux"}} + res = open_client.post( + "/agent/result", + headers=_ah(agent_token), + json={"job_id": jid, "ok": True, "data": {"system": "Linux"}}, ) assert res.status_code == 200 - stats = client.get("/jobs").json()["stats"] + stats = open_client.get("/jobs").json()["stats"] assert stats.get("done") == 1 - audit = client.get("/audit", params={"verify": True}).json() + audit = open_client.get("/audit", params={"verify": True}).json() assert audit["verified"] is True events = [e["event"] for e in audit["entries"]] assert events == ["agent_enrolled", "job_enqueued", "job_claimed", "job_completed"] -def test_poll_only_claims_own_jobs(client): - t1 = client.post("/tokens").json()["token"] - t2 = client.post("/tokens").json()["token"] - client.post("/enroll", json={"agent_id": "a1", "token": t1}) - client.post("/enroll", json={"agent_id": "a2", "token": t2}) - client.post("/jobs", json={"agent_id": "a1", "action": "system_info"}) - poll = client.post("/agent/poll", json={"agent_id": "a2"}).json() +def test_poll_only_claims_own_jobs(open_client): + t1 = open_client.post("/tokens").json()["token"] + t2 = open_client.post("/tokens").json()["token"] + a1 = open_client.post( + "/enroll", json={"agent_id": "a1", "token": t1} + ).json()["agent_token"] + a2 = open_client.post( + "/enroll", json={"agent_id": "a2", "token": t2} + ).json()["agent_token"] + open_client.post("/jobs", json={"agent_id": "a1", "action": "system_info"}) + poll = open_client.post("/agent/poll", headers=_ah(a2), json={}).json() assert poll["job"] is None - poll = client.post("/agent/poll", json={"agent_id": "a1"}).json() + poll = open_client.post("/agent/poll", headers=_ah(a1), json={}).json() assert poll["job"] is not None