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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 24 additions & 15 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down Expand Up @@ -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) |
Expand Down Expand Up @@ -136,9 +137,12 @@ dev mode makes startup fail with an error, before any files are created.

```bash
export SHADOWGATE_API_TOKENS_JSON='{"<admin-token>":"admin","<operator-token>":"operator","<viewer-token>":"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
Expand Down Expand Up @@ -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="<agent_token from /enroll>").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 |
Expand Down Expand Up @@ -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`.
Expand Down
4 changes: 2 additions & 2 deletions docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 | +-------------------+
Expand Down
30 changes: 27 additions & 3 deletions docs/tracker.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down Expand Up @@ -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 |

Expand All @@ -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)

Expand Down Expand Up @@ -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 |
Expand All @@ -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. |
2 changes: 1 addition & 1 deletion run.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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
85 changes: 85 additions & 0 deletions src/shadowgate/agent/config.py
Original file line number Diff line number Diff line change
@@ -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)
Loading
Loading