From 323686df94722be81c75f8be7e4f4a357376a013 Mon Sep 17 00:00:00 2001 From: "Saransh Singh (Splo1t)" <148835673+5aranx@users.noreply.github.com> Date: Mon, 30 Nov 2026 16:47:41 +0530 Subject: [PATCH 1/5] N1: ignore other programs' keys in .env Only SHADOWGATE_* keys are read from .env; unknown SHADOWGATE_* keys are still rejected, and shadowgate server reports them and exits 2 instead of raising a traceback. --- CHANGELOG.md | 6 +++++ README.md | 4 ++-- docs/tracker.md | 2 +- src/shadowgate/cli/main.py | 9 +++++++- src/shadowgate/config.py | 43 ++++++++++++++++++++++++++++++++++-- tests/test_env_precedence.py | 31 ++++++++++++++++++++++++++ 6 files changed, 89 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5e69cdd..6fb7627 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,12 @@ All notable changes to ShadowGate are recorded here. The format follows [Semantic Versioning](https://semver.org/). The version is defined once, in `src/shadowgate/version.py`. +## [Unreleased] + +### Fixed +- A `.env` file may hold other programs' variables; only unknown `SHADOWGATE_*` keys are + rejected, and `shadowgate server` reports them without a traceback. + ## [0.1.0] - 2026-11-30 First pre-release. Suitable for loopback evaluation with several agents on one host; diff --git a/README.md b/README.md index 3cf91c2..9d95a51 100644 --- a/README.md +++ b/README.md @@ -93,8 +93,8 @@ uv sync --frozen --extra dev # creates .venv from uv.lock Settings are read from environment variables with the `SHADOWGATE_` prefix, or from a `.env` file in the working directory. Environment variables take precedence over `.env`. -A `.env` file may contain **only** ShadowGate settings: any other key, even one without -the prefix, makes startup fail with a validation error. +A `.env` file may also hold other programs' variables; they are ignored. An unknown +`SHADOWGATE_*` key (usually a typo) is rejected: `shadowgate server` names it and exits 2. | Variable | Default | Used for | |---|---|---| diff --git a/docs/tracker.md b/docs/tracker.md index 096adcc..4a6d7e3 100644 --- a/docs/tracker.md +++ b/docs/tracker.md @@ -1186,7 +1186,7 @@ Not changed: adding PEP 639 `license-files` to `pyproject.toml`, since the build ### 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. +**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. **Resolved (§14):** keys without the `SHADOWGATE_` prefix are now ignored; unknown `SHADOWGATE_*` keys are still rejected. ## 11. Concurrency fix: T11 serialization, T12 append lock, Poller 401 (2026-11-30) diff --git a/src/shadowgate/cli/main.py b/src/shadowgate/cli/main.py index db8a846..0e13c2f 100644 --- a/src/shadowgate/cli/main.py +++ b/src/shadowgate/cli/main.py @@ -53,11 +53,18 @@ def _registry() -> Registry: def cmd_server(args: argparse.Namespace) -> int: import uvicorn + from pydantic import ValidationError from shadowgate.config import get_settings from shadowgate.server.app import create_app - settings = get_settings() + try: + settings = get_settings() + except ValidationError as exc: + for error in exc.errors(): + name = ".".join(str(part) for part in error["loc"]) or "settings" + _err(f"invalid setting {name}: {error['msg']}") + return EXIT_CONFIG host = args.host or settings.host port = args.port if args.port is not None else settings.port try: diff --git a/src/shadowgate/config.py b/src/shadowgate/config.py index 3c5b7cd..b45694a 100644 --- a/src/shadowgate/config.py +++ b/src/shadowgate/config.py @@ -1,12 +1,39 @@ from functools import lru_cache +from typing import Any from pydantic import AliasChoices, Field -from pydantic_settings import BaseSettings, SettingsConfigDict +from pydantic_settings import ( + BaseSettings, + DotEnvSettingsSource, + PydanticBaseSettingsSource, + SettingsConfigDict, +) + +ENV_PREFIX = "SHADOWGATE_" + + +class _ShadowGateDotEnv(DotEnvSettingsSource): + """Read ``.env`` but skip keys that belong to other programs. + + A shared ``.env`` often holds other tools' variables. Only ``SHADOWGATE_*`` keys are + ShadowGate's; an unknown ``SHADOWGATE_*`` key (a typo) is still rejected. + """ + + def __call__(self) -> dict[str, Any]: + known = set(self.settings_cls.model_fields) + for field in self.settings_cls.model_fields.values(): + if isinstance(field.validation_alias, AliasChoices): + known.update(str(choice) for choice in field.validation_alias.choices) + return { + key: value + for key, value in super().__call__().items() + if key in known or key.upper().startswith(ENV_PREFIX) + } class Settings(BaseSettings): model_config = SettingsConfigDict( - env_prefix="SHADOWGATE_", env_file=".env", populate_by_name=True + env_prefix=ENV_PREFIX, env_file=".env", populate_by_name=True ) db_path: str = "shadowgate.db" @@ -24,6 +51,18 @@ class Settings(BaseSettings): ) rate_limit_per_minute: int = 60 + @classmethod + def settings_customise_sources( + cls, + settings_cls: type[BaseSettings], + init_settings: PydanticBaseSettingsSource, + env_settings: PydanticBaseSettingsSource, + dotenv_settings: PydanticBaseSettingsSource, + file_secret_settings: PydanticBaseSettingsSource, + ) -> tuple[PydanticBaseSettingsSource, ...]: + dotenv = _ShadowGateDotEnv(settings_cls) + return init_settings, env_settings, dotenv, file_secret_settings + @lru_cache def get_settings() -> Settings: diff --git a/tests/test_env_precedence.py b/tests/test_env_precedence.py index f82a7a7..4543ddb 100644 --- a/tests/test_env_precedence.py +++ b/tests/test_env_precedence.py @@ -17,6 +17,7 @@ from pathlib import Path import pytest +from pydantic import ValidationError from shadowgate.config import Settings from shadowgate.server.app import create_app @@ -241,3 +242,33 @@ def test_suite_is_isolated_from_caller_token_configuration(tmp_path): ) assert result.returncode == 0, result.stdout[-2000:] assert " passed" in result.stdout and " failed" not in result.stdout + + +# --- N1: a shared .env may hold other programs' keys --------------------------------- + + +@pytest.mark.parametrize( + "line", + ["OTHER_APP_KEY=1", "OLD_SHADOWGATE_API_TOKENS=x", "DATABASE_URL=postgres://x"], +) +def test_dotenv_keys_of_other_programs_are_ignored(monkeypatch, tmp_path, line): + monkeypatch.chdir(tmp_path) + (tmp_path / ".env").write_text(f"{line}\nSHADOWGATE_API_TOKENS_JSON='{DOTENV_JSON}'\n") + assert Settings().api_tokens_json == DOTENV_JSON + + +@pytest.mark.parametrize("line", ["SHADOWGATE_TYPO_PORT=1", "SHADOWGATE_API_TOKENS_OLD=x"]) +def test_dotenv_unknown_shadowgate_key_is_still_rejected(monkeypatch, tmp_path, line): + monkeypatch.chdir(tmp_path) + (tmp_path / ".env").write_text(f"{line}\n") + with pytest.raises(ValidationError, match=r"extra_forbidden|Extra inputs"): + Settings() + + +def test_server_reports_invalid_setting_without_traceback(monkeypatch, tmp_path, capsys): + from shadowgate.cli import main as cli + + monkeypatch.chdir(tmp_path) + (tmp_path / ".env").write_text("SHADOWGATE_TYPO_PORT=1\n") + assert cli.main(["server"]) == 2 + assert "invalid setting shadowgate_typo_port" in capsys.readouterr().err From 39c3c1da476df6312f8c09ca59f8fcabc76d0319 Mon Sep 17 00:00:00 2001 From: "Saransh Singh (Splo1t)" <148835673+5aranx@users.noreply.github.com> Date: Mon, 30 Nov 2026 16:52:07 +0530 Subject: [PATCH 2/5] T11: one transaction per request; audit written at commit - server/db.py: Transaction is the shared re-entrant lock and the unit of work. Nested calls join it; the outermost exit commits; any error (or a swallowed nested error) rolls everything back. - Queue, run engine and store no longer commit mid-operation. - /jobs, /agent/poll and /agent/result run as one transaction each, so a failed audit write or engine error leaves no stranded job and a retried result is recorded and advances the run (fixes the engine gap). - Enrollment writes its audit entry before committing (fixes F2). - AuditLog defers appends made inside a transaction and writes them just before the commit; they are dropped on rollback. - tests/test_transactions.py: 9 failure-injection tests, all failing on the previous code. --- CHANGELOG.md | 5 + README.md | 11 +- docs/architecture.md | 17 ++- src/shadowgate/server/app.py | 32 ++++-- src/shadowgate/server/audit.py | 54 ++++++--- src/shadowgate/server/db.py | 89 ++++++++++++++- src/shadowgate/server/queue.py | 12 +- src/shadowgate/server/runs.py | 15 +-- src/shadowgate/server/store.py | 19 ++-- tests/test_transactions.py | 202 +++++++++++++++++++++++++++++++++ 10 files changed, 385 insertions(+), 71 deletions(-) create mode 100644 tests/test_transactions.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 6fb7627..39488b2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,11 @@ All notable changes to ShadowGate are recorded here. The format follows ## [Unreleased] ### Fixed +- Each request is now one database transaction. A failure part-way (audit write, run + engine, enqueue) rolls everything back: no job stuck `running` after a failed claim, no + enrollment whose credential nobody received, and a retried result after a server error + is recorded and advances the run instead of returning `duplicate`. +- Audit entries are written just before the database commits and dropped on rollback. - A `.env` file may hold other programs' variables; only unknown `SHADOWGATE_*` keys are rejected, and `shadowgate server` reports them without a traceback. diff --git a/README.md b/README.md index 9d95a51..b6def93 100644 --- a/README.md +++ b/README.md @@ -242,9 +242,10 @@ yet implemented. - **One server process only:** database and audit-log access are serialized with in-process locks, so requests are safe under concurrency but handled one at a time. Two server processes (for example `uvicorn --workers 2`) on the same files would fork the audit chain. -- **Crash consistency:** some operations still commit in several steps. A crash or an - error between them (for example, the audit file failing to write after an enrollment - commit) can leave a job claimed but undelivered or a run that never advances. +- **Audit vs. database:** each request is one transaction, and its audit entries are written + just before the commit. If the audit write fails, nothing is committed. In the rare case + that the database commit itself fails after that, the log holds entries for a change + that did not happen. - **Audit log:** 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. @@ -253,8 +254,6 @@ yet implemented. - **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. @@ -267,8 +266,6 @@ yet implemented. - Jobs claimed by a crashed agent stay `running`. - The `Poller` treats any 4xx other than 401/403 (including `408` and `429`) as final and drops the result. - - If the server fails after marking a job finished, a retried result returns `duplicate` - and the runbook run does not advance. - **Runbook engine defects:** - A dependent step can start before all of its dependency's targets finish. - A failing compensation step re-queues itself repeatedly. diff --git a/docs/architecture.md b/docs/architecture.md index 7a267c5..0f9b6fe 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -43,15 +43,20 @@ make multi-connection reads live. `tests/test_queue.py` runs 8 threads over 40 jobs, each on its **own** connection, and asserts zero duplicate claims. The running server shares **one** connection across FastAPI's request threads. -`Store`, `SqlQueue` and `RunEngine` hold one re-entrant lock (`server/db.py`) for -every method that touches it, so each operation, including nested run-engine -calls, runs alone. `tests/test_concurrency.py` drives 5 agents polling in +`Store`, `SqlQueue` and `RunEngine` share one `Transaction` (`server/db.py`): a +re-entrant lock that is also the unit of work. Every method that touches the +connection runs inside it; nested calls join the outer unit, the outermost exit +commits, and any exception rolls everything back. Endpoints that do several things +(claim + audit, complete + audit + run engine, enqueue + audit) wrap them in +`with store.transaction():`. Audit entries appended inside a transaction are held +back and written just before the commit, and dropped on rollback, so the log and +the database agree. `tests/test_transactions.py` injects a failure between each +former commit point. `tests/test_concurrency.py` drives 5 agents polling in parallel over HTTP and 20 threads on one store, and asserts no errors, no spurious 401s and no stranded jobs. -Remaining limits: the lock is per process (run one server process), requests -that touch the database are handled one at a time, and several operations still -commit in more than one step, so a crash between steps is not rolled back. +Remaining limits: the lock is per process (run one server process), and requests +that touch the database are handled one at a time. ## Plugin trust diff --git a/src/shadowgate/server/app.py b/src/shadowgate/server/app.py index 512e397..326a470 100644 --- a/src/shadowgate/server/app.py +++ b/src/shadowgate/server/app.py @@ -162,34 +162,42 @@ def create_job(req: JobRequest, store: Store = Depends(get_store)) -> dict[str, import uuid job_id = str(uuid.uuid4()) - store.queue.enqueue(job_id, req.agent_id, req.action, req.params) - store.audit.append("job_enqueued", actor="operator", target=req.agent_id, - detail={"job_id": job_id, "action": req.action}) + with store.transaction(): # no queued job without its audit entry + store.queue.enqueue(job_id, req.agent_id, req.action, req.params) + store.audit.append("job_enqueued", actor="operator", target=req.agent_id, + detail={"job_id": job_id, "action": req.action}) return {"job_id": job_id, "status": "queued"} @app.post("/agent/poll") 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=agent_id, target=job.id, - detail={"action": job.action}) + with store.transaction(): # if the audit write fails, the job stays queued + job = store.queue.claim_next(agent_id=agent_id) + if job is None: + return {"job": None} + 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, 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) + # One unit: if the audit write or the run engine fails, the job stays `running` + # and the agent's retry is accepted, instead of returning `duplicate` forever. + with store.transaction(): + outcome = store.queue.complete( + req.job_id, agent_id=agent_id, success=req.ok, data=req.data + ) + if outcome == CompletionOutcome.ACCEPTED: + 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) 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"} @app.post("/runbooks", dependencies=[Depends(require_role("admin"))]) diff --git a/src/shadowgate/server/audit.py b/src/shadowgate/server/audit.py index d50080b..c8fc240 100644 --- a/src/shadowgate/server/audit.py +++ b/src/shadowgate/server/audit.py @@ -7,6 +7,10 @@ Appends are serialized per file: reading the head and writing the new entry happen under one lock, so concurrent writers cannot both chain onto the same predecessor. The lock is per process; run a single server process per audit file. + +When attached to the store's :class:`~shadowgate.server.db.Transaction`, entries appended +inside a transaction are held back and written just before it commits (and dropped if +it rolls back), so the log never records a change the database undid. """ from __future__ import annotations @@ -17,7 +21,10 @@ import threading from datetime import UTC, datetime from pathlib import Path -from typing import Any +from typing import TYPE_CHECKING, Any + +if TYPE_CHECKING: + from shadowgate.server.db import Transaction GENESIS = "0" * 64 @@ -45,6 +52,12 @@ def __init__(self, path: str | Path) -> None: if not self.path.exists(): self.path.touch() self._append_lock = _lock_for(self.path) + self._tx: Transaction | None = None + self._pending: list[dict[str, Any]] = [] + + def attach(self, tx: Transaction) -> None: + """Defer appends made inside ``tx`` until it commits.""" + self._tx = tx def _last_hash(self) -> str: last = GENESIS @@ -56,20 +69,35 @@ def _last_hash(self) -> str: def append( self, event: str, actor: str, target: str, detail: dict[str, Any] | None = None - ) -> dict[str, Any]: + ) -> None: + record: dict[str, Any] = { + "ts": datetime.now(UTC).isoformat(), + "event": event, + "actor": actor, + "target": target, + "detail": detail or {}, + } + if self._tx is not None and self._tx.active: + if not self._pending: + self._tx.defer(self._flush, self._pending.clear) + self._pending.append(record) + return + self._write([record]) + + def _flush(self) -> None: + records, self._pending = self._pending, [] + self._write(records) + + def _write(self, records: list[dict[str, Any]]) -> None: with self._append_lock: - entry: dict[str, Any] = { - "ts": datetime.now(UTC).isoformat(), - "event": event, - "actor": actor, - "target": target, - "detail": detail or {}, - "prev": self._last_hash(), - } - entry["hash"] = _digest(_canonical(entry)) + prev = self._last_hash() + lines = [] + for record in records: + entry = {**record, "prev": prev} + entry["hash"] = prev = _digest(_canonical(entry)) + lines.append(json.dumps(entry) + "\n") with self.path.open("a") as f: - f.write(json.dumps(entry) + "\n") - return entry + f.write("".join(lines)) def entries(self) -> list[dict[str, Any]]: with self._append_lock: # never observe a half-written line diff --git a/src/shadowgate/server/db.py b/src/shadowgate/server/db.py index f95ab27..6682455 100644 --- a/src/shadowgate/server/db.py +++ b/src/shadowgate/server/db.py @@ -1,19 +1,96 @@ -"""Serialized access to the shared sqlite3 connection. +"""Serialized, transactional access to the shared sqlite3 connection. ``Store``, ``SqlQueue`` and ``RunEngine`` share one connection that FastAPI uses from its -threadpool. A sqlite3 connection is not safe for concurrent use, so every method that -touches it holds the same re-entrant lock: whole operations (including nested engine -calls) run one at a time, and no thread sees another thread's half-finished statement. +threadpool. They also share one :class:`Transaction`, a re-entrant lock that doubles as +a unit of work: + +* entering it takes the lock, so only one thread uses the connection at a time; +* the outermost exit commits, and any exception rolls back everything done since the + outermost entry, including work done by nested calls; +* nested entries join the outer unit instead of committing on their own; +* work outside the database (the audit file) can join too, with :meth:`Transaction.defer`: + it runs just before the commit, and a failure there rolls the database back. + +Methods decorated with :func:`locked` run inside it, so a whole request (for example, +claim a job and write its audit entry) can be made atomic by wrapping it in +``with store.transaction():``. Helpers never call ``commit()`` themselves. """ from __future__ import annotations import functools +import sqlite3 +import threading from collections.abc import Callable from contextlib import AbstractContextManager +from types import TracebackType from typing import Any, Concatenate, Protocol -__all__ = ["locked"] +__all__ = ["Transaction", "locked"] + + +class Transaction: + def __init__(self, conn: sqlite3.Connection) -> None: + self._conn = conn + self._lock = threading.RLock() + self._depth = 0 + self._failed = False + self._owner: int | None = None + self._hooks: list[tuple[Callable[[], None], Callable[[], None]]] = [] + + @property + def active(self) -> bool: + """True when the calling thread is inside this transaction.""" + return self._depth > 0 and self._owner == threading.get_ident() + + def defer(self, before_commit: Callable[[], None], on_rollback: Callable[[], None]) -> None: + """Run ``before_commit`` just before the outermost commit, or ``on_rollback`` + instead if the unit fails. Only valid while :attr:`active`.""" + if not self.active: + raise RuntimeError("defer() outside the transaction") + self._hooks.append((before_commit, on_rollback)) + + def __enter__(self) -> sqlite3.Connection: + self._lock.acquire() + self._depth += 1 + self._owner = threading.get_ident() + return self._conn + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + tb: TracebackType | None, + ) -> None: + try: + if exc_type is not None: + self._failed = True + self._depth -= 1 + if self._depth: + return + self._owner = None + failed, self._failed = self._failed, False + hooks, self._hooks = self._hooks, [] + if not failed: + try: + for before_commit, _ in hooks: + before_commit() + except BaseException: + self._rollback(hooks) + raise + self._conn.commit() + return + self._rollback(hooks) + if exc_type is None: + # an inner unit failed and its exception was swallowed: never commit half + raise RuntimeError("transaction rolled back: a nested operation failed") + finally: + self._lock.release() + + def _rollback(self, hooks: list[tuple[Callable[[], None], Callable[[], None]]]) -> None: + self._conn.rollback() + for _, on_rollback in hooks: + on_rollback() class _HasLock(Protocol): @@ -24,7 +101,7 @@ def _lock(self) -> AbstractContextManager[Any]: ... def locked[S: _HasLock, **P, R]( method: Callable[Concatenate[S, P], R], ) -> Callable[Concatenate[S, P], R]: - """Run ``method`` while holding ``self._lock``.""" + """Run ``method`` inside ``self._lock`` (a :class:`Transaction`).""" def wrapper(self: S, /, *args: P.args, **kwargs: P.kwargs) -> R: with self._lock: diff --git a/src/shadowgate/server/queue.py b/src/shadowgate/server/queue.py index 8b04bc3..85251bf 100644 --- a/src/shadowgate/server/queue.py +++ b/src/shadowgate/server/queue.py @@ -4,12 +4,11 @@ import json import sqlite3 -import threading from dataclasses import dataclass from enum import StrEnum from typing import Any -from shadowgate.server.db import locked +from shadowgate.server.db import Transaction, locked class CompletionOutcome(StrEnum): @@ -30,20 +29,20 @@ class SqlQueue: """Synchronous SQLite queue for correctness tests; the async wrapper is a thin coroutine around the same pattern. Atomicity comes from a single UPDATE constrained to status='queued'. A connection shared with other components - must be passed together with the lock that guards it.""" + must be passed together with the Transaction that guards it.""" def __init__( self, path: str, conn: sqlite3.Connection | None = None, - lock: threading.RLock | None = None, + lock: Transaction | None = None, ) -> None: self.path = path - self._lock = lock or threading.RLock() if conn is not None: self._conn = conn else: self._conn = sqlite3.connect(path, check_same_thread=False) + self._lock = lock or Transaction(self._conn) self._conn.execute("PRAGMA journal_mode=WAL") self._conn.execute("PRAGMA busy_timeout=5000") self._setup() @@ -70,7 +69,6 @@ def enqueue(self, job_id: str, agent_id: str, action: str, params: dict[str, Any "INSERT INTO qjobs(id,agent_id,action,params,status) VALUES(?,?,?,?,'queued')", (job_id, agent_id, action, json.dumps(params)), ) - self._conn.commit() @locked def claim_next(self, agent_id: str) -> ClaimedJob | None: @@ -84,7 +82,6 @@ def claim_next(self, agent_id: str) -> ClaimedJob | None: (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])) @@ -98,7 +95,6 @@ def complete( "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( diff --git a/src/shadowgate/server/runs.py b/src/shadowgate/server/runs.py index 3a2e4ef..5338418 100644 --- a/src/shadowgate/server/runs.py +++ b/src/shadowgate/server/runs.py @@ -6,14 +6,13 @@ from __future__ import annotations import sqlite3 -import threading import uuid from contextlib import closing from datetime import UTC, datetime from typing import Any from shadowgate.server.audit import AuditLog -from shadowgate.server.db import locked +from shadowgate.server.db import Transaction, locked from shadowgate.server.orchestrator import Runbook, Step, matches, topo_order from shadowgate.server.queue import SqlQueue @@ -21,10 +20,10 @@ class RunEngine: def __init__( self, conn: sqlite3.Connection, queue: SqlQueue, audit: AuditLog, - lock: threading.RLock | None = None, + lock: Transaction | None = None, ) -> None: self._conn = conn - self._lock = lock or threading.RLock() + self._lock = lock or Transaction(conn) self.queue = queue self.audit = audit self._setup() @@ -53,7 +52,6 @@ def register_runbook(self, runbook: Runbook, spec: str) -> None: self._conn.execute( "INSERT OR REPLACE INTO runbooks(name,spec) VALUES(?,?)", (runbook.name, spec) ) - self._conn.commit() @locked def get_runbook_spec(self, name: str) -> str | None: @@ -83,7 +81,6 @@ def start_run(self, runbook: Runbook, agents: list[dict[str, Any]]) -> str: " VALUES(?,?,?,'pending')", (run_id, step.name, agent["id"]), ) - self._conn.commit() self.audit.append("run_started", actor="operator", target=run_id, detail={"runbook": runbook.name}) for name in topo_order(runbook): @@ -129,7 +126,6 @@ def _schedule(self, run_id: str, step: Step, runbook: Runbook, ) self.audit.append("job_enqueued", actor="runbook", target=agent_id, detail={"job_id": job_id, "action": step.action, "run": run_id}) - self._conn.commit() @locked def on_job_result(self, job_id: str, ok: bool) -> dict[str, Any] | None: @@ -146,7 +142,6 @@ def on_job_result(self, job_id: str, ok: bool) -> dict[str, Any] | None: ) self._conn.execute("DELETE FROM run_jobs WHERE job_id=?", (job_id,)) run_row = self._conn.execute("SELECT runbook FROM runs WHERE id=?", (run_id,)).fetchone() - self._conn.commit() if not ok: self._fail_run(run_id, run_row[0] if run_row else "") return {"run_id": run_id, "status": "failed"} @@ -192,7 +187,6 @@ def _maybe_advance(self, run_id: str, runbook_name: str) -> None: "UPDATE run_steps SET status=? WHERE run_id=? AND step=?", ("failed" if failed else "done", run_id, step.name), ) - self._conn.commit() if failed: self._fail_run(run_id, runbook_name) return @@ -212,7 +206,6 @@ def _maybe_advance(self, run_id: str, runbook_name: str) -> None: ).fetchone()[0] if not_done == 0: self._conn.execute("UPDATE runs SET status='done' WHERE id=?", (run_id,)) - self._conn.commit() self.audit.append("run_completed", actor="engine", target=run_id, detail={}) def _agents_for_run(self, run_id: str) -> list[dict[str, Any]]: @@ -227,7 +220,6 @@ def _agents_for_run(self, run_id: str) -> list[dict[str, Any]]: def _fail_run(self, run_id: str, runbook_name: str) -> None: self._conn.execute("UPDATE runs SET status='failed' WHERE id=?", (run_id,)) - self._conn.commit() self.audit.append("run_failed", actor="engine", target=run_id, detail={}) spec = self.get_runbook_spec(runbook_name) if spec is None: @@ -258,7 +250,6 @@ def _fail_run(self, run_id: str, runbook_name: str) -> None: ) self.audit.append("compensation_enqueued", actor="engine", target=agent_id, detail={"job_id": job_id, "action": step.action, "run": run_id}) - self._conn.commit() @locked def run_status(self, run_id: str) -> dict[str, Any] | None: diff --git a/src/shadowgate/server/store.py b/src/shadowgate/server/store.py index 34a9e7a..b13cb71 100644 --- a/src/shadowgate/server/store.py +++ b/src/shadowgate/server/store.py @@ -9,7 +9,6 @@ import hashlib import secrets import sqlite3 -import threading from contextlib import closing from datetime import UTC, datetime, timedelta from enum import StrEnum @@ -17,7 +16,7 @@ from typing import Any from shadowgate.server.audit import AuditLog -from shadowgate.server.db import locked +from shadowgate.server.db import Transaction, locked from shadowgate.server.queue import SqlQueue @@ -31,15 +30,16 @@ class Store: def __init__(self, path: str, audit: AuditLog | None = None) -> None: self.path = path Path(path).parent.mkdir(parents=True, exist_ok=True) - # Guards self._conn, which the queue and run engine share (see server/db.py). - self._lock = threading.RLock() self._conn = sqlite3.connect(path, check_same_thread=False) + # Lock and unit of work for self._conn, shared with the queue and run engine. + self._lock = Transaction(self._conn) 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, lock=self._lock) self.audit: AuditLog = audit or AuditLog(str(Path(path).parent / "audit.log")) + self.audit.attach(self._lock) from shadowgate.server.runs import RunEngine self.engine = RunEngine(self._conn, self.queue, self.audit, lock=self._lock) @@ -79,7 +79,6 @@ def mint_token(self, ttl_minutes: int = 30, agent_id: str | None = None) -> str: "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 enroll_agent( @@ -112,10 +111,16 @@ def enroll_agent( 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}) + # Inside the transaction: if the audit write fails, the enrollment and the + # token burn roll back, so no credential exists that nobody received. + self.audit.append("agent_enrolled", actor=agent_id, target="server", + detail={"tags": tags, "bound": bound, "reclaimed": not inserted}) return EnrollOutcome.ENROLLED, secret + def transaction(self) -> Transaction: + """One atomic unit of work over the store, queue and run engine.""" + return self._lock + @locked def authenticate_agent(self, token: str) -> str | None: digest = hashlib.sha256(token.encode()).hexdigest() diff --git a/tests/test_transactions.py b/tests/test_transactions.py new file mode 100644 index 0000000..d6099a4 --- /dev/null +++ b/tests/test_transactions.py @@ -0,0 +1,202 @@ +"""T11 transaction boundaries: a failure part-way through an operation leaves no +partial state, and a retry succeeds. + +Each test injects one failure (the audit write, the run engine, or an enqueue) between +what used to be separate commit points. +""" + +from __future__ import annotations + +import sqlite3 +from typing import Any + +import pytest +from conftest import TOKENS, _paths, fetchall +from fastapi.testclient import TestClient + +from shadowgate.config import Settings +from shadowgate.server.app import create_app +from shadowgate.server.audit import AuditLog +from shadowgate.server.db import Transaction +from shadowgate.server.orchestrator import parse_runbook +from shadowgate.server.store import Store + +ADMIN = {"Authorization": "Bearer tok-admin"} +OPERATOR = {"Authorization": "Bearer tok-op"} + + +class Boom(Exception): + pass + + +def fail_once(monkeypatch: pytest.MonkeyPatch, obj: Any, name: str, + when: Any = lambda *a, **k: True) -> list[int]: + """Make ``obj.name`` raise Boom the first time ``when(*args)`` is true.""" + original = getattr(obj, name) + fired: list[int] = [] + + def wrapper(*args: Any, **kwargs: Any) -> Any: + if not fired and when(*args, **kwargs): + fired.append(1) + raise Boom(name) + return original(*args, **kwargs) + + monkeypatch.setattr(obj, name, wrapper) + return fired + + +def on_event(event: str) -> Any: + return lambda ev, *a, **k: ev == event + + +@pytest.fixture +def app_client(tmp_path): + settings = Settings(**_paths(tmp_path, api_tokens_json=TOKENS)) + with TestClient(create_app(settings), raise_server_exceptions=False) as client: + yield client + + +@pytest.fixture +def agent(app_client) -> dict[str, str]: + invite = app_client.post("/tokens", headers=ADMIN).json()["token"] + resp = app_client.post("/enroll", json={"agent_id": "a1", "token": invite}) + return {"X-ShadowGate-Agent-Token": resp.json()["agent_token"]} + + +def _store(client: TestClient) -> Store: + store: Store = client.app.state.store # type: ignore[attr-defined] + return store + + +def _events(client: TestClient, event: str) -> int: + entries = client.get("/audit", headers=OPERATOR).json()["entries"] + return sum(1 for e in entries if e["event"] == event) + + +def _queue_job(client: TestClient) -> str: + resp = client.post("/jobs", headers=OPERATOR, json={"agent_id": "a1", "action": "system_info"}) + assert resp.status_code == 200 + return str(resp.json()["job_id"]) + + +def test_enqueue_rolls_back_when_audit_fails(monkeypatch, app_client, agent): + fail_once(monkeypatch, _store(app_client).audit, "append", on_event("job_enqueued")) + resp = app_client.post("/jobs", headers=OPERATOR, + json={"agent_id": "a1", "action": "system_info"}) + assert resp.status_code == 500 + assert app_client.get("/jobs", headers=OPERATOR).json()["stats"] == {} + + +def test_claim_rolls_back_when_audit_fails(monkeypatch, app_client, agent): + job_id = _queue_job(app_client) + fail_once(monkeypatch, _store(app_client).audit, "append", on_event("job_claimed")) + assert app_client.post("/agent/poll", headers=agent, json={}).status_code == 500 + assert app_client.get("/jobs", headers=OPERATOR).json()["stats"] == {"queued": 1} + + retry = app_client.post("/agent/poll", headers=agent, json={}) # not stranded + assert retry.status_code == 200 and retry.json()["job"]["id"] == job_id + + +@pytest.mark.parametrize("failing", ["audit", "engine"]) +def test_result_rolls_back_and_retry_is_recorded(monkeypatch, app_client, agent, failing): + job_id = _queue_job(app_client) + assert app_client.post("/agent/poll", headers=agent, json={}).json()["job"]["id"] == job_id + store = _store(app_client) + if failing == "audit": + fail_once(monkeypatch, store.audit, "append", on_event("job_completed")) + else: + fail_once(monkeypatch, store.engine, "on_job_result") + + body = {"job_id": job_id, "ok": True} + assert app_client.post("/agent/result", headers=agent, json=body).status_code == 500 + assert app_client.get("/jobs", headers=OPERATOR).json()["stats"] == {"running": 1} + + retry = app_client.post("/agent/result", headers=agent, json=body) + assert retry.json() == {"status": "recorded"} # previously: "duplicate", run stuck + assert app_client.get("/jobs", headers=OPERATOR).json()["stats"] == {"done": 1} + assert _events(app_client, "job_completed") == 1 + + +def test_result_retry_advances_the_run(monkeypatch, app_client, agent): + spec = {"name": "two", "steps": [ + {"name": "first", "action": "system_info"}, + {"name": "second", "action": "system_info", "depends_on": ["first"]}, + ]} + assert app_client.post("/runbooks", headers=ADMIN, json=spec).status_code == 200 + run_id = app_client.post("/runs", headers=OPERATOR, json={"runbook": "two"}).json()["run_id"] + first = app_client.post("/agent/poll", headers=agent, json={}).json()["job"] + + fail_once(monkeypatch, _store(app_client).engine, "on_job_result") + body = {"job_id": first["id"], "ok": True} + assert app_client.post("/agent/result", headers=agent, json=body).status_code == 500 + assert app_client.post("/agent/result", headers=agent, json=body).json()["status"] == "recorded" + + second = app_client.post("/agent/poll", headers=agent, json={}).json()["job"] + assert second is not None # the engine ran on the retry and scheduled step two + app_client.post("/agent/result", headers=agent, json={"job_id": second["id"], "ok": True}) + status = app_client.get(f"/runs/{run_id}", headers=OPERATOR).json() + assert status["status"] == "done", status + + +def test_enrollment_rolls_back_when_audit_fails(monkeypatch, app_client, tmp_path): + invite = app_client.post("/tokens", headers=ADMIN).json()["token"] + fail_once(monkeypatch, _store(app_client).audit, "append", on_event("agent_enrolled")) + body = {"agent_id": "a1", "token": invite} + assert app_client.post("/enroll", json=body).status_code == 500 + assert app_client.get("/agents", headers=OPERATOR).json()["agents"] == [] + assert fetchall(tmp_path / "sg.db", "SELECT burned_at FROM enroll_tokens") == [(None,)] + + retry = app_client.post("/enroll", json=body) # the token was not burned + assert retry.status_code == 200 and retry.json()["agent_token"] + + +def test_start_run_is_all_or_nothing(monkeypatch, tmp_path): + store = Store(str(tmp_path / "sg.db"), audit=AuditLog(tmp_path / "audit.log")) + agents = [{"id": f"a{i}", "tags": ""} for i in range(3)] + runbook = parse_runbook('{"name": "fan", "steps": [{"name": "s", "action": "system_info"}]}') + store.engine.register_runbook(runbook, '{"name": "fan"}') + + calls: list[int] = [] + def second_call(*args: Any, **kwargs: Any) -> bool: + calls.append(1) + return len(calls) == 2 + + fail_once(monkeypatch, store.queue, "enqueue", second_call) + with pytest.raises(Boom): + store.engine.start_run(runbook, agents) + + db = tmp_path / "sg.db" + for table in ("runs", "run_steps", "run_step_agents", "run_jobs", "qjobs"): + assert fetchall(db, f"SELECT COUNT(*) FROM {table}") == [(0,)], table + assert store.engine.start_run(runbook, agents) # works once the fault is gone + assert store.queue.stats() == {"queued": 3} + + +def test_swallowed_nested_failure_never_commits(tmp_path): + conn = sqlite3.connect(str(tmp_path / "t.db"), check_same_thread=False) + conn.execute("CREATE TABLE t(x)") + conn.commit() + tx = Transaction(conn) + with pytest.raises(RuntimeError, match="nested operation failed"), tx: + conn.execute("INSERT INTO t VALUES (1)") + try: + with tx: + conn.execute("INSERT INTO t VALUES (2)") + raise Boom + except Boom: + pass + assert conn.execute("SELECT COUNT(*) FROM t").fetchone() == (0,) + + with tx: # the transaction is usable again afterwards + conn.execute("INSERT INTO t VALUES (3)") + assert conn.execute("SELECT x FROM t").fetchall() == [(3,)] + + +def test_audit_file_failure_at_commit_rolls_back_the_database(monkeypatch, app_client, agent): + job_id = _queue_job(app_client) + fail_once(monkeypatch, _store(app_client).audit, "_write") + assert app_client.post("/agent/poll", headers=agent, json={}).status_code == 500 + assert app_client.get("/jobs", headers=OPERATOR).json()["stats"] == {"queued": 1} + assert app_client.post("/agent/poll", headers=agent, json={}).json()["job"]["id"] == job_id + assert _events(app_client, "job_claimed") == 1 + assert app_client.get("/audit?verify=true", headers=OPERATOR).json()["verified"] is True From 706b3e43f969aa6fb196c195808f30a84d3b6415 Mon Sep 17 00:00:00 2001 From: "Saransh Singh (Splo1t)" <148835673+5aranx@users.noreply.github.com> Date: Mon, 30 Nov 2026 16:55:15 +0530 Subject: [PATCH 3/5] T12: anchored audit head, verification detail, O(1) appends - After every write, .head records the entry count and last hash; verify() detects removed or rewritten newest entries, a missing anchor, and reports where the chain breaks. - If the log changed behind the server's back, the next write keeps the old anchor as evidence and appends an audit_anchor_mismatch entry. - Head hash, count and size are cached per file; appends no longer re-read the log. - GET /audit?verify=true adds a verification object. - 13 audit tests; 12 fail on the previous code. --- CHANGELOG.md | 9 ++ README.md | 6 +- docs/architecture.md | 29 +++-- docs/threat-model.md | 2 +- src/shadowgate/server/app.py | 6 +- src/shadowgate/server/audit.py | 222 +++++++++++++++++++++++++++------ tests/test_audit.py | 139 ++++++++++++++++++++- 7 files changed, 360 insertions(+), 53 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 39488b2..f18d169 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,15 @@ All notable changes to ShadowGate are recorded here. The format follows ## [Unreleased] +### Added +- Audit head anchor (`.head`): `GET /audit?verify=true` now detects removed or rewritten + newest entries and returns a `verification` object (entries, how many verified, anchored + count, error). Tampering found while writing is recorded as `audit_anchor_mismatch` and + the old anchor is kept. + +### Changed +- Audit appends are O(1) instead of re-reading the whole log. + ### Fixed - Each request is now one database transaction. A failure part-way (audit write, run engine, enqueue) rolls everything back: no job stuck `running` after a failed claim, no diff --git a/README.md b/README.md index b6def93..14ba1c8 100644 --- a/README.md +++ b/README.md @@ -24,7 +24,7 @@ actions) against them, and review the results on an audit log and a read-only da | **Job ownership** | An agent can claim and complete only jobs assigned to its own id. A retried identical result is acknowledged as `duplicate`; a conflicting one is rejected. | | **Job queue** | SQLite (WAL mode). Each job is claimed with a single `UPDATE … RETURNING`. | | **Runbooks** | Sets of steps with dependencies, registered under a name (`unnamed` if omitted). Validation rejects cycles. Steps fan out to agents by tag, with a per-run concurrency cap and compensating steps on failure. | -| **Audit log** | An append-only JSONL file. Each entry includes the SHA-256 of the previous one, so `GET /audit?verify=true` detects in-place edits. | +| **Audit log** | An append-only JSONL file. Each entry includes the SHA-256 of the previous one, and a sidecar `audit.log.head` anchors the newest entry, so `GET /audit?verify=true` detects edited, reordered, removed or rewritten entries and says where. | | **Dashboard** | Server-rendered read-only pages at `/ui` (agents, job counts, runs). | | **Builtin actions** | `system_info`, `disk_health`, `file_fetch` (returns a byte count and a truncation flag, never file contents), `service_status` (`systemctl is-active`). | @@ -246,7 +246,9 @@ yet implemented. just before the commit. If the audit write fails, nothing is committed. In the rare case that the database commit itself fails after that, the log holds entries for a change that did not happen. -- **Audit log:** deleting the newest entries is not detected. +- **Audit log:** the anchor sits next to the log, so someone who can rewrite both files + consistently (or delete the anchor and restart the server) is not detected. Copy + `verification` output or the anchor off the host if that matters. - **Transport:** 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 diff --git a/docs/architecture.md b/docs/architecture.md index 0f9b6fe..523d2e4 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -68,13 +68,26 @@ in the codebase, but are not yet wired into an agent CLI. ## Audit integrity `AuditLog.append` writes `prev = sha256(canonical(last_entry))` into each JSONL -line and `verify_chain()` recomputes the chain. Editing or reordering an existing -line is detected (`tests/test_audit.py` covers the edit case). +line, and `verify()` recomputes the chain. After every write, the sidecar +`.head` records `{count, head}`. Verification reports `ok`, the number of +entries, how many leading entries check out, the anchored count, and an error: + +- an edited, reordered or corrupt entry: where the chain breaks; +- a log shorter than its anchor: the newest entries were removed; +- a log whose entry at the anchored position has a different hash: rewritten; +- a missing or unreadable anchor. + +If the server finds the log changed behind its back when it next writes, it +keeps the old anchor as `.head.` and appends an +`audit_anchor_mismatch` entry before continuing, so the evidence survives and +`verify()` keeps failing. + +Appends are O(1): the head hash, entry count and file size are cached per file, +and the file is re-read only when its size shows another writer. Known limits: -- **Tail truncation is not detected.** Removing the newest line(s), or emptying - the file, still verifies, because nothing anchors the head. -- **Appends are serialized per process.** Reading the head and writing the - entry happen under one lock per file, so concurrent requests keep one chain. - Two processes writing the same file can still fork it. Each append still - re-reads the whole file (O(n)). +- **The anchor is local.** Rewriting the log and its anchor consistently, or + deleting the anchor and restarting (an existing log without an anchor is + adopted as-is), is not detected. Signed or off-host checkpoints are future work. +- **Appends are serialized per process.** Two processes writing the same file + can still fork the chain. diff --git a/docs/threat-model.md b/docs/threat-model.md index 43c673a..14f96bf 100644 --- a/docs/threat-model.md +++ b/docs/threat-model.md @@ -54,7 +54,7 @@ authorized to administer. It is designed to make unauthorized use hard. | 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 edited or reordered | `verify_chain()` returns false | -| Audit log truncated or emptied | **Not detected**: still returns true (nothing anchors the head) | +| Audit log truncated or emptied | Detected against the `.head` anchor; if the server writes again, it keeps the old anchor and logs `audit_anchor_mismatch`. Not detected if the anchor is also rewritten or deleted before a restart | | Concurrent audit writes (no tampering) | Serialized per file within one process; a second process writing the same file can fork the chain | | Concurrent HTTP requests | Shared sqlite connection is serialized by one lock; the agent `Poller` retries a 401 up to 3 times with backoff and stops on persistent 401 or any 403 | | Compromised plugin package | Gate exists in `plugins/gate.py` but is not yet wired into an agent CLI | diff --git a/src/shadowgate/server/app.py b/src/shadowgate/server/app.py index 326a470..3463677 100644 --- a/src/shadowgate/server/app.py +++ b/src/shadowgate/server/app.py @@ -242,7 +242,11 @@ def jobs(store: Store = Depends(get_store)) -> dict[str, Any]: @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} + if not verify: + return {"entries": audit.entries(), "verified": None} + result = audit.verify() + return {"entries": audit.entries(), "verified": result.ok, + "verification": result.as_dict()} @app.get("/healthz") def healthz() -> dict[str, str]: diff --git a/src/shadowgate/server/audit.py b/src/shadowgate/server/audit.py index c8fc240..a55644f 100644 --- a/src/shadowgate/server/audit.py +++ b/src/shadowgate/server/audit.py @@ -1,12 +1,19 @@ -"""Append-only hash-chained audit log. +"""Append-only hash-chained audit log with a head anchor. -Each entry embeds the SHA-256 of the previous entry's canonical serialized -form. verify_chain walks the log and fails on any mutation, reorder, or -deletion. +Each entry embeds the SHA-256 of the previous entry's canonical serialized form, so +editing, reordering or deleting an entry in the middle breaks the chain. -Appends are serialized per file: reading the head and writing the new entry happen under -one lock, so concurrent writers cannot both chain onto the same predecessor. The lock is -per process; run a single server process per audit file. +Deleting the newest entries keeps the remaining chain valid, so the head is anchored +separately: after every write, ``.head`` records the entry count and the last hash. +:meth:`AuditLog.verify` reports a log that is shorter than its anchor, or disagrees with +it, as truncated. The anchor defends against tampering with the log alone; someone who +can rewrite both files consistently is not detected (ship the head hash off the host for +that). + +Appends are O(1): the head (hash, entry count, file size) is cached per file and reloaded +only when the file size shows that something else wrote to it. Reading the head and +writing new entries happen under one lock per file, so concurrent writers cannot fork the +chain. The lock and cache are per process; run a single server process per audit file. When attached to the store's :class:`~shadowgate.server.db.Transaction`, entries appended inside a transaction are held back and written just before it commits (and dropped if @@ -18,7 +25,9 @@ import contextlib import hashlib import json +import os import threading +from dataclasses import dataclass, field from datetime import UTC, datetime from pathlib import Path from typing import TYPE_CHECKING, Any @@ -27,14 +36,26 @@ from shadowgate.server.db import Transaction GENESIS = "0" * 64 +ANCHOR_MISMATCH = "audit_anchor_mismatch" + + +@dataclass +class _FileState: + """Per-file lock and cached head, shared by every AuditLog on that file.""" + + lock: threading.Lock = field(default_factory=threading.Lock) + size: int = -1 # -1: not loaded + count: int = 0 + head: str = GENESIS + -_FILE_LOCKS: dict[Path, threading.Lock] = {} -_FILE_LOCKS_GUARD = threading.Lock() +_STATES: dict[Path, _FileState] = {} +_STATES_GUARD = threading.Lock() -def _lock_for(path: Path) -> threading.Lock: - with _FILE_LOCKS_GUARD: - return _FILE_LOCKS.setdefault(path.resolve(), threading.Lock()) +def _state_for(path: Path) -> _FileState: + with _STATES_GUARD: + return _STATES.setdefault(path.resolve(), _FileState()) def _canonical(entry: dict[str, Any]) -> bytes: @@ -45,27 +66,40 @@ def _digest(payload: bytes) -> str: return hashlib.sha256(payload).hexdigest() +@dataclass +class Verification: + ok: bool + entries: int # entries in the log + verified: int # leading entries whose chain checks out + anchored: int | None # entry count recorded in the anchor (None: no anchor) + error: str | None = None + + def as_dict(self) -> dict[str, Any]: + return {"ok": self.ok, "entries": self.entries, "verified": self.verified, + "anchored": self.anchored, "error": self.error} + + class AuditLog: def __init__(self, path: str | Path) -> None: self.path = Path(path) + self.anchor_path = self.path.with_name(self.path.name + ".head") self.path.parent.mkdir(parents=True, exist_ok=True) if not self.path.exists(): self.path.touch() - self._append_lock = _lock_for(self.path) + self._state = _state_for(self.path) self._tx: Transaction | None = None self._pending: list[dict[str, Any]] = [] + with self._state.lock: + if not self.anchor_path.exists(): + # first use, or a log from before anchoring: trust what is there now + self._load() + self._write_anchor() def attach(self, tx: Transaction) -> None: """Defer appends made inside ``tx`` until it commits.""" self._tx = tx - def _last_hash(self) -> str: - last = GENESIS - for line in self.path.read_text().splitlines(): - if line.strip(): - with contextlib.suppress(json.JSONDecodeError, KeyError): - last = json.loads(line)["hash"] - return last + # --- writing ---------------------------------------------------------------------- def append( self, event: str, actor: str, target: str, detail: dict[str, Any] | None = None @@ -88,33 +122,145 @@ def _flush(self) -> None: records, self._pending = self._pending, [] self._write(records) + def _load(self) -> list[str | None]: + """Recompute the cached head from the file (caller holds the lock). + + Returns each entry's hash (None for a corrupt line).""" + data = self.path.read_bytes() + hashes: list[str | None] = [] + head = GENESIS + for line in data.splitlines(): + if not line.strip(): + continue + value: str | None = None + # a corrupt line keeps the previous head; verify() reports it + with contextlib.suppress(ValueError, KeyError, TypeError): + value = head = str(json.loads(line)["hash"]) + hashes.append(value) + self._state.size, self._state.count, self._state.head = len(data), len(hashes), head + return hashes + + def _read_anchor(self) -> tuple[int, str] | None: + try: + anchor = json.loads(self.anchor_path.read_text()) + return int(anchor["count"]), str(anchor["head"]) + except (OSError, ValueError, KeyError, TypeError): + return None + + def _anchor_mismatch(self, hashes: list[str | None]) -> dict[str, Any] | None: + """Describe how the reloaded log disagrees with its anchor, if it does.""" + anchor = self._read_anchor() + if anchor is None: + return {"reason": "anchor missing or unreadable", "found_entries": len(hashes)} + count, head = anchor + if len(hashes) < count: + return {"reason": "entries removed", "anchored_entries": count, + "found_entries": len(hashes)} + if count and hashes[count - 1] != head: + return {"reason": "log rewritten", "anchored_entries": count, + "found_entries": len(hashes)} + return None + def _write(self, records: list[dict[str, Any]]) -> None: - with self._append_lock: - prev = self._last_hash() - lines = [] + state = self._state + with state.lock: + if state.size != self.path.stat().st_size: + # first write in this process, or the file changed behind our back + mismatch = self._anchor_mismatch(self._load()) + if mismatch is not None: + # keep the evidence: preserve the old anchor and record the event + stamp = datetime.now(UTC).strftime("%Y%m%dT%H%M%S%fZ") + with contextlib.suppress(FileNotFoundError): + os.replace(self.anchor_path, + self.anchor_path.with_name(f"{self.anchor_path.name}.{stamp}")) + records = [{"ts": datetime.now(UTC).isoformat(), + "event": ANCHOR_MISMATCH, "actor": "audit", "target": "audit", + "detail": mismatch}, *records] + prev, lines = state.head, [] for record in records: entry = {**record, "prev": prev} entry["hash"] = prev = _digest(_canonical(entry)) lines.append(json.dumps(entry) + "\n") - with self.path.open("a") as f: - f.write("".join(lines)) + payload = "".join(lines).encode() + with self.path.open("ab") as f: + f.write(payload) + state.size += len(payload) + state.count += len(records) + state.head = prev + self._write_anchor() + + def _write_anchor(self) -> None: + tmp = self.anchor_path.with_name(self.anchor_path.name + ".tmp") + tmp.write_text(json.dumps({"count": self._state.count, "head": self._state.head})) + os.replace(tmp, self.anchor_path) + + # --- reading ---------------------------------------------------------------------- + + def _read(self) -> tuple[bytes, str | None]: + with self._state.lock: # never observe a half-written line or a stale anchor + data = self.path.read_bytes() + try: + anchor = self.anchor_path.read_text() + except FileNotFoundError: + anchor = None + return data, anchor def entries(self) -> list[dict[str, Any]]: - with self._append_lock: # never observe a half-written line - text = self.path.read_text() + data, _ = self._read() out: list[dict[str, Any]] = [] - for line in text.splitlines(): + for line in data.splitlines(): if line.strip(): - out.append(json.loads(line)) + try: + out.append(json.loads(line)) + except ValueError: + out.append({"corrupt": line.decode(errors="replace")}) return out - def verify_chain(self) -> bool: - prev = GENESIS - for entry in self.entries(): - if entry.get("prev") != prev: - return False - expected = _digest(_canonical({k: v for k, v in entry.items() if k != "hash"})) - if expected != entry.get("hash"): - return False + def verify(self) -> Verification: + data, anchor_text = self._read() + lines = [line for line in data.splitlines() if line.strip()] + prev, verified, error = GENESIS, 0, None + mismatch_at: int | None = None + hashes: list[str] = [] + for number, line in enumerate(lines, start=1): + try: + entry = json.loads(line) + body = {k: v for k, v in entry.items() if k != "hash"} + valid = entry.get("prev") == prev and _digest(_canonical(body)) == entry["hash"] + except (ValueError, KeyError, TypeError, AttributeError): + valid = False + if not valid: + error = f"entry {number} is altered, reordered, or out of sequence" + break prev = entry["hash"] - return True + hashes.append(prev) + verified = number + if entry.get("event") == ANCHOR_MISMATCH and mismatch_at is None: + mismatch_at = number + + anchored: int | None = None + try: + anchor = json.loads(anchor_text) if anchor_text is not None else None + if anchor is not None: + anchored = int(anchor["count"]) + anchor_head = str(anchor["head"]) + except (ValueError, KeyError, TypeError): + error = error or f"anchor {self.anchor_path.name} is unreadable" + anchor = None + if anchor is None and anchor_text is None: + error = error or f"anchor {self.anchor_path.name} is missing" + elif anchor is not None and error is None: + assert anchored is not None + if len(lines) < anchored: + error = (f"log has {len(lines)} entries but the anchor records {anchored}: " + "the newest entries were removed") + elif anchored and hashes[anchored - 1] != anchor_head: + error = f"entry {anchored} does not match the anchor: the log was rewritten" + if error is None and mismatch_at is not None: + error = (f"entry {mismatch_at} records that the log was truncated or rewritten " + "before it; the old anchor was kept beside the log") + return Verification(ok=error is None, entries=len(lines), verified=verified, + anchored=anchored, error=error) + + def verify_chain(self) -> bool: + return self.verify().ok diff --git a/tests/test_audit.py b/tests/test_audit.py index 07f5e41..3acf9ee 100644 --- a/tests/test_audit.py +++ b/tests/test_audit.py @@ -1,4 +1,9 @@ -from shadowgate.server.audit import AuditLog +import json +from pathlib import Path + +import pytest + +from shadowgate.server.audit import AuditLog, _canonical, _digest def test_chain_verifies_and_tamper_detected(tmp_path): @@ -11,9 +16,137 @@ def test_chain_verifies_and_tamper_detected(tmp_path): # tamper with an entry lines = (tmp_path / "audit.log").read_text().splitlines() - entry = __import__("json").loads(lines[1]) + entry = json.loads(lines[1]) entry["detail"] = {"ok": False} - lines[1] = __import__("json").dumps(entry) + lines[1] = json.dumps(entry) (tmp_path / "audit.log").write_text("\n".join(lines) + "\n") assert log.verify_chain() is False + + +# --- T12: head anchor, verification detail, O(1) appends ----------------------------- + +def _log_with(tmp_path: Path, n: int) -> AuditLog: + log = AuditLog(tmp_path / "audit.log") + for i in range(n): + log.append("probe", actor="t", target=str(i)) + return log + + +def _lines(path: Path) -> list[str]: + return path.read_text().splitlines() + + +def test_intact_log_verifies_with_detail(tmp_path): + result = _log_with(tmp_path, 3).verify() + assert result.as_dict() == {"ok": True, "entries": 3, "verified": 3, "anchored": 3, + "error": None} + + +@pytest.mark.parametrize("keep", [2, 0]) +def test_removing_newest_entries_is_detected(tmp_path, keep): + log = _log_with(tmp_path, 3) + lines = _lines(log.path)[:keep] + log.path.write_text("".join(line + "\n" for line in lines)) + result = log.verify() + assert not result.ok and result.verified == keep and result.anchored == 3 + assert "removed" in (result.error or "") + assert log.verify_chain() is False + + +def test_rewritten_tail_is_detected(tmp_path): + log = _log_with(tmp_path, 3) + lines = _lines(log.path)[:2] + log.path.write_text("".join(line + "\n" for line in lines)) + forged = AuditLog(tmp_path / "audit.log") + # a forger re-extends the cut log with a valid-looking chain of the same length + forged_entry = {"ts": "x", "event": "forged", "actor": "a", "target": "t", "detail": {}, + "prev": json.loads(lines[-1])["hash"]} + forged_entry["hash"] = _digest(_canonical(forged_entry)) + with log.path.open("a") as f: + f.write(json.dumps(forged_entry) + "\n") + result = forged.verify() + assert not result.ok and "rewritten" in (result.error or "") + + +def test_mid_chain_edit_reports_where_verification_stopped(tmp_path): + log = _log_with(tmp_path, 4) + lines = _lines(log.path) + entry = json.loads(lines[2]) + entry["target"] = "edited" + lines[2] = json.dumps(entry) + log.path.write_text("\n".join(lines) + "\n") + result = log.verify() + assert (result.ok, result.verified) == (False, 2) + assert "entry 3" in (result.error or "") + + +def test_corrupt_line_is_reported_not_raised(tmp_path): + log = _log_with(tmp_path, 2) + with log.path.open("a") as f: + f.write("{not json\n") + assert log.verify().ok is False + assert log.entries()[-1] == {"corrupt": "{not json"} + + +def test_missing_anchor_is_detected(tmp_path): + log = _log_with(tmp_path, 2) + log.anchor_path.unlink() + result = log.verify() + assert not result.ok and "missing" in (result.error or "") + + +def test_append_after_truncation_keeps_the_evidence(tmp_path): + log = _log_with(tmp_path, 3) + lines = _lines(log.path)[:1] + log.path.write_text(lines[0] + "\n") + + log.append("after", actor="t", target="x") # the server keeps running... + result = log.verify() + assert not result.ok # ...but the log stays marked as tampered + assert "truncated or rewritten" in (result.error or "") + events = [e["event"] for e in log.entries()] + assert events == ["probe", "audit_anchor_mismatch", "after"] + mismatch = log.entries()[1]["detail"] + assert mismatch == {"reason": "entries removed", "anchored_entries": 3, "found_entries": 1} + kept = [p for p in tmp_path.iterdir() if p.name.startswith("audit.log.head.")] + assert len(kept) == 1 and json.loads(kept[0].read_text())["count"] == 3 + + +def test_existing_log_without_anchor_is_adopted(tmp_path): + log = _log_with(tmp_path, 2) + log.anchor_path.unlink() + adopted = AuditLog(log.path) # e.g. first start after upgrading + assert adopted.verify().ok and adopted.verify().anchored == 2 + + +def test_append_does_not_reread_the_log(tmp_path, monkeypatch): + log = _log_with(tmp_path, 1) # head now cached + reads: list[Path] = [] + original = Path.read_bytes + + def counting(self: Path) -> bytes: + reads.append(self) + return original(self) + + monkeypatch.setattr(Path, "read_bytes", counting) + for i in range(50): + log.append("probe", actor="t", target=str(i)) + assert reads == [] + monkeypatch.undo() + assert log.verify().ok and log.verify().entries == 51 + + +def test_two_handles_in_one_process_share_the_head(tmp_path): + first = _log_with(tmp_path, 1) + second = AuditLog(first.path) + second.append("from-second", actor="t", target="x") + first.append("from-first", actor="t", target="y") + assert first.verify().ok and first.verify().entries == 3 + + +def test_audit_endpoint_reports_verification_detail(rbac_client): + resp = rbac_client.get("/audit?verify=true", headers={"Authorization": "Bearer tok-view"}) + body = resp.json() + assert body["verified"] is True + assert body["verification"]["ok"] is True and body["verification"]["error"] is None From 4ec4a8e309d17286a29bf583e2cdf94b92e382c8 Mon Sep 17 00:00:00 2001 From: "Saransh Singh (Splo1t)" <148835673+5aranx@users.noreply.github.com> Date: Mon, 30 Nov 2026 16:59:44 +0530 Subject: [PATCH 4/5] T14: built-in TLS with CA pinning - shadowgate tls init: private CA and server certificate (EC P-256) for the given hostnames plus localhost/127.0.0.1; keys created mode 600; never overwrites. - shadowgate server --tls-cert/--tls-key (or SHADOWGATE_TLS_*): serves HTTPS; checks the files load together and the key is owner-only. A non-loopback bind without TLS is refused unless --allow-plaintext. - agent enroll --ca-file pins the CA in the 0600 credential file; plain HTTP to non-loopback hosts is refused; the agent stops (exit 2) when the server certificate fails verification. - tests/test_tls.py: 13 tests including an HTTPS end-to-end run with wrong-CA rejection. --- CHANGELOG.md | 7 + README.md | 45 ++++-- docs/architecture.md | 4 +- docs/threat-model.md | 13 +- src/shadowgate/agent/config.py | 46 +++++- src/shadowgate/agent/poll.py | 23 ++- src/shadowgate/cli/main.py | 117 +++++++++++++-- src/shadowgate/config.py | 2 + src/shadowgate/crypto/tls.py | 123 ++++++++++++++++ tests/test_cli.py | 8 +- tests/test_tls.py | 254 +++++++++++++++++++++++++++++++++ 11 files changed, 598 insertions(+), 44 deletions(-) create mode 100644 src/shadowgate/crypto/tls.py create mode 100644 tests/test_tls.py diff --git a/CHANGELOG.md b/CHANGELOG.md index f18d169..b4789e1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,7 +13,14 @@ All notable changes to ShadowGate are recorded here. The format follows count, error). Tampering found while writing is recorded as `audit_anchor_mismatch` and the old anchor is kept. +- Built-in HTTPS: `shadowgate tls init` (private CA + server certificate), + `shadowgate server --tls-cert/--tls-key`, and `agent enroll --ca-file`, which pins the + CA in the agent's credential file. + ### Changed +- The server refuses a non-loopback bind without TLS (`--allow-plaintext` overrides), and + agents refuse plain HTTP to non-loopback hosts. An agent stops (exit 2) when the server + certificate fails verification instead of retrying forever. - Audit appends are O(1) instead of re-reading the whole log. ### Fixed diff --git a/README.md b/README.md index 14ba1c8..14e7a87 100644 --- a/README.md +++ b/README.md @@ -8,8 +8,9 @@ actions) against them, and review the results on an audit log and a read-only da > covert-channel, exfiltration, or evasion code anywhere in the tree. **Status: pre-release (0.1.0).** -- The control server works for loopback evaluation with several agents and is covered by - tests, including concurrent-load tests. Run a single server process. +- The control server works with several agents, locally or across a network over its + built-in HTTPS (`shadowgate tls init`), and is covered by tests including concurrent + load and HTTPS end-to-end runs. Run a single server process. - `shadowgate server`, `shadowgate agent enroll` and `shadowgate agent run` work end to end (covered by a test that runs a real server and agent). - Several known defects remain. See [Known limitations](#known-limitations) before using it @@ -35,9 +36,10 @@ actions) against them, and review the results on an audit log and a read-only da ## Architecture ``` -operator (curl / browser) agent (Python library) +operator (curl / browser) agent (`shadowgate agent run`) │ Authorization: Bearer │ X-ShadowGate-Agent-Token - │ or Basic (token as password) │ (plain HTTP; TLS not provided) + │ or Basic (token as password) │ HTTPS, server CA pinned at enrollment + │ │ (plain HTTP only to loopback) ▼ ▼ FastAPI app (server/app.py, built by create_app factory) ├── Store (server/store.py) SQLite WAL: agents, enroll_tokens @@ -58,7 +60,7 @@ See [`docs/architecture.md`](docs/architecture.md) and | `src/shadowgate/server/` | app, store, queue, runs, orchestrator, audit | | `src/shadowgate/agent/` | executor, polling client (`Poller`), credential file (`config.py`) | | `src/shadowgate/plugins/` | `Action` protocol, registry, loader, gate, builtins | -| `src/shadowgate/crypto/` | ed25519 manifest signing; mTLS CA helpers (unused) | +| `src/shadowgate/crypto/` | TLS CA and server certificates (`tls.py`); ed25519 manifest signing; mTLS helpers (unused) | | `src/shadowgate/cli/` | `shadowgate` command: `server`, `agent enroll`, `agent run`, `plugin list` | | `src/shadowgate/web/templates/` | dashboard templates | | `docs/` | architecture, threat model | @@ -104,10 +106,11 @@ A `.env` file may also hold other programs' variables; they are ignored. An unkn | `SHADOWGATE_AUDIT_LOG_PATH` | `.shadowgate/audit.log` | Audit log file. Relative to the working directory. | | `SHADOWGATE_DATA_DIR` | `.shadowgate` | Directory created at startup. It does **not** relocate the database or audit log. | | `SHADOWGATE_RATE_LIMIT_PER_MINUTE` | `60` | Per-source-IP, per-endpoint limit on `POST /tokens` and `POST /enroll`. Must be ≥ 1: `0` or a negative value rejects every request. Behind a reverse proxy, all clients share the proxy's IP. | +| `SHADOWGATE_HOST`, `SHADOWGATE_PORT` | `127.0.0.1`, `8080` | Bind address for `shadowgate server` (`--host`/`--port` override them). | +| `SHADOWGATE_TLS_CERT_PATH`, `SHADOWGATE_TLS_KEY_PATH` | *(empty)* | Serve HTTPS with this certificate and key (`--tls-cert`/`--tls-key` override them). The key must be mode 600. | -`SHADOWGATE_HOST`, `SHADOWGATE_PORT`, `SHADOWGATE_ORG_KEY_PATH`, `SHADOWGATE_CA_KEY_PATH` and -`SHADOWGATE_CA_CERT_PATH` exist in `config.py` but are **not used**. Pass the bind -address and port to Uvicorn instead. +`SHADOWGATE_ORG_KEY_PATH`, `SHADOWGATE_CA_KEY_PATH` and `SHADOWGATE_CA_CERT_PATH` exist in +`config.py` but are **not used**. Invalid token JSON, an unknown role, a malformed token, or an empty map without insecure dev mode makes startup fail with an error, before any files are created. @@ -139,8 +142,25 @@ export SHADOWGATE_API_TOKENS_JSON='{"":"admin","":" uv run shadowgate server # --host/--port, default 127.0.0.1:8080 ``` -Without operator tokens the server refuses to start (exit code 2). Binding to a -non-loopback address prints a warning, because there is no TLS. +Without operator tokens the server refuses to start (exit code 2). + +### Over a network (HTTPS) + +```bash +uv run shadowgate tls init --hostname gw.example --hostname 10.0.0.5 # once +uv run shadowgate server --host 0.0.0.0 --port 8443 \ + --tls-cert .shadowgate/tls/server.crt --tls-key .shadowgate/tls/server.key +``` + +`tls init` creates a private CA and a server certificate for the names agents will use +(`localhost` and `127.0.0.1` are always included), with private keys at mode 600; it never +overwrites files. Copy `ca.crt` to agent hosts and enroll with +`--server https://gw.example:8443 --ca-file ca.crt`: the agent pins that CA in its +credential file. A certificate from a public CA works too; then omit `--ca-file`. + +The server refuses a non-loopback bind without TLS. `--allow-plaintext` overrides that for +a TLS-terminating proxy on a trusted network. Agents refuse plain `http://` to anything but +loopback, and stop with exit code 2 if the server's certificate fails verification. Replace the placeholders with long random values, e.g. `python -c 'import secrets; print(secrets.token_urlsafe(32))'`. @@ -249,8 +269,9 @@ yet implemented. - **Audit log:** the anchor sits next to the log, so someone who can rewrite both files consistently (or delete the anchor and restart the server) is not detected. Copy `verification` output or the anchor off the host if that matters. -- **Transport:** no TLS. Tokens travel in clear text; keep the server on loopback or behind - a TLS-terminating proxy you control. mTLS is not implemented. +- **Transport:** HTTPS is built in, but agents authenticate with a bearer token, not a client + certificate (no mTLS). There is no certificate rotation or revocation; `tls init` server + certificates last 397 days. Operators' own clients (`curl`, browser) must trust the CA. - **Agent credentials:** they cannot be rotated or revoked, and agent tags cannot be changed after enrollment, except by editing the database. - **Enrollment edge cases:** diff --git a/docs/architecture.md b/docs/architecture.md index 523d2e4..eefe9ae 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -3,7 +3,7 @@ ``` +-------------------+ HTTP + Agent Token +-------------------+ operator | shadowgate | <----------------------> | shadowgate agent | - dashboard | server (FastAPI) | (mTLS deferred to T14) | (CLI: enroll, | + dashboard | server (FastAPI) | HTTPS, server CA pinned | (CLI: enroll, | | | | run; Poller) | | Store (sqlite) | | executor | | qjobs (WAL) | | builtins | @@ -29,7 +29,7 @@ ## Data flow -1. Operator mints a one-time enrollment token (`POST /tokens`, optionally bound to an `agent_id`) → agent burns it once (`POST /enroll`) → `agents` stores `secret_hash` (SHA-256) and returns a one-time `agent_token`. (mTLS cert issuance/pinning is not yet implemented; deferred to T14.) +1. Operator mints a one-time enrollment token (`POST /tokens`, optionally bound to an `agent_id`) → agent burns it once (`POST /enroll`) → `agents` stores `secret_hash` (SHA-256) and returns a one-time `agent_token`. (Transport: server-side TLS, with the server CA pinned in the agent's credential file; agents do not use client certificates.) 2. Operator enqueues a job (`POST /jobs`) or starts a runbook (`POST /runs`). 3. Agent short-polls `POST /agent/poll` with `X-ShadowGate-Agent-Token` (long-poll is not yet implemented); server authenticates the agent and claims that agent's next queued job atomically (`claim_next(agent_id=...)`). 4. Agent executes the action (builtins; signed third-party plugin registry is not yet wired into an agent CLI) and posts `POST /agent/result` with `X-ShadowGate-Agent-Token`; server enforces job ownership (`id`, `agent_id`, `status='running'`). diff --git a/docs/threat-model.md b/docs/threat-model.md index 14f96bf..50dab85 100644 --- a/docs/threat-model.md +++ b/docs/threat-model.md @@ -16,7 +16,8 @@ authorized to administer. It is designed to make unauthorized use hard. 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).* + Agents do not present client certificates (no mTLS); the transport is protected by + server-side TLS with the server CA pinned in the agent's credential file. - **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). @@ -32,9 +33,13 @@ authorized to administer. It is designed to make unauthorized use hard. 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. +- **Transport:** `shadowgate server --tls-cert/--tls-key` serves HTTPS, and the + server refuses a non-loopback bind without it (unless `--allow-plaintext`, for a + TLS proxy). Agents refuse plain HTTP to non-loopback hosts and verify the server + against the CA pinned at enrollment (or the system trust store), so a network + attacker cannot read or replay credentials. Not covered: client certificates + (mTLS), certificate rotation and revocation, and theft of the server key or the + CA key (which `tls init` leaves next to the server; move it off the host). - **Plugin gate:** `plugins/gate.py` and `crypto/signing.py` exist, but third-party plugin verification is not yet wired into an agent CLI. diff --git a/src/shadowgate/agent/config.py b/src/shadowgate/agent/config.py index a0bf797..e5fef97 100644 --- a/src/shadowgate/agent/config.py +++ b/src/shadowgate/agent/config.py @@ -1,6 +1,8 @@ -"""Agent credential file: server URL, agent id and the secret issued at enrollment. +"""Agent credential file: server URL, agent id, the secret issued at enrollment, and +optionally the CA certificate that the server's TLS certificate must chain to. -The secret never appears on a command line. ``shadowgate agent enroll`` writes this file +The secret never appears on a command line. Plain HTTP is allowed only to a loopback +address; a remote server must use HTTPS. ``shadowgate agent enroll`` writes this file with mode 0600 and refuses to overwrite an existing one; ``shadowgate agent run`` refuses a file that other users can read or write. """ @@ -9,8 +11,9 @@ import json import os +import ssl import stat -from dataclasses import asdict, dataclass +from dataclasses import dataclass from pathlib import Path from urllib.parse import urlsplit @@ -27,6 +30,7 @@ class AgentConfig: server_url: str agent_id: str agent_token: str + ca_pem: str | None = None # pinned CA; None means the system trust store def __post_init__(self) -> None: for name in ("server_url", "agent_id", "agent_token"): @@ -34,12 +38,39 @@ def __post_init__(self) -> None: if not isinstance(value, str) or not value.strip(): raise AgentConfigError(f"{name} must be a non-empty string") check_server_url(self.server_url) + if self.ca_pem is not None: + if urlsplit(self.server_url).scheme != "https": + raise AgentConfigError("a CA certificate only applies to an https:// server") + self.ssl_context() # fail now, not on the first poll + + def ssl_context(self) -> ssl.SSLContext | bool: + """What httpx should verify the server against.""" + if urlsplit(self.server_url).scheme != "https": + return True # plain HTTP to loopback: nothing to verify + if self.ca_pem is None: + return ssl.create_default_context() + try: + return ssl.create_default_context(cadata=self.ca_pem) + except (ssl.SSLError, ValueError) as exc: + raise AgentConfigError(f"the CA certificate is not valid PEM: {exc}") from None + + def as_dict(self) -> dict[str, str]: + data = {"server_url": self.server_url, "agent_id": self.agent_id, + "agent_token": self.agent_token} + if self.ca_pem is not None: + data["ca_pem"] = self.ca_pem + return data def check_server_url(url: str) -> None: parts = urlsplit(url) if parts.scheme not in ("http", "https") or not parts.hostname: raise AgentConfigError(f"server URL must be http(s)://host[:port], got {url!r}") + if is_plaintext_remote(url): + raise AgentConfigError( + f"refusing plain HTTP to {parts.hostname}: the agent credential would travel in " + "clear text; use https:// (see `shadowgate tls init`)" + ) def is_plaintext_remote(url: str) -> bool: @@ -56,7 +87,7 @@ def write_config(path: Path, config: AgentConfig) -> None: except FileExistsError: raise AgentConfigError(f"{path} already exists; refusing to overwrite it") from None with os.fdopen(fd, "w") as f: - json.dump(asdict(config), f, indent=2) + json.dump(config.as_dict(), f, indent=2) f.write("\n") @@ -80,6 +111,9 @@ def load_config(path: Path) -> AgentConfig: raw = json.loads(text) except ValueError: raise AgentConfigError(f"{path} is not valid JSON") from None - if not isinstance(raw, dict) or set(raw) != {"server_url", "agent_id", "agent_token"}: - raise AgentConfigError(f"{path} must contain exactly server_url, agent_id, agent_token") + required = {"server_url", "agent_id", "agent_token"} + if not isinstance(raw, dict) or not required <= set(raw) <= required | {"ca_pem"}: + raise AgentConfigError( + f"{path} must contain server_url, agent_id, agent_token and optionally ca_pem" + ) return AgentConfig(**raw) diff --git a/src/shadowgate/agent/poll.py b/src/shadowgate/agent/poll.py index 40dd045..5b5fc67 100644 --- a/src/shadowgate/agent/poll.py +++ b/src/shadowgate/agent/poll.py @@ -1,5 +1,6 @@ from __future__ import annotations +import ssl import time import httpx @@ -11,11 +12,15 @@ class AgentAuthError(Exception): """The server kept rejecting the agent credential.""" +class AgentTLSError(Exception): + """The server's TLS certificate failed verification; retrying will not help.""" + + class Poller: 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, - auth_retries: int = 3, + auth_retries: int = 3, verify: ssl.SSLContext | bool = True, ) -> None: self.executor = executor self.server_url = server_url.rstrip("/") @@ -24,12 +29,13 @@ def __init__( self.result_retries = result_retries self.retry_backoff = retry_backoff self.auth_retries = auth_retries + self.verify = verify self._auth_failures = 0 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) + transport=transport, verify=self.verify) def _check_auth(self, response: httpx.Response) -> bool: """Return False for a rejected credential, raising once rejections persist. @@ -95,5 +101,18 @@ def run(self) -> None: try: if not self.poll_once(client): time.sleep(self.poll_interval) + except httpx.ConnectError as exc: + if _is_certificate_failure(exc): + raise AgentTLSError(str(exc)) from exc + time.sleep(self.poll_interval) except (httpx.HTTPError, ValueError): time.sleep(self.poll_interval) + + +def _is_certificate_failure(exc: BaseException) -> bool: + seen: BaseException | None = exc + while seen is not None: + if isinstance(seen, ssl.SSLCertVerificationError): + return True + seen = seen.__cause__ or seen.__context__ + return "CERTIFICATE_VERIFY_FAILED" in str(exc) diff --git a/src/shadowgate/cli/main.py b/src/shadowgate/cli/main.py index 0e13c2f..85b8f5d 100644 --- a/src/shadowgate/cli/main.py +++ b/src/shadowgate/cli/main.py @@ -1,7 +1,8 @@ """``shadowgate`` command line. - shadowgate server [--host H] [--port P] - shadowgate agent enroll --server URL --agent-id ID [--tags T] [--config PATH] + shadowgate server [--host H] [--port P] [--tls-cert F --tls-key F] [--allow-plaintext] + shadowgate tls init [--dir D] [--hostname H ...] + shadowgate agent enroll --server URL --agent-id ID [--tags T] [--ca-file F] [--config PATH] shadowgate agent run [--config PATH] [--poll-interval S] shadowgate plugin list @@ -13,7 +14,10 @@ import argparse import getpass +import os import signal +import ssl +import stat import sys from collections.abc import Sequence from pathlib import Path @@ -27,7 +31,6 @@ AgentConfig, AgentConfigError, check_server_url, - is_plaintext_remote, load_config, write_config, ) @@ -67,15 +70,67 @@ def cmd_server(args: argparse.Namespace) -> int: return EXIT_CONFIG host = args.host or settings.host port = args.port if args.port is not None else settings.port + cert = args.tls_cert or settings.tls_cert_path + key = args.tls_key or settings.tls_key_path + tls_error = _check_tls_files(cert, key) + if tls_error: + _err(f"refusing to start: {tls_error}") + return EXIT_CONFIG + if not cert and host not in LOOPBACK_HOSTS: + if not args.allow_plaintext: + _err(f"refusing to listen on {host} without TLS: tokens would travel in clear text") + _err("pass --tls-cert/--tls-key (see `shadowgate tls init`), or --allow-plaintext " + "if a TLS proxy on a trusted network terminates connections for you") + return EXIT_CONFIG + _err(f"warning: listening on {host} without TLS; tokens travel in clear text") try: app = create_app(settings) except ValueError as exc: _err(f"refusing to start: {exc}") _err("set SHADOWGATE_API_TOKENS_JSON (see README, Configuration)") return EXIT_CONFIG - if host not in LOOPBACK_HOSTS: - _err(f"warning: listening on {host} without TLS; tokens travel in clear text") - uvicorn.run(app, host=host, port=port) + if cert: + uvicorn.run(app, host=host, port=port, ssl_certfile=cert, ssl_keyfile=key) + else: + uvicorn.run(app, host=host, port=port) + return EXIT_OK + + +def _check_tls_files(cert: str, key: str) -> str | None: + """Return why the certificate and key can't be used, or None.""" + if not cert and not key: + return None + if not (cert and key): + return "give both --tls-cert and --tls-key" + for path in (cert, key): + if not Path(path).is_file(): + return f"{path} not found" + mode = Path(key).stat().st_mode + if os.name == "posix" and mode & (stat.S_IRWXG | stat.S_IRWXO): + return f"{key} is accessible to other users (mode {stat.S_IMODE(mode):o}); chmod 600 it" + try: + ssl.create_default_context(ssl.Purpose.CLIENT_AUTH).load_cert_chain(cert, key) + except (ssl.SSLError, OSError) as exc: + return f"cannot load {cert} with {key}: {exc}" + return None + + +# --- tls ------------------------------------------------------------------------------ + + +def cmd_tls_init(args: argparse.Namespace) -> int: + from shadowgate.crypto.tls import DEFAULT_HOSTNAMES, init_tls + + try: + files = init_tls(Path(args.dir).expanduser(), args.hostname or []) + except FileExistsError as exc: + _err(str(exc)) + return EXIT_CONFIG + names = ", ".join(dict.fromkeys([*(args.hostname or []), *DEFAULT_HOSTNAMES])) + print(f"server certificate for: {names}") + print(f" server: --tls-cert {files.server_cert} --tls-key {files.server_key}") + print(f" agents: --ca-file {files.ca_cert}") + print(f"keep {files.ca_key} private (mode 600); it can issue certificates agents trust") return EXIT_OK @@ -98,8 +153,19 @@ def cmd_agent_enroll(args: argparse.Namespace) -> int: if config_path.exists(): _err(f"{config_path} already exists; refusing to overwrite it") return EXIT_CONFIG - if is_plaintext_remote(args.server): - _err("warning: enrolling over plain HTTP to a remote host; the secret is exposed") + ca_pem: str | None = None + if args.ca_file: + try: + ca_pem = Path(args.ca_file).expanduser().read_text() + verify = AgentConfig(args.server, args.agent_id, "-", ca_pem).ssl_context() + except OSError as exc: + _err(f"cannot read {args.ca_file}: {exc.strerror}") + return EXIT_CONFIG + except AgentConfigError as exc: + _err(str(exc)) + return EXIT_CONFIG + else: + verify = AgentConfig(args.server, args.agent_id, "-").ssl_context() token = _read_enrollment_token() if not token: _err("no enrollment token on stdin") @@ -108,7 +174,8 @@ def cmd_agent_enroll(args: argparse.Namespace) -> int: url = args.server.rstrip("/") + "/enroll" try: response = httpx.post( - url, json={"agent_id": args.agent_id, "token": token, "tags": args.tags}, timeout=15 + url, json={"agent_id": args.agent_id, "token": token, "tags": args.tags}, + timeout=15, verify=verify, ) except httpx.HTTPError as exc: _err(f"cannot reach {url}: {exc}") @@ -124,7 +191,8 @@ def cmd_agent_enroll(args: argparse.Namespace) -> int: return EXIT_FAILURE try: secret = response.json()["agent_token"] - config = AgentConfig(server_url=args.server, agent_id=args.agent_id, agent_token=secret) + config = AgentConfig(server_url=args.server, agent_id=args.agent_id, + agent_token=secret, ca_pem=ca_pem) write_config(config_path, config) except (ValueError, KeyError, TypeError, AgentConfigError) as exc: _err(f"enrolled, but the credential could not be saved: {exc}") @@ -139,7 +207,7 @@ def _stop_on_sigterm(signum: int, frame: FrameType | None) -> None: def cmd_agent_run(args: argparse.Namespace) -> int: from shadowgate.agent.executor import Executor - from shadowgate.agent.poll import AgentAuthError, Poller + from shadowgate.agent.poll import AgentAuthError, AgentTLSError, Poller try: config = load_config(Path(args.config)) @@ -149,14 +217,13 @@ def cmd_agent_run(args: argparse.Namespace) -> int: if args.poll_interval <= 0: _err("--poll-interval must be positive") return EXIT_CONFIG - if is_plaintext_remote(config.server_url): - _err("warning: plain HTTP to a remote host; the agent credential is exposed") poller = Poller( Executor(_registry(), agent_id=config.agent_id), config.server_url, agent_token=config.agent_token, poll_interval=args.poll_interval, + verify=config.ssl_context(), ) previous = signal.signal(signal.SIGTERM, _stop_on_sigterm) print(f"agent {config.agent_id} polling {config.server_url}", flush=True) @@ -165,6 +232,9 @@ def cmd_agent_run(args: argparse.Namespace) -> int: except AgentAuthError as exc: _err(f"stopping: {exc}; re-enroll this agent") return EXIT_AUTH + except AgentTLSError as exc: + _err(f"stopping: the server's TLS certificate failed verification: {exc}") + return EXIT_CONFIG except KeyboardInterrupt: print(f"agent {config.agent_id} stopped", flush=True) return EXIT_OK @@ -188,13 +258,27 @@ def cmd_plugin_list(args: argparse.Namespace) -> int: def build_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser(prog="shadowgate") parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}") - sub = parser.add_subparsers(dest="cmd", required=True, metavar="{server,agent,plugin}") + sub = parser.add_subparsers(dest="cmd", required=True, + metavar="{server,tls,agent,plugin}") server = sub.add_parser("server", help="run the control server") server.add_argument("--host", help="bind address (default: settings, 127.0.0.1)") server.add_argument("--port", type=int, help="port (default: settings, 8080)") + server.add_argument("--tls-cert", help="PEM certificate (chain) to serve HTTPS with") + server.add_argument("--tls-key", help="PEM private key for --tls-cert (mode 600)") + server.add_argument("--allow-plaintext", action="store_true", + help="allow a non-loopback bind without TLS (behind a TLS proxy only)") server.set_defaults(func=cmd_server) + tls = sub.add_parser("tls", help="create TLS certificates") + tls_sub = tls.add_subparsers(dest="tls_cmd", required=True, metavar="{init}") + tls_init = tls_sub.add_parser("init", help="create a private CA and a server certificate") + tls_init.add_argument("--dir", default=".shadowgate/tls", help="output directory") + tls_init.add_argument("--hostname", action="append", + help="name or IP agents use to reach the server (repeatable); " + "localhost and 127.0.0.1 are always included") + tls_init.set_defaults(func=cmd_tls_init) + agent = sub.add_parser("agent", help="enroll or run an agent") agent_sub = agent.add_subparsers(dest="agent_cmd", required=True, metavar="{enroll,run}") config_help = f"agent credential file (default: {DEFAULT_CONFIG_PATH})" @@ -203,7 +287,10 @@ def build_parser() -> argparse.ArgumentParser: "enroll", help="enroll with a one-time token read from stdin and save the credential", ) - enroll.add_argument("--server", required=True, help="server URL, e.g. http://127.0.0.1:8080") + enroll.add_argument("--server", required=True, + help="server URL, e.g. https://gw.example:8443 (http only to loopback)") + enroll.add_argument("--ca-file", help="CA certificate to pin for an https server " + "(default: the system trust store)") enroll.add_argument("--agent-id", required=True) enroll.add_argument("--tags", default="", help="comma-separated tags, e.g. role=web") enroll.add_argument("--config", default=str(DEFAULT_CONFIG_PATH), help=config_help) diff --git a/src/shadowgate/config.py b/src/shadowgate/config.py index b45694a..78c2495 100644 --- a/src/shadowgate/config.py +++ b/src/shadowgate/config.py @@ -50,6 +50,8 @@ class Settings(BaseSettings): validation_alias=AliasChoices("SHADOWGATE_API_TOKENS_JSON", "SHADOWGATE_API_TOKENS"), ) rate_limit_per_minute: int = 60 + tls_cert_path: str = "" + tls_key_path: str = "" @classmethod def settings_customise_sources( diff --git a/src/shadowgate/crypto/tls.py b/src/shadowgate/crypto/tls.py new file mode 100644 index 0000000..8197776 --- /dev/null +++ b/src/shadowgate/crypto/tls.py @@ -0,0 +1,123 @@ +"""TLS material for ``shadowgate server``: a private CA and a server certificate. + +``shadowgate tls init`` calls :func:`init_tls`. Agents trust the CA certificate (passed to +``shadowgate agent enroll --ca-file`` and pinned in their credential file); the server +presents the server certificate. Private keys are created with mode 0600 and existing +files are never overwritten. A certificate from a public CA works too: give the server +its files and enroll agents without ``--ca-file``. +""" + +from __future__ import annotations + +import datetime as dt +import ipaddress +import os +from dataclasses import dataclass +from pathlib import Path + +from cryptography import x509 +from cryptography.hazmat.primitives import hashes, serialization +from cryptography.hazmat.primitives.asymmetric import ec +from cryptography.x509.oid import ExtendedKeyUsageOID, NameOID + +DEFAULT_HOSTNAMES = ("localhost", "127.0.0.1") +CA_DAYS = 3650 +SERVER_DAYS = 397 + + +@dataclass(frozen=True) +class TlsFiles: + ca_cert: Path + ca_key: Path + server_cert: Path + server_key: Path + + @classmethod + def in_dir(cls, directory: Path) -> TlsFiles: + return cls(directory / "ca.crt", directory / "ca.key", + directory / "server.crt", directory / "server.key") + + +def _name(common_name: str) -> x509.Name: + return x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, common_name)]) + + +def _san(hostnames: list[str]) -> x509.SubjectAlternativeName: + entries: list[x509.GeneralName] = [] + for host in hostnames: + try: + entries.append(x509.IPAddress(ipaddress.ip_address(host))) + except ValueError: + entries.append(x509.DNSName(host)) + return x509.SubjectAlternativeName(entries) + + +def _write_private(path: Path, data: bytes) -> None: + fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + with os.fdopen(fd, "wb") as f: + f.write(data) + + +def _write_public(path: Path, data: bytes) -> None: + fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o644) + with os.fdopen(fd, "wb") as f: + f.write(data) + + +def _key_pem(key: ec.EllipticCurvePrivateKey) -> bytes: + return key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, + serialization.NoEncryption()) + + +def init_tls(directory: Path, hostnames: list[str]) -> TlsFiles: + """Create a CA and a server certificate for ``hostnames`` in ``directory``.""" + files = TlsFiles.in_dir(directory) + existing = [p for p in vars(files).values() if p.exists()] + if existing: + raise FileExistsError(f"refusing to overwrite {', '.join(map(str, existing))}") + names = list(dict.fromkeys([*hostnames, *DEFAULT_HOSTNAMES])) + directory.mkdir(parents=True, exist_ok=True, mode=0o700) + now = dt.datetime.now(dt.UTC) + + ca_key = ec.generate_private_key(ec.SECP256R1()) + ca_cert = ( + x509.CertificateBuilder() + .subject_name(_name("ShadowGate local CA")) + .issuer_name(_name("ShadowGate local CA")) + .public_key(ca_key.public_key()) + .serial_number(x509.random_serial_number()) + .not_valid_before(now - dt.timedelta(minutes=5)) + .not_valid_after(now + dt.timedelta(days=CA_DAYS)) + .add_extension(x509.BasicConstraints(ca=True, path_length=0), critical=True) + .add_extension(x509.KeyUsage( + digital_signature=False, content_commitment=False, key_encipherment=False, + data_encipherment=False, key_agreement=False, key_cert_sign=True, + crl_sign=True, encipher_only=False, decipher_only=False, + ), critical=True) + .add_extension(x509.SubjectKeyIdentifier.from_public_key(ca_key.public_key()), + critical=False) + .sign(ca_key, hashes.SHA256()) + ) + + server_key = ec.generate_private_key(ec.SECP256R1()) + server_cert = ( + x509.CertificateBuilder() + .subject_name(_name(names[0])) + .issuer_name(ca_cert.subject) + .public_key(server_key.public_key()) + .serial_number(x509.random_serial_number()) + .not_valid_before(now - dt.timedelta(minutes=5)) + .not_valid_after(now + dt.timedelta(days=SERVER_DAYS)) + .add_extension(x509.BasicConstraints(ca=False, path_length=None), critical=True) + .add_extension(_san(names), critical=False) + .add_extension(x509.ExtendedKeyUsage([ExtendedKeyUsageOID.SERVER_AUTH]), critical=False) + .add_extension(x509.AuthorityKeyIdentifier.from_issuer_public_key(ca_key.public_key()), + critical=False) + .sign(ca_key, hashes.SHA256()) + ) + + _write_private(files.ca_key, _key_pem(ca_key)) + _write_public(files.ca_cert, ca_cert.public_bytes(serialization.Encoding.PEM)) + _write_private(files.server_key, _key_pem(server_key)) + _write_public(files.server_cert, server_cert.public_bytes(serialization.Encoding.PEM)) + return files diff --git a/tests/test_cli.py b/tests/test_cli.py index 4f78f02..cf0e1f9 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -79,7 +79,7 @@ def test_server_starts_with_settings(monkeypatch, tmp_path, fake_uvicorn): def test_server_flags_override_settings(monkeypatch, tmp_path, fake_uvicorn, capsys): _server_env(monkeypatch, tmp_path, TOKENS) - assert cli.main(["server", "--host", "0.0.0.0", "--port", "9999"]) == 0 + assert cli.main(["server", "--host", "0.0.0.0", "--port", "9999", "--allow-plaintext"]) == 0 assert (fake_uvicorn[0]["host"], fake_uvicorn[0]["port"]) == ("0.0.0.0", 9999) assert "without TLS" in capsys.readouterr().err @@ -113,7 +113,8 @@ def test_config_written_owner_only_and_never_overwritten(tmp_path): (None, 0o600, "not found"), ('{"server_url":"http://h","agent_id":"a1","agent_token":"t"}', 0o644, "other users"), ("not json", 0o600, "not valid JSON"), - ('{"server_url":"http://h","agent_id":"a1"}', 0o600, "exactly"), + ('{"server_url":"http://h","agent_id":"a1"}', 0o600, "must contain"), + ('{"server_url":"http://h","agent_id":"a1","agent_token":"t"}', 0o600, "plain HTTP"), ('{"server_url":"ftp://h","agent_id":"a1","agent_token":"t"}', 0o600, "http"), ('{"server_url":"http://h","agent_id":"a1","agent_token":" "}', 0o600, "agent_token"), ], @@ -172,7 +173,8 @@ def enroll_via(monkeypatch, rbac_client): """Route the CLI's enrollment request into the test app and feed stdin.""" sent: list[dict[str, Any]] = [] - def fake_post(url: str, *, json: dict[str, Any], timeout: float) -> httpx.Response: + def fake_post(url: str, *, json: dict[str, Any], timeout: float, + verify: Any) -> httpx.Response: assert url == "http://127.0.0.1:8080/enroll" sent.append(json) return rbac_client.post("/enroll", json=json) diff --git a/tests/test_tls.py b/tests/test_tls.py new file mode 100644 index 0000000..3dd0ca2 --- /dev/null +++ b/tests/test_tls.py @@ -0,0 +1,254 @@ +"""T14: built-in TLS (`shadowgate tls init`, `server --tls-cert/--tls-key`, agent CA pinning).""" + +from __future__ import annotations + +import ipaddress +import json +import os +import signal +import ssl +import stat +import subprocess +import sys +from pathlib import Path +from typing import Any + +import httpx +import pytest +from conftest import TOKENS, _paths +from cryptography import x509 +from cryptography.hazmat.primitives import hashes +from cryptography.hazmat.primitives.asymmetric import ec +from test_cli import _free_port, _wait_for + +from shadowgate.agent.config import AgentConfig, AgentConfigError, load_config, write_config +from shadowgate.agent.poll import AgentTLSError, Poller +from shadowgate.cli import main as cli + +ADMIN = {"Authorization": "Bearer tok-admin"} +OPERATOR = {"Authorization": "Bearer tok-op"} + + +def _init(directory: Path, *hostnames: str) -> Path: + args = ["tls", "init", "--dir", str(directory)] + for name in hostnames: + args += ["--hostname", name] + assert cli.main(args) == 0 + return directory + + +# --- tls init ------------------------------------------------------------------------- + + +def test_tls_init_creates_a_ca_and_a_server_certificate(tmp_path, capsys): + tls = _init(tmp_path / "tls", "gw.example", "10.0.0.5") + out = capsys.readouterr().out + assert "--ca-file" in out and "--tls-cert" in out + for name in ("ca.key", "server.key"): + assert stat.S_IMODE((tls / name).stat().st_mode) == 0o600, name + + ca = x509.load_pem_x509_certificate((tls / "ca.crt").read_bytes()) + server = x509.load_pem_x509_certificate((tls / "server.crt").read_bytes()) + san = server.extensions.get_extension_for_class(x509.SubjectAlternativeName).value + assert san.get_values_for_type(x509.DNSName) == ["gw.example", "localhost"] + assert san.get_values_for_type(x509.IPAddress) == [ + ipaddress.ip_address("10.0.0.5"), ipaddress.ip_address("127.0.0.1") + ] + assert server.issuer == ca.subject + ca_key = ca.public_key() + assert isinstance(ca_key, ec.EllipticCurvePublicKey) + ca_key.verify(server.signature, server.tbs_certificate_bytes, ec.ECDSA(hashes.SHA256())) + + +def test_tls_init_never_overwrites(tmp_path, capsys): + tls = _init(tmp_path / "tls") + before = (tls / "ca.key").read_bytes() + assert cli.main(["tls", "init", "--dir", str(tls)]) == 2 + assert "refusing to overwrite" in capsys.readouterr().err + assert (tls / "ca.key").read_bytes() == before + + +# --- server --------------------------------------------------------------------------- + + +@pytest.fixture +def fake_uvicorn(monkeypatch, tmp_path): + import uvicorn + + for key, value in _paths(tmp_path).items(): + monkeypatch.setenv(f"SHADOWGATE_{key.upper()}", value) + monkeypatch.setenv("SHADOWGATE_API_TOKENS_JSON", TOKENS) + calls: list[dict[str, Any]] = [] + monkeypatch.setattr(uvicorn, "run", lambda app, **kw: calls.append(kw)) + return calls + + +def test_server_refuses_remote_bind_without_tls(fake_uvicorn, capsys): + assert cli.main(["server", "--host", "0.0.0.0"]) == 2 + assert fake_uvicorn == [] + assert "without TLS" in capsys.readouterr().err + + +def test_server_serves_https_with_tls_files(fake_uvicorn, tmp_path): + tls = _init(tmp_path / "tls") + assert cli.main(["server", "--host", "0.0.0.0", "--tls-cert", str(tls / "server.crt"), + "--tls-key", str(tls / "server.key")]) == 0 + assert fake_uvicorn[0]["ssl_certfile"] == str(tls / "server.crt") + assert fake_uvicorn[0]["ssl_keyfile"] == str(tls / "server.key") + + +def test_server_reads_tls_files_from_settings(fake_uvicorn, tmp_path, monkeypatch): + tls = _init(tmp_path / "tls") + monkeypatch.setenv("SHADOWGATE_TLS_CERT_PATH", str(tls / "server.crt")) + monkeypatch.setenv("SHADOWGATE_TLS_KEY_PATH", str(tls / "server.key")) + assert cli.main(["server"]) == 0 + assert fake_uvicorn[0]["ssl_certfile"] == str(tls / "server.crt") + + +def test_server_rejects_unusable_tls_files(fake_uvicorn, tmp_path, capsys): + tls = _init(tmp_path / "tls") + other = _init(tmp_path / "other") + cert, key = str(tls / "server.crt"), str(tls / "server.key") + cases = [ + (["--tls-cert", cert], "both"), + (["--tls-cert", cert, "--tls-key", str(tmp_path / "missing.key")], "not found"), + (["--tls-cert", cert, "--tls-key", str(other / "server.key")], "cannot load"), + ] + for extra, message in cases: + assert cli.main(["server", *extra]) == 2, extra + assert message in capsys.readouterr().err, extra + os.chmod(key, 0o644) + assert cli.main(["server", "--tls-cert", cert, "--tls-key", key]) == 2 + assert "other users" in capsys.readouterr().err + assert fake_uvicorn == [] + + +# --- agent config and enroll ---------------------------------------------------------- + + +def test_plain_http_is_refused_for_remote_servers(): + with pytest.raises(AgentConfigError, match="plain HTTP"): + AgentConfig("http://gw.example:8080", "a1", "t") + for url in ("http://127.0.0.1:8080", "http://localhost", "https://gw.example"): + AgentConfig(url, "a1", "t") + + +def test_pinned_ca_round_trips_and_is_validated(tmp_path): + tls = _init(tmp_path / "tls") + ca_pem = (tls / "ca.crt").read_text() + path = tmp_path / "agent.json" + write_config(path, AgentConfig("https://gw.example", "a1", "t", ca_pem)) + assert load_config(path).ca_pem == ca_pem + assert isinstance(load_config(path).ssl_context(), ssl.SSLContext) + with pytest.raises(AgentConfigError, match="https"): + AgentConfig("http://127.0.0.1", "a1", "t", ca_pem) + with pytest.raises(AgentConfigError, match="PEM"): + AgentConfig("https://gw.example", "a1", "t", "not a certificate") + + +@pytest.mark.parametrize( + ("server", "ca", "message"), + [ + ("http://gw.example:8080", None, "plain HTTP"), + ("http://127.0.0.1:8080", "ca.crt", "only applies to an https"), + ("https://gw.example", "missing.crt", "cannot read"), + ], +) +def test_enroll_rejects_insecure_or_bad_tls_settings(tmp_path, capsys, server, ca, message): + _init(tmp_path) + args = ["agent", "enroll", "--server", server, "--agent-id", "a1", + "--config", str(tmp_path / "agent.json")] + if ca: + args += ["--ca-file", str(tmp_path / ca)] + assert cli.main(args) == 2 + assert message in capsys.readouterr().err + assert not (tmp_path / "agent.json").exists() + + +def test_poller_stops_on_certificate_failure(): + def handler(request: httpx.Request) -> httpx.Response: + error = ssl.SSLCertVerificationError("certificate verify failed") + raise httpx.ConnectError("[SSL: CERTIFICATE_VERIFY_FAILED]", request=request) from error + + poller = Poller(None, "https://server", agent_token="t", poll_interval=0) # type: ignore[arg-type] + poller.make_client = lambda transport=None: httpx.Client( # type: ignore[method-assign] + transport=httpx.MockTransport(handler)) + with pytest.raises(AgentTLSError): + poller.run() + + +# --- end to end over HTTPS ------------------------------------------------------------ + + +def test_end_to_end_over_https(tmp_path): + tls = _init(tmp_path / "tls") + wrong = _init(tmp_path / "wrong") + port = _free_port() + base = f"https://127.0.0.1:{port}" + env = {k: v for k, v in os.environ.items() if not k.upper().startswith("SHADOWGATE_")} + env.update({f"SHADOWGATE_{k.upper()}": v for k, v in _paths(tmp_path).items()}) + env["SHADOWGATE_API_TOKENS_JSON"] = TOKENS + shadowgate = [sys.executable, "-m", "shadowgate.cli.main"] + ca = ssl.create_default_context(cafile=str(tls / "ca.crt")) + procs: list[subprocess.Popen[str]] = [] + + def start(*args: str) -> subprocess.Popen[str]: + proc = subprocess.Popen([*shadowgate, *args], cwd=tmp_path, env=env, text=True, + stdout=subprocess.PIPE, stderr=subprocess.STDOUT) + procs.append(proc) + return proc + + def enroll(agent_id: str, ca_file: Path, config: Path) -> subprocess.CompletedProcess[str]: + invite = httpx.post(f"{base}/tokens", headers=ADMIN, verify=ca).json()["token"] + return subprocess.run( + [*shadowgate, "agent", "enroll", "--server", base, "--agent-id", agent_id, + "--ca-file", str(ca_file), "--config", str(config)], + input=invite + "\n", cwd=tmp_path, env=env, text=True, + capture_output=True, timeout=30, + ) + + try: + server = start("server", "--port", str(port), "--tls-cert", str(tls / "server.crt"), + "--tls-key", str(tls / "server.key")) + _wait_for(lambda: httpx.get(f"{base}/healthz", verify=ca).status_code == 200) + with pytest.raises(httpx.TransportError): # plain HTTP is not served + httpx.get(f"http://127.0.0.1:{port}/healthz") + + # an agent pinned to the wrong CA refuses the server and saves nothing + rejected = enroll("bad", wrong / "ca.crt", tmp_path / "bad.json") + assert rejected.returncode == 1 and "CERTIFICATE_VERIFY_FAILED" in rejected.stderr + assert not (tmp_path / "bad.json").exists() + + config = tmp_path / "agent.json" + enrolled = enroll("e2e", tls / "ca.crt", config) + assert enrolled.returncode == 0, enrolled.stderr + assert json.loads(config.read_text())["ca_pem"] == (tls / "ca.crt").read_text() + + agent = start("agent", "run", "--config", str(config), "--poll-interval", "0.2") + httpx.post(f"{base}/jobs", headers=OPERATOR, verify=ca, + json={"agent_id": "e2e", "action": "system_info"}) + _wait_for(lambda: httpx.get(f"{base}/jobs", headers=OPERATOR, verify=ca) + .json()["stats"] == {"done": 1}) + agent.send_signal(signal.SIGTERM) + out, _ = agent.communicate(timeout=15) + assert agent.returncode == 0, out + + # the same credential pinned to the wrong CA stops with a clear error + tampered = load_config(config) + bad_config = tmp_path / "wrong-ca.json" + write_config(bad_config, AgentConfig(tampered.server_url, tampered.agent_id, + tampered.agent_token, + (wrong / "ca.crt").read_text())) + stopped = subprocess.run( + [*shadowgate, "agent", "run", "--config", str(bad_config), "--poll-interval", "0.1"], + cwd=tmp_path, env=env, text=True, capture_output=True, timeout=30, + ) + assert stopped.returncode == 2 and "failed verification" in stopped.stderr + + server.send_signal(signal.SIGTERM) + server.communicate(timeout=15) + finally: + for proc in procs: + if proc.poll() is None: + proc.kill() + proc.communicate() From ee2f02ffd2851280b143b7ff1fab15b83501b5db Mon Sep 17 00:00:00 2001 From: "Saransh Singh (Splo1t)" <148835673+5aranx@users.noreply.github.com> Date: Mon, 30 Nov 2026 17:01:11 +0530 Subject: [PATCH 5/5] CI on Python 3.12 and 3.13, end-to-end demo, README badges MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - CI installs from the lock file and runs examples/demo.sh. - examples/demo.sh: HTTPS server, three agents, a runbook run, audit verification and a tamper check, in a temporary directory. - README: CI, release, license and Python badges; demo section. - Tracker §14 records N1, T11, T12, T14, CI and demo. --- .github/workflows/ci.yml | 16 ++++++--- CHANGELOG.md | 3 ++ README.md | 16 +++++++++ docs/tracker.md | 29 +++++++++++++-- examples/demo.sh | 78 ++++++++++++++++++++++++++++++++++++++++ 5 files changed, 134 insertions(+), 8 deletions(-) create mode 100755 examples/demo.sh diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3a83b57..95bcf26 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -5,6 +5,10 @@ on: [push, pull_request] jobs: test: runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + python: ["3.12", "3.13"] steps: - uses: actions/checkout@v4 - uses: astral-sh/setup-uv@v5 @@ -12,8 +16,10 @@ jobs: version: "0.12.22" - uses: actions/setup-python@v5 with: - python-version: "3.12" - - run: uv sync --extra dev - - run: uv run ruff check src tests - - run: uv run mypy - - run: uv run pytest -q + python-version: ${{ matrix.python }} + - run: uv sync --frozen --extra dev --python ${{ matrix.python }} + - run: uv run --frozen ruff check src tests + - run: uv run --frozen mypy + - run: uv run --frozen pytest -q + - name: Demo + run: uv run --frozen bash examples/demo.sh diff --git a/CHANGELOG.md b/CHANGELOG.md index b4789e1..f2124e3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,9 @@ All notable changes to ShadowGate are recorded here. The format follows `shadowgate server --tls-cert/--tls-key`, and `agent enroll --ca-file`, which pins the CA in the agent's credential file. +- `examples/demo.sh`: one-command end-to-end demo (HTTPS, three agents, a runbook run, + audit verification and a tamper check). CI runs it, on Python 3.12 and 3.13. + ### Changed - The server refuses a non-loopback bind without TLS (`--allow-plaintext` overrides), and agents refuse plain HTTP to non-loopback hosts. An agent stops (exit 2) when the server diff --git a/README.md b/README.md index 14e7a87..06086a1 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,10 @@ # ShadowGate +[![CI](https://github.com/5aranx/ShadowGate/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/5aranx/ShadowGate/actions/workflows/ci.yml) +[![Release](https://img.shields.io/github/v/tag/5aranx/ShadowGate?label=release)](https://github.com/5aranx/ShadowGate/releases/tag/v0.1.0) +[![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE) +![Python 3.12 | 3.13](https://img.shields.io/badge/python-3.12%20%7C%203.13-blue.svg) + ShadowGate is a control server for running audited jobs on Linux hosts you own and administer. Operators enroll agents, queue actions or runbooks (dependency graphs of actions) against them, and review the results on an audit log and a read-only dashboard. @@ -117,6 +122,17 @@ dev mode makes startup fail with an error, before any files are created. ## Running +### One-command demo + +```bash +bash examples/demo.sh +``` + +In a temporary directory that is removed afterwards, the demo creates TLS certificates, +starts the server over HTTPS with fresh random tokens, enrolls three agents, runs the +example runbook on all of them, verifies the audit log, then deletes the newest audit entry +to show the tamper check failing. It needs `curl` and `jq`, and CI runs it on every push. + ### Local development launcher ```bash diff --git a/docs/tracker.md b/docs/tracker.md index 4a6d7e3..785b8a6 100644 --- a/docs/tracker.md +++ b/docs/tracker.md @@ -24,10 +24,10 @@ S1–S8 and C1–C9 and probes P1–P11. | T9 | Result persistence, claim attempt and lease, re-queue | P1 | High | Planned | M7, T5 | | T10 | Working `shadowgate server` / `shadowgate agent` CLI | P1 | Med | **Done (§12)** | M7 | | T23 | Enqueue validation (target agent must exist) | P1 | Low | Planned | M7 | -| T11 | Transaction boundaries and connection serialization | P2 | High | **Partly done (§11):** serialization done; transaction boundaries open | M7 | -| T12 | Serialized, anchored, O(1) audit log | P2 | High | **Partly done (§11):** append lock done; anchoring and O(1) open | T11 | +| T11 | Transaction boundaries and connection serialization | P2 | High | **Done (§11, §14)** | M7 | +| T12 | Serialized, anchored, O(1) audit log | P2 | High | **Done (§11, §14):** local anchor; signed/off-host checkpoints not done | 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 | +| T14 | Transport identity (TLS / mTLS) decision and implementation | P2 | Med | **Done (§14):** owner chose built-in TLS; mTLS not done | 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 | @@ -1252,6 +1252,28 @@ and strict mypy clean. The README commands were also run live. wheel and sdist carry version 0.1.0, the new description, and no removed dependencies (see the change log row). +## 14. After 0.1.0: N1, T11, T12, T14, CI and demo (2026-11-30) + +**Scope (owner-approved):** N1; the rest of T11 and T12; T14 with **built-in TLS** (owner +decision over mTLS and proxy-only); a CI badge and a demo script. + +| Item | Change | Tests (fail on the previous code) | +|---|---|---| +| **N1** | The `.env` source drops keys without the `SHADOWGATE_` prefix; unknown `SHADOWGATE_*` keys are still rejected; `shadowgate server` reports invalid settings without a traceback (exit 2). | 6 in `test_env_precedence.py` (4 failed before) | +| **T11** | `Transaction` (`server/db.py`) is the shared lock and the unit of work: nested calls join, the outermost exit commits, any error (or a swallowed nested error) rolls back. No helper commits. `/jobs`, `/agent/poll`, `/agent/result` are one transaction each. Enrollment writes its audit entry before committing. Audit appends inside a transaction are written just before the commit and dropped on rollback. Fixes F2 and the engine gap. | 9 in `test_transactions.py` (all failed before) | +| **T12** | `.head` anchors count and head after every write; `verify()` reports entries, verified prefix, anchored count and the error (removed, rewritten, corrupt, missing anchor). A log changed behind the server's back gets an `audit_anchor_mismatch` entry on the next write, and the old anchor is kept. Head cached per file: O(1) appends. `/audit?verify=true` adds `verification`. | 12 in `test_audit.py` (all failed before) | +| **T14** | `shadowgate tls init` (CA + server cert, EC P-256, keys 0600, no overwrite); `server --tls-cert/--tls-key` (or settings) with load and permission checks; non-loopback plaintext bind refused unless `--allow-plaintext`; `agent enroll --ca-file` pins the CA in the credential file; agents refuse plain HTTP to non-loopback hosts and stop (exit 2) on certificate failure. | 13 in `test_tls.py`, including an HTTPS end-to-end run with wrong-CA rejection | +| **CI / demo** | CI installs from the lock file (`--frozen`), runs on Python 3.12 and 3.13, and runs `examples/demo.sh`; README badges (CI, release, license, Python). | demo run locally; CI runs on push | + +**Verification:** `./run.sh --check` gives 151 passed with ruff and strict mypy clean; the +README HTTPS commands and the demo were run live. + +**Still open:** +- No mTLS, certificate rotation or revocation; the CA key stays next to the server unless moved. +- The audit anchor is local: rewriting both files, or deleting the anchor before a restart, is not detected. +- If the database commit itself fails after the audit entries were written, the log holds entries for a change that did not happen (rare). +- Locks are per process: run one server process. + ## 6. Change log | Date | Change | @@ -1266,3 +1288,4 @@ wheel and sdist carry version 0.1.0, the new description, and no removed depende | 2026-11-30 | T10 done (§12): `shadowgate server`, `agent enroll` (token via stdin, 0600 credential file), `agent run`, `plugin list`; `run.sh` uses the CLI. 25 tests incl. a real-process end-to-end test (110 total). B4 resolved. | | 2026-11-30 | B5 resolved with T18 (§13): accurate `pyproject` description, single-source version, CHANGELOG, removed `models.py` and 4 unused dependencies. 110 passed (repo and clean frozen copy); wheel metadata checked. All release blockers B1–B6 resolved; tagging awaits the owner. | | 2026-11-30 | `v0.1.0` tagged on `main` (owner-approved); CHANGELOG dated. | +| 2026-11-30 | After 0.1.0 (§14): N1 fixed; T11 done (one transaction per request, audit at commit; F2 and engine gap fixed); T12 done (anchored head, verification detail, O(1) appends); T14 done (built-in TLS, CA pinning, plaintext refused off loopback); CI on 3.12/3.13 runs a new demo; README badges. 151 tests. | diff --git a/examples/demo.sh b/examples/demo.sh new file mode 100755 index 0000000..28cb473 --- /dev/null +++ b/examples/demo.sh @@ -0,0 +1,78 @@ +#!/usr/bin/env bash +# ShadowGate end-to-end demo, entirely on this machine: +# HTTPS server -> 3 enrolled agents -> a runbook run -> verified audit log -> tamper check. +# Everything lives in a temporary directory that is removed on exit. Needs curl and jq. +set -euo pipefail + +for tool in curl jq; do + command -v "$tool" >/dev/null || { echo "demo needs $tool" >&2; exit 2; } +done +REPO=$(cd "$(dirname "$0")/.." && pwd) +SG=(uv run --project "$REPO" --frozen -q shadowgate) +WORK=$(mktemp -d) +PIDS=() +cleanup() { + for pid in "${PIDS[@]}"; do kill -TERM "$pid" 2>/dev/null || true; done + wait 2>/dev/null || true + rm -rf "$WORK" +} +trap cleanup EXIT +cd "$WORK" + +step() { printf '\n\033[1m== %s\033[0m\n' "$*"; } +random() { python3 -c 'import secrets; print(secrets.token_urlsafe(24))'; } +PORT=$(python3 -c 'import socket; s=socket.socket(); s.bind(("127.0.0.1",0)); print(s.getsockname()[1])') +BASE="https://localhost:$PORT" + +ADMIN=$(random); OPERATOR=$(random); VIEWER=$(random) # fresh per run, never printed +export SHADOWGATE_API_TOKENS_JSON="{\"$ADMIN\":\"admin\",\"$OPERATOR\":\"operator\",\"$VIEWER\":\"viewer\"}" +api() { # api TOKEN METHOD PATH [JSON] + curl -sf --cacert tls/ca.crt -X "$2" "$BASE$3" -H "Authorization: Bearer $1" \ + -H 'Content-Type: application/json' ${4:+-d "$4"} +} + +step "1. Create a private CA and server certificate" +"${SG[@]}" tls init --dir tls >/dev/null +ls -l tls | awk 'NR>1 {print " " $1, $NF}' + +step "2. Start the server over HTTPS on port $PORT" +"${SG[@]}" server --port "$PORT" --tls-cert tls/server.crt --tls-key tls/server.key \ + >server.log 2>&1 & +PIDS+=($!) +for _ in $(seq 100); do curl -sf --cacert tls/ca.crt "$BASE/healthz" >/dev/null && break; sleep 0.1; done +curl -sf --cacert tls/ca.crt "$BASE/healthz" | jq -c . + +step "3. Enroll three agents (one-time tokens via stdin; credentials saved mode 600)" +for agent in web-1 web-2 db-1; do + api "$ADMIN" POST /tokens "{\"agent_id\":\"$agent\"}" | jq -r .token | + "${SG[@]}" agent enroll --server "$BASE" --ca-file tls/ca.crt --agent-id "$agent" \ + --tags linux --config "$agent.json" + "${SG[@]}" agent run --config "$agent.json" --poll-interval 0.2 >"$agent.log" 2>&1 & + PIDS+=($!) +done +api "$VIEWER" GET /agents | jq -c '[.agents[].id]' + +step "4. Register the example runbook and run it on every 'linux' agent" +uv run --project "$REPO" --frozen -q python -c \ + 'import json,sys,yaml; print(json.dumps(yaml.safe_load(open(sys.argv[1]))))' \ + "$REPO/examples/runbooks/disk-health-audit.yaml" >runbook.json +api "$ADMIN" POST /runbooks "$(cat runbook.json)" | jq -c . +RUN=$(api "$OPERATOR" POST /runs '{"runbook":"disk-health-audit"}' | jq -r .run_id) +for _ in $(seq 100); do + STATUS=$(api "$VIEWER" GET "/runs/$RUN" | jq -r .status) + [[ "$STATUS" != running ]] && break + sleep 0.2 +done +api "$VIEWER" GET "/runs/$RUN" | jq -c '{status, steps}' +[[ "$STATUS" == done ]] || { echo "run did not finish: $STATUS" >&2; exit 1; } + +step "5. Verify the audit log" +api "$VIEWER" GET '/audit?verify=true' | jq -c '.verification' +api "$VIEWER" GET /audit | jq -r '.entries | group_by(.event) | map(" \(.[0].event): \(length)") | .[]' + +step "6. Tamper check: cut the newest audit entry and verify again" +AUDIT=$(python3 -c 'import os; print(os.environ.get("SHADOWGATE_AUDIT_LOG_PATH", ".shadowgate/audit.log"))') +sed -i '$ d' "$AUDIT" +api "$VIEWER" GET '/audit?verify=true' | jq -c '.verification | {ok, error}' + +step "Done. All state was in $WORK and is removed now."