diff --git a/README.md b/README.md index ac238a8..56e3ef5 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,8 @@ actions) against them, and review the results on an audit log and a read-only da **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 agent runs only as a Python library; the `shadowgate` command is not wired up yet. +- `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 beyond a single-host test setup. @@ -56,10 +57,10 @@ See [`docs/architecture.md`](docs/architecture.md) and | Path | Contents | |---|---| | `src/shadowgate/server/` | app, store, queue, runs, orchestrator, audit (`models.py` is unused) | -| `src/shadowgate/agent/` | executor, polling client (`Poller`) | +| `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/cli/` | `shadowgate` entry point (placeholder) | +| `src/shadowgate/cli/` | `shadowgate` command: `server`, `agent enroll`, `agent run`, `plugin list` | | `src/shadowgate/web/templates/` | dashboard templates | | `docs/` | architecture, threat model | | `examples/runbooks/` | sample runbook (YAML) | @@ -136,9 +137,12 @@ dev mode makes startup fail with an error, before any files are created. ```bash export SHADOWGATE_API_TOKENS_JSON='{"":"admin","":"operator","":"viewer"}' -uv run uvicorn --factory shadowgate.server.app:create_app --host 127.0.0.1 --port 8080 +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. + Replace the placeholders with long random values, e.g. `python -c 'import secrets; print(secrets.token_urlsafe(32))'`. ### Walkthrough @@ -181,20 +185,24 @@ curl -s -X POST localhost:8080/runs -H 'Authorization: Bearer op-token' \ -H 'Content-Type: application/json' -d '{"runbook":"disk-health-audit"}' ``` -**Running an agent.** There is no CLI for this yet. From Python: +**Running an agent.** Enroll once, then run. The one-time token is read from stdin (or a +hidden prompt), never from the command line, and the agent credential is saved to a file +only you can read (mode 600; default `~/.config/shadowgate/agent.json`): -```python -from shadowgate.agent.executor import Executor -from shadowgate.agent.poll import Poller -from shadowgate.plugins.base import Registry -from shadowgate.plugins.loader import load_builtins +```bash +curl -s -X POST localhost:8080/tokens -H 'Authorization: Bearer admin-token' \ + -H 'Content-Type: application/json' -d '{"agent_id":"a2"}' | jq -r .token | + uv run shadowgate agent enroll --server http://127.0.0.1:8080 --agent-id a2 --tags role=web -registry = Registry() -load_builtins(registry) -Poller(Executor(registry, agent_id="a1"), "http://127.0.0.1:8080", - agent_token="").run() +uv run shadowgate agent run # polls every second; Ctrl-C or SIGTERM stops it +uv run shadowgate plugin list # the actions this agent can run (builtins only) ``` +`agent enroll` refuses to overwrite an existing credential file, and `agent run` refuses +one that other users can read. Exit codes: `0` success, `1` server unreachable or other +failure, `2` usage or configuration error, `3` credential rejected (re-enroll). A transient +`401` is retried 3 times before the agent stops. + ### API summary | Method and path | Auth | @@ -253,7 +261,8 @@ yet implemented. `duplicate column name: secret_hash`. Restart and it succeeds. **Functional gaps** -- **CLI:** `shadowgate server|agent|plugin` print a placeholder; there is no agent CLI. +- **Agent CLI:** loads builtin actions only (no third-party plugins until verification is + wired, T13); there is no service unit or credential rotation. - **Job results:** - The `data` payload a job reports is not stored. - Jobs claimed by a crashed agent stay `running`. diff --git a/docs/architecture.md b/docs/architecture.md index 96caccc..7a267c5 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -3,8 +3,8 @@ ``` +-------------------+ HTTP + Agent Token +-------------------+ operator | shadowgate | <----------------------> | shadowgate agent | - dashboard | server (FastAPI) | (mTLS deferred to T14) | (library; CLI | - | | | not yet wired) | + dashboard | server (FastAPI) | (mTLS deferred to T14) | (CLI: enroll, | + | | | run; Poller) | | Store (sqlite) | | executor | | qjobs (WAL) | | builtins | | RunEngine | +-------------------+ diff --git a/docs/tracker.md b/docs/tracker.md index b57d8ec..8348163 100644 --- a/docs/tracker.md +++ b/docs/tracker.md @@ -22,7 +22,7 @@ S1–S8 and C1–C9 and probes P1–P11. | T7 | Runbook schema validation → 400; strict selectors | P1 | Med | Planned | none (serialize with T8 on `app.py`) | | T8 | Per-run runbook spec snapshot | P1 | Med | Planned | T7 | | T9 | Result persistence, claim attempt and lease, re-queue | P1 | High | Planned | M7, T5 | -| T10 | Working `shadowgate server` / `shadowgate agent` CLI | P1 | Med | Planned | M7 | +| 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 | @@ -1084,7 +1084,7 @@ The change-set items also pass: probes 18/18 (§7), suite, ruff, mypy, docs. | B1 | `pyproject.toml` declares MIT, but there is **no `LICENSE` file** | Documentation review D7 | **Resolved (§10):** MIT `LICENSE` added, `Copyright (c) 2026 5aranx` | | B2 | Concurrent use is unreliable: stranded jobs and 500s (E1); valid agents get spurious 401, and the `Poller` stops (V1); the audit chain forks (E2) | Phase 4 §8 | **Resolved (§11)** for a single server process | | B3 | The documented check `./run.sh --check` fails 6 tests (V2); `run.sh` overrides `.env` tokens (V3) | Phase 4 §8; clean-copy test run | **Resolved (§10)** | -| B4 | There is no runnable agent: the CLI subcommands are placeholders that exit 0 | Integration and test review | T10 (approval) | +| B4 | There is no runnable agent: the CLI subcommands are placeholders that exit 0 | Integration and test review | **Resolved (§12)** | | B5 | Package metadata is stale: `pyproject` description claims mTLS and signed plugins; no CHANGELOG; the version is defined twice; unused dependencies | Documentation review D8–D10/D17; dependency review | Owner-approved metadata change (and T18) | | B6 | The process docs are untracked and contain local or internal references | Architecture review; coordinator | **Resolved (§10):** sanitized, to be committed | @@ -1109,7 +1109,7 @@ All user-visible items are listed in the README's Known limitations. |---|---| | Commit M7 to `main` as a reviewed milestone (not a release) | Reasonable once the owner decides B3 (or accepts it as documented) and B6. Security goals are verified, and CI-equivalent checks are green. | | Tagged pre-release / public publication | **Not ready**: B1, B3, B5 | -| Multi-agent or networked deployment | **Not ready**: B4, plus no TLS (T14). B2 resolved for one server process (§11). | +| Multi-agent or networked deployment | Loopback multi-agent use works (B2, B4 resolved, §11–§12). Networked: **not ready**, no TLS (T14). | ## 10. Blocker 3 fix, license and documentation cleanup (2026-11-30) @@ -1214,6 +1214,29 @@ mypy clean, and the concurrency file passed 5 consecutive runs. - T12: tail truncation is undetected and appends are still O(n). - V5 (enrollment 500 when SQLite is busy) is unchanged. +## 12. T10: working command line (2026-11-30) + +**Scope (owner-approved):** T10 as planned in §1. Third-party plugins stay unloaded +until T13. + +| Command | Behavior | +|---|---| +| `shadowgate server [--host] [--port]` | Builds the app from validated settings and runs uvicorn. Invalid or missing operator tokens: message and exit 2. Non-loopback bind: warning (no TLS). `run.sh` now starts the server this way. | +| `shadowgate agent enroll --server --agent-id [--tags] [--config]` | Reads the one-time token from stdin (hidden prompt on a TTY), never argv. Refuses an existing config file before contacting the server. Writes `{server_url, agent_id, agent_token}` with `O_EXCL` and mode 0600 (directory 0700). 403/409 → exit 3. | +| `shadowgate agent run [--config] [--poll-interval]` | Refuses a missing, malformed or group/other-accessible config (exit 2). Builtin actions only. SIGTERM or Ctrl-C → exit 0; persistent credential rejection → exit 3. | +| `shadowgate plugin list` | Lists the builtin actions. | +| No or unknown subcommand | argparse usage error, exit 2 (was exit 0). | + +**Tests:** `tests/test_cli.py` (25), including an end-to-end test that runs `shadowgate +server` and `shadowgate agent run` as real processes: enroll over stdin, queue a job, the +agent completes it, the audit chain verifies, both stop on SIGTERM. Total 110 passed; ruff +and strict mypy clean. The README commands were also run live. + +**Still open:** +- The secret is lost if saving the config file fails after enrollment (same class as F2). +- With the server down, `agent run` retries silently every interval; there is no logging. +- No service unit, credential rotation or revocation (not yet planned as a task). + ## 6. Change log | Date | Change | @@ -1225,3 +1248,4 @@ mypy clean, and the concurrency file passed 5 consecutive runs. | 2026-11-30 | Phase 5 release readiness: **NOT READY** (§9). Docs only: README rewritten (all commands executed verbatim); architecture and threat-model corrected for the audit, concurrency and transport findings (documentation review recheck: all fixed). Clean frozen build green (61 ×3); V2 reproduced. Blockers B1–B6 await owner decisions. Nothing staged, committed, pushed or tagged. | | 2026-11-30 | B3 fixed (test isolation, `run.sh` token precedence), 16 regression tests added (77 total), MIT LICENSE added, process docs sanitized; independent review clean (no Critical/High). N1 recorded (pre-existing `.env` strictness). Prepared for commit (§10). | | 2026-11-30 | B2 fixed for one server process (§11): shared-connection lock (E1, V1), per-file audit append lock (E2), Poller retries transient 401. 8 tests added (85 total); the 4 concurrency tests fail on the unfixed tree. T11 transaction boundaries and T12 anchoring/O(1) remain open. | +| 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. | diff --git a/run.sh b/run.sh index 68b8f08..a41707a 100755 --- a/run.sh +++ b/run.sh @@ -34,4 +34,4 @@ else echo "operator tokens: development defaults admin-token / op-token / view-token" fi echo "stop with Ctrl-C" -exec uv run uvicorn --factory shadowgate.server.app:create_app --host 127.0.0.1 --port 8080 +exec uv run shadowgate server --host 127.0.0.1 --port 8080 diff --git a/src/shadowgate/agent/config.py b/src/shadowgate/agent/config.py new file mode 100644 index 0000000..a0bf797 --- /dev/null +++ b/src/shadowgate/agent/config.py @@ -0,0 +1,85 @@ +"""Agent credential file: server URL, agent id and the secret issued at enrollment. + +The secret never appears on a command line. ``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. +""" + +from __future__ import annotations + +import json +import os +import stat +from dataclasses import asdict, dataclass +from pathlib import Path +from urllib.parse import urlsplit + +DEFAULT_CONFIG_PATH = Path("~/.config/shadowgate/agent.json") +LOOPBACK_HOSTS = {"127.0.0.1", "::1", "localhost"} + + +class AgentConfigError(Exception): + """The agent configuration is missing, malformed or unsafe.""" + + +@dataclass(frozen=True) +class AgentConfig: + server_url: str + agent_id: str + agent_token: str + + def __post_init__(self) -> None: + for name in ("server_url", "agent_id", "agent_token"): + value = getattr(self, name) + 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) + + +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}") + + +def is_plaintext_remote(url: str) -> bool: + """True when credentials would cross a network unencrypted.""" + parts = urlsplit(url) + return parts.scheme == "http" and parts.hostname not in LOOPBACK_HOSTS + + +def write_config(path: Path, config: AgentConfig) -> None: + path = path.expanduser() + path.parent.mkdir(parents=True, exist_ok=True, mode=0o700) + try: + fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + 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) + f.write("\n") + + +def load_config(path: Path) -> AgentConfig: + path = path.expanduser() + try: + mode = path.stat().st_mode + text = path.read_text() + except FileNotFoundError: + raise AgentConfigError( + f"{path} not found; create it with `shadowgate agent enroll`" + ) from None + except OSError as exc: + raise AgentConfigError(f"cannot read {path}: {exc.strerror}") from None + if os.name == "posix" and mode & (stat.S_IRWXG | stat.S_IRWXO): + raise AgentConfigError( + f"{path} is accessible to other users (mode {stat.S_IMODE(mode):o}); " + f"run `chmod 600 {path}`" + ) + try: + 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") + return AgentConfig(**raw) diff --git a/src/shadowgate/cli/main.py b/src/shadowgate/cli/main.py index 67d2f47..db8a846 100644 --- a/src/shadowgate/cli/main.py +++ b/src/shadowgate/cli/main.py @@ -1,23 +1,224 @@ +"""``shadowgate`` command line. + + shadowgate server [--host H] [--port P] + shadowgate agent enroll --server URL --agent-id ID [--tags T] [--config PATH] + shadowgate agent run [--config PATH] [--poll-interval S] + shadowgate plugin list + +Exit codes: 0 success, 1 runtime failure, 2 usage or configuration error, +3 credential rejected by the server. +""" + from __future__ import annotations import argparse +import getpass +import signal +import sys +from collections.abc import Sequence +from pathlib import Path +from types import FrameType +import httpx + +from shadowgate.agent.config import ( + DEFAULT_CONFIG_PATH, + LOOPBACK_HOSTS, + AgentConfig, + AgentConfigError, + check_server_url, + is_plaintext_remote, + load_config, + write_config, +) +from shadowgate.plugins.base import Registry +from shadowgate.plugins.loader import load_builtins from shadowgate.version import __version__ +EXIT_OK, EXIT_FAILURE, EXIT_CONFIG, EXIT_AUTH = 0, 1, 2, 3 + + +def _err(message: str) -> None: + print(f"shadowgate: {message}", file=sys.stderr) + + +def _registry() -> Registry: + registry = Registry() + load_builtins(registry) # builtins only: third-party plugins wait for verification (T13) + return registry + + +# --- server --------------------------------------------------------------------------- + + +def cmd_server(args: argparse.Namespace) -> int: + import uvicorn + + from shadowgate.config import get_settings + from shadowgate.server.app import create_app + + settings = get_settings() + host = args.host or settings.host + port = args.port if args.port is not None else settings.port + 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) + return EXIT_OK + + +# --- agent ---------------------------------------------------------------------------- + + +def _read_enrollment_token() -> str: + if sys.stdin.isatty(): + return getpass.getpass("enrollment token: ").strip() + return sys.stdin.readline().strip() + + +def cmd_agent_enroll(args: argparse.Namespace) -> int: + config_path = Path(args.config).expanduser() + try: + check_server_url(args.server) + except AgentConfigError as exc: + _err(str(exc)) + return EXIT_CONFIG + 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") + token = _read_enrollment_token() + if not token: + _err("no enrollment token on stdin") + return EXIT_CONFIG + + url = args.server.rstrip("/") + "/enroll" + try: + response = httpx.post( + url, json={"agent_id": args.agent_id, "token": token, "tags": args.tags}, timeout=15 + ) + except httpx.HTTPError as exc: + _err(f"cannot reach {url}: {exc}") + return EXIT_FAILURE + if response.status_code in (401, 403): + _err("enrollment rejected: the token is invalid, expired, used, or bound to another id") + return EXIT_AUTH + if response.status_code == 409: + _err(f"agent id {args.agent_id!r} is already enrolled") + return EXIT_AUTH + if response.status_code != 200: + _err(f"enrollment failed: HTTP {response.status_code}") + return EXIT_FAILURE + try: + secret = response.json()["agent_token"] + config = AgentConfig(server_url=args.server, agent_id=args.agent_id, agent_token=secret) + write_config(config_path, config) + except (ValueError, KeyError, TypeError, AgentConfigError) as exc: + _err(f"enrolled, but the credential could not be saved: {exc}") + return EXIT_FAILURE + print(f"enrolled {args.agent_id}; credential saved to {config_path} (mode 600)") + return EXIT_OK -def main() -> int: + +def _stop_on_sigterm(signum: int, frame: FrameType | None) -> None: + raise KeyboardInterrupt + + +def cmd_agent_run(args: argparse.Namespace) -> int: + from shadowgate.agent.executor import Executor + from shadowgate.agent.poll import AgentAuthError, Poller + + try: + config = load_config(Path(args.config)) + except AgentConfigError as exc: + _err(str(exc)) + return EXIT_CONFIG + 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, + ) + previous = signal.signal(signal.SIGTERM, _stop_on_sigterm) + print(f"agent {config.agent_id} polling {config.server_url}", flush=True) + try: + poller.run() + except AgentAuthError as exc: + _err(f"stopping: {exc}; re-enroll this agent") + return EXIT_AUTH + except KeyboardInterrupt: + print(f"agent {config.agent_id} stopped", flush=True) + return EXIT_OK + finally: + signal.signal(signal.SIGTERM, previous) + return EXIT_OK # pragma: no cover - Poller.run only returns by raising + + +# --- plugin --------------------------------------------------------------------------- + + +def cmd_plugin_list(args: argparse.Namespace) -> int: + for name in _registry().names(): + print(name) + return EXIT_OK + + +# --- parser --------------------------------------------------------------------------- + + +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") - sub.add_parser("server", help="run the control server") - sub.add_parser("agent", help="run an agent") - sub.add_parser("plugin", help="plugin management") - args = parser.parse_args() - if args.cmd is None: - parser.print_help() - return 0 - print(f"shadowgate {args.cmd}: not yet wired; see src/shadowgate") - return 0 + sub = parser.add_subparsers(dest="cmd", required=True, metavar="{server,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.set_defaults(func=cmd_server) + + 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})" + + enroll = agent_sub.add_parser( + "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("--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) + enroll.set_defaults(func=cmd_agent_enroll) + + run = agent_sub.add_parser("run", help="poll the server and run jobs until stopped") + run.add_argument("--config", default=str(DEFAULT_CONFIG_PATH), help=config_help) + run.add_argument("--poll-interval", type=float, default=1.0, help="seconds between polls") + run.set_defaults(func=cmd_agent_run) + + plugin = sub.add_parser("plugin", help="inspect actions") + plugin_sub = plugin.add_subparsers(dest="plugin_cmd", required=True, metavar="{list}") + plugin_sub.add_parser("list", help="list the actions this agent can run").set_defaults( + func=cmd_plugin_list + ) + return parser + + +def main(argv: Sequence[str] | None = None) -> int: + args = build_parser().parse_args(argv) + code: int = args.func(args) + return code if __name__ == "__main__": diff --git a/tests/test_cli.py b/tests/test_cli.py new file mode 100644 index 0000000..4f78f02 --- /dev/null +++ b/tests/test_cli.py @@ -0,0 +1,305 @@ +"""T10: the ``shadowgate`` command line (server, agent enroll/run, plugin list).""" + +from __future__ import annotations + +import io +import json +import os +import signal +import socket +import stat +import subprocess +import sys +import time +from pathlib import Path +from typing import Any + +import httpx +import pytest +from conftest import TOKENS, _paths + +from shadowgate.agent.config import AgentConfig, AgentConfigError, load_config, write_config +from shadowgate.agent.poll import AgentAuthError, Poller +from shadowgate.cli import main as cli +from shadowgate.version import __version__ + +ADMIN = {"Authorization": "Bearer tok-admin"} +OPERATOR = {"Authorization": "Bearer tok-op"} + + +# --- top level ------------------------------------------------------------------------ + + +def test_version(capsys): + with pytest.raises(SystemExit) as exc: + cli.main(["--version"]) + assert exc.value.code == 0 + assert __version__ in capsys.readouterr().out + + +@pytest.mark.parametrize("argv", [[], ["agent"], ["plugin"], ["bogus"]]) +def test_missing_or_unknown_subcommand_exits_non_zero(argv): + with pytest.raises(SystemExit) as exc: + cli.main(argv) + assert exc.value.code == 2 + + +def test_plugin_list_prints_builtins(capsys): + assert cli.main(["plugin", "list"]) == 0 + assert capsys.readouterr().out.split() == [ + "disk_health", "file_fetch", "service_status", "system_info" + ] + + +# --- server --------------------------------------------------------------------------- + + +@pytest.fixture +def fake_uvicorn(monkeypatch): + import uvicorn + + calls: list[dict[str, Any]] = [] + monkeypatch.setattr(uvicorn, "run", lambda app, **kw: calls.append({"app": app, **kw})) + return calls + + +def _server_env(monkeypatch, tmp_path: Path, tokens: str | None) -> None: + for key, value in _paths(tmp_path).items(): + monkeypatch.setenv(f"SHADOWGATE_{key.upper()}", value) + if tokens is not None: + monkeypatch.setenv("SHADOWGATE_API_TOKENS_JSON", tokens) + + +def test_server_starts_with_settings(monkeypatch, tmp_path, fake_uvicorn): + _server_env(monkeypatch, tmp_path, TOKENS) + assert cli.main(["server"]) == 0 + assert len(fake_uvicorn) == 1 + assert (fake_uvicorn[0]["host"], fake_uvicorn[0]["port"]) == ("127.0.0.1", 8080) + + +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 (fake_uvicorn[0]["host"], fake_uvicorn[0]["port"]) == ("0.0.0.0", 9999) + assert "without TLS" in capsys.readouterr().err + + +def test_server_without_tokens_refuses_to_start(monkeypatch, tmp_path, fake_uvicorn, capsys): + _server_env(monkeypatch, tmp_path, None) + assert cli.main(["server"]) == 2 + assert fake_uvicorn == [] + assert "refusing to start" in capsys.readouterr().err + + +# --- agent config file ---------------------------------------------------------------- + + +def _config(server: str = "http://127.0.0.1:8080") -> AgentConfig: + return AgentConfig(server_url=server, agent_id="a1", agent_token="s3cret") + + +def test_config_written_owner_only_and_never_overwritten(tmp_path): + path = tmp_path / "sub" / "agent.json" + write_config(path, _config()) + assert stat.S_IMODE(path.stat().st_mode) == 0o600 + assert load_config(path) == _config() + with pytest.raises(AgentConfigError, match="refusing to overwrite"): + write_config(path, _config()) + + +@pytest.mark.parametrize( + ("content", "mode", "message"), + [ + (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":"ftp://h","agent_id":"a1","agent_token":"t"}', 0o600, "http"), + ('{"server_url":"http://h","agent_id":"a1","agent_token":" "}', 0o600, "agent_token"), + ], +) +def test_agent_run_rejects_bad_config(tmp_path, capsys, content, mode, message): + path = tmp_path / "agent.json" + if content is not None: + path.write_text(content) + path.chmod(mode) + assert cli.main(["agent", "run", "--config", str(path)]) == 2 + assert message in capsys.readouterr().err + + +# --- agent run ------------------------------------------------------------------------ + + +@pytest.fixture +def config_file(tmp_path) -> Path: + path = tmp_path / "agent.json" + write_config(path, _config()) + return path + + +@pytest.mark.parametrize( + ("raised", "code"), [(AgentAuthError("invalid agent credential"), 3), (KeyboardInterrupt(), 0)] +) +def test_agent_run_drives_poller(monkeypatch, config_file, raised, code): + seen: list[Poller] = [] + + def fake_run(self: Poller) -> None: + seen.append(self) + raise raised + + monkeypatch.setattr(Poller, "run", fake_run) + assert cli.main(["agent", "run", "--config", str(config_file), + "--poll-interval", "0.5"]) == code + poller = seen[0] + assert (poller.server_url, poller.agent_token, poller.poll_interval) == ( + "http://127.0.0.1:8080", "s3cret", 0.5) + assert poller.executor.agent_id == "a1" + assert poller.executor.registry.names() == [ + "disk_health", "file_fetch", "service_status", "system_info" + ] + assert signal.getsignal(signal.SIGTERM) is signal.SIG_DFL # handler restored + + +def test_agent_run_rejects_non_positive_interval(config_file): + assert cli.main(["agent", "run", "--config", str(config_file), "--poll-interval", "0"]) == 2 + + +# --- agent enroll (against an in-process server) -------------------------------------- + + +@pytest.fixture +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: + assert url == "http://127.0.0.1:8080/enroll" + sent.append(json) + return rbac_client.post("/enroll", json=json) + + monkeypatch.setattr(cli.httpx, "post", fake_post) + + def run(stdin: str, config: Path, *extra: str) -> int: + monkeypatch.setattr(sys, "stdin", io.StringIO(stdin)) + return cli.main(["agent", "enroll", "--server", "http://127.0.0.1:8080", + "--agent-id", "a1", "--config", str(config), *extra]) + + return run, sent + + +def test_enroll_saves_a_working_credential(enroll_via, rbac_client, tmp_path): + run, sent = enroll_via + invite = rbac_client.post("/tokens", headers=ADMIN).json()["token"] + path = tmp_path / "agent.json" + assert run(invite + "\n", path, "--tags", "role=web") == 0 + assert sent == [{"agent_id": "a1", "token": invite, "tags": "role=web"}] + assert stat.S_IMODE(path.stat().st_mode) == 0o600 + config = load_config(path) + poll = rbac_client.post("/agent/poll", json={}, + headers={"X-ShadowGate-Agent-Token": config.agent_token}) + assert poll.status_code == 200 + + +def test_enroll_with_bad_token_writes_nothing(enroll_via, tmp_path, capsys): + run, _ = enroll_via + path = tmp_path / "agent.json" + assert run("not-a-token\n", path) == 3 + assert not path.exists() + assert "rejected" in capsys.readouterr().err + + +def test_enroll_refuses_existing_config_before_contacting_server(enroll_via, config_file): + run, sent = enroll_via + before = config_file.read_text() + assert run("anything\n", config_file) == 2 + assert sent == [] + assert config_file.read_text() == before + + +def test_enroll_requires_token_on_stdin(enroll_via, tmp_path): + run, sent = enroll_via + assert run("", tmp_path / "agent.json") == 2 + assert sent == [] + + +def test_enroll_rejects_bad_server_url(tmp_path): + assert cli.main(["agent", "enroll", "--server", "localhost:8080", "--agent-id", "a1", + "--config", str(tmp_path / "agent.json")]) == 2 + + +# --- end to end: real server process, real agent process ------------------------------ + + +def _free_port() -> int: + with socket.socket() as s: + s.bind(("127.0.0.1", 0)) + return int(s.getsockname()[1]) + + +def _wait_for(predicate: Any, timeout: float = 20) -> None: + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + try: + if predicate(): + return + except httpx.HTTPError: + pass + time.sleep(0.1) + raise AssertionError("timed out") + + +def test_end_to_end_server_enroll_agent_job_result(tmp_path): + port = _free_port() + base = f"http://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"] + 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 + + try: + server = start("server", "--port", str(port)) + _wait_for(lambda: httpx.get(f"{base}/healthz").status_code == 200) + + invite = httpx.post(f"{base}/tokens", headers=ADMIN, json={"agent_id": "e2e"}).json() + config = tmp_path / "agent.json" + enroll = subprocess.run( + [*shadowgate, "agent", "enroll", "--server", base, "--agent-id", "e2e", + "--tags", "role=web", "--config", str(config)], + input=invite["token"] + "\n", cwd=tmp_path, env=env, text=True, + capture_output=True, timeout=30, + ) + assert enroll.returncode == 0, enroll.stderr + assert invite["token"] not in enroll.stdout + enroll.stderr + assert json.loads(config.read_text())["agent_token"] not in enroll.stdout + + agent = start("agent", "run", "--config", str(config), "--poll-interval", "0.2") + job = httpx.post(f"{base}/jobs", headers=OPERATOR, + json={"agent_id": "e2e", "action": "system_info"}).json() + _wait_for(lambda: httpx.get(f"{base}/jobs", headers=OPERATOR).json()["stats"] + == {"done": 1}) + + audit = httpx.get(f"{base}/audit?verify=true", headers=OPERATOR).json() + assert audit["verified"] is True + completed = [e for e in audit["entries"] if e["event"] == "job_completed"] + assert [(e["actor"], e["target"], e["detail"]["ok"]) for e in completed] == [ + ("e2e", job["job_id"], True) + ] + + agent.send_signal(signal.SIGTERM) + out, _ = agent.communicate(timeout=15) + assert agent.returncode == 0, out + assert "stopped" in out + server.send_signal(signal.SIGTERM) + server.communicate(timeout=15) + finally: + for proc in procs: + if proc.poll() is None: + proc.kill() + proc.communicate() diff --git a/tests/test_env_precedence.py b/tests/test_env_precedence.py index 0b6e451..f82a7a7 100644 --- a/tests/test_env_precedence.py +++ b/tests/test_env_precedence.py @@ -187,7 +187,7 @@ def test_launcher_token_precedence( server_call = calls[-1] for name, value in env_extra.items(): # inherited by the server process unchanged monkeypatch.setenv(name, value) - assert server_call["ARGS"].startswith("run uvicorn --factory shadowgate.server.app:create_app") + assert server_call["ARGS"] == "run shadowgate server --host 127.0.0.1 --port 8080" if exported_json is not None: assert server_call["JSON"] == exported_json assert _effective_tokens(monkeypatch, project, server_call) == effective