Skip to content

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

ShadowGate

CI Release License: MIT Python 3.12 | 3.13

ShadowGate is a control server for running audited jobs on Linux hosts you own and administer. Operators enroll agents, queue actions or runbooks (dependency graphs of actions) against them, and review the results on an audit log and a read-only dashboard.

This is an agent-management tool for hosts you own and administer. There is no covert-channel, exfiltration, or evasion code anywhere in the tree.

Status: pre-release (0.1.0).

  • 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 before using it beyond a single-host test setup.

What it does

Area What exists today
Operator API FastAPI server. Operator routes are protected by bearer tokens with three roles: viewer < operator < admin. The server refuses to start without a valid token configuration, unless it is explicitly in insecure dev mode.
Agent identity An admin mints a one-time enrollment token, which expires after 30 minutes and can optionally be bound to one agent id. The agent exchanges it once for a per-agent token. The server stores only the SHA-256 of that token. Agents send it in the X-ShadowGate-Agent-Token header.
Job ownership An agent can claim and complete only jobs assigned to its own id. A retried identical result is acknowledged as duplicate; a conflicting one is rejected.
Job queue SQLite (WAL mode). Each job is claimed with a single UPDATE … RETURNING.
Runbooks Sets of steps with dependencies, registered under a name (unnamed if omitted). Validation rejects cycles. Steps fan out to agents by tag, with a per-run concurrency cap and compensating steps on failure.
Audit log An append-only JSONL file. Each entry includes the SHA-256 of the previous one, 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).

Present in the code but not used at runtime yet:

  • mTLS certificate helpers (crypto/mtls.py).
  • The ed25519 plugin-manifest gate for third-party plugins (plugins/gate.py).

Architecture

operator (curl / browser)                         agent (`shadowgate agent run`)
   │ Authorization: Bearer <token>                   │ X-ShadowGate-Agent-Token
   │ 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
   │     ├── SqlQueue (server/queue.py)    qjobs: atomic claim, owner-checked completion
   │     └── RunEngine (server/runs.py)    runbooks, runs, steps, compensation
   ├── orchestrator.py                runbook parsing, validation, tag matching
   ├── AuditLog (server/audit.py)     hash-chained JSONL file
   └── Jinja2 templates (web/)        /ui pages

agent/poll.py  Poller: poll → Executor (agent/executor.py) → builtin actions → post result

See docs/architecture.md and docs/threat-model.md.

Path Contents
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/ 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
examples/runbooks/ sample runbook (YAML)
tests/ pytest suite

Technologies

  • Python ≥ 3.12. Developed and tested on 3.13; CI runs 3.12.
  • FastAPI, Uvicorn, Pydantic v2 and pydantic-settings, Jinja2.
  • Standard-library sqlite3, which must link SQLite ≥ 3.35 for RETURNING.
  • cryptography (ed25519, X.509), PyYAML, httpx.
  • Tooling: uv, hatchling, pytest, ruff, mypy (strict).
  • All versions are pinned in uv.lock.

Prerequisites

  • Linux. service_status needs systemd.
  • uv, which installs a suitable Python if needed.
  • curl and jq for the examples below.

Installation

git clone https://github.com/5aranx/ShadowGate.git
cd ShadowGate
uv sync --frozen --extra dev     # creates .venv from uv.lock

Configuration

Settings are read from environment variables with the SHADOWGATE_ prefix, or from a .env file in the working directory. Environment variables take precedence over .env. A .env file may 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
SHADOWGATE_API_TOKENS_JSON (empty) Required unless insecure dev mode is on. JSON object mapping token → role, e.g. {"<admin-token>":"admin","<viewer-token>":"viewer"}. Roles: viewer, operator, admin. Tokens must be non-empty and contain no whitespace or :. The legacy name SHADOWGATE_API_TOKENS is also accepted.
SHADOWGATE_INSECURE_DEV false true allows an empty token map. Operator routes are then unauthenticated, and /docs and /openapi.json are enabled. Agent routes still require agent tokens. Local development only.
SHADOWGATE_DB_PATH shadowgate.db SQLite database. Relative to the working directory.
SHADOWGATE_AUDIT_LOG_PATH .shadowgate/audit.log Audit log file. Relative to the working directory.
SHADOWGATE_DATA_DIR .shadowgate Directory created at startup. It does not relocate the database or audit log.
SHADOWGATE_RATE_LIMIT_PER_MINUTE 60 Per-source-IP, per-endpoint limit on POST /tokens and POST /enroll. Must be ≥ 1: 0 or a negative value rejects every request. Behind a reverse proxy, all clients share the proxy's IP.
SHADOWGATE_HOST, SHADOWGATE_PORT 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_ORG_KEY_PATH, SHADOWGATE_CA_KEY_PATH and SHADOWGATE_CA_CERT_PATH exist in config.py but are not used.

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

Running

One-command demo

bash 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

./run.sh

run.sh does the following:

  1. Syncs dependencies.
  2. Picks the operator tokens, highest precedence first:
    1. SHADOWGATE_API_TOKENS_JSON or SHADOWGATE_API_TOKENS already set in your shell (names are case-insensitive). An empty value is respected, and the server then refuses to start.
    2. Either name defined in ./.env. The server reads it itself; run.sh doesn't override it.
    3. Otherwise, a built-in development map: admin-token, op-token, view-token. These are public example values; never use them anywhere reachable by others.
  3. Starts the server on 127.0.0.1:8080 and prints which token source is in use.

./run.sh --check syncs dependencies and runs ruff, mypy and pytest. It exports no tokens.

Directly

export SHADOWGATE_API_TOKENS_JSON='{"<admin-token>":"admin","<operator-token>":"operator","<viewer-token>":"viewer"}'
uv run shadowgate server            # --host/--port, default 127.0.0.1:8080

Without operator tokens the server refuses to start (exit code 2).

Over a network (HTTPS)

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))'.

Walkthrough

These examples use the run.sh development tokens:

# 1. admin mints a one-time enrollment token (optionally bound: -d '{"agent_id":"a1"}')
TOKEN=$(curl -s -X POST localhost:8080/tokens -H 'Authorization: Bearer admin-token' | jq -r .token)

# 2. the agent enrolls with it and receives its own token (returned once, stored hashed)
AGENT_TOKEN=$(curl -s -X POST localhost:8080/enroll -H 'Content-Type: application/json' \
  -d "{\"agent_id\":\"a1\",\"token\":\"$TOKEN\",\"tags\":\"linux\"}" | jq -r .agent_token)

# 3. an operator queues a job for that agent
JOB=$(curl -s -X POST localhost:8080/jobs -H 'Authorization: Bearer op-token' \
  -H 'Content-Type: application/json' -d '{"agent_id":"a1","action":"system_info"}' | jq -r .job_id)

# 4. the agent claims it and reports a result
curl -s -X POST localhost:8080/agent/poll -H "X-ShadowGate-Agent-Token: $AGENT_TOKEN"
curl -s -X POST localhost:8080/agent/result -H "X-ShadowGate-Agent-Token: $AGENT_TOKEN" \
  -H 'Content-Type: application/json' -d "{\"job_id\":\"$JOB\",\"ok\":true}"

# 5. a viewer checks state and the audit chain
curl -s localhost:8080/jobs -H 'Authorization: Bearer view-token'
curl -s 'localhost:8080/audit?verify=true' -H 'Authorization: Bearer view-token' | jq .verified

Dashboard: open http://127.0.0.1:8080/ui. The browser prompts for HTTP Basic credentials: any username, and a viewer, operator or admin token as the password.

Runbooks. POST /runbooks takes JSON (admin). To submit the YAML example:

uv run python -c 'import json,sys,yaml; print(json.dumps(yaml.safe_load(open(sys.argv[1]))))' \
  examples/runbooks/disk-health-audit.yaml |
  curl -s -X POST localhost:8080/runbooks -H 'Authorization: Bearer admin-token' \
       -H 'Content-Type: application/json' -d @-
curl -s -X POST localhost:8080/runs -H 'Authorization: Bearer op-token' \
     -H 'Content-Type: application/json' -d '{"runbook":"disk-health-audit"}'

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):

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

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
GET /healthz, GET / (redirects to /ui) public
POST /enroll one-time enrollment token in the body
POST /agent/poll, POST /agent/result X-ShadowGate-Agent-Token
GET /agents, /jobs, /runs/{id}, /audit, /ui, /ui/agents, /ui/jobs, /ui/runs viewer
POST /jobs, POST /runs operator
POST /tokens, POST /runbooks admin

Operator credentials can be sent as Authorization: Bearer <token> or as HTTP Basic with the token as the password.

Testing

uv run --frozen pytest -q             # full suite
uv run --frozen ruff check src tests
uv run --frozen mypy                  # strict
./run.sh --check                      # uv sync --extra dev (not --frozen), then the same checks

CI (.github/workflows/ci.yml) runs ruff, mypy and pytest on every push and pull request.

The suite is isolated from your configuration. Each test runs in its own temporary directory with all SHADOWGATE_* variables removed, so shell exports or a .env file don't change the results. tests/test_env_precedence.py pins the token precedence described under Configuration and Running, including the behavior of run.sh (exercised with a stub uv, so nothing is installed or started).

Known limitations

These are the user-visible issues found during verification. Fixes are planned but not yet implemented.

Not suitable for networked use yet

  • 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.
  • Audit vs. database: each request is one transaction, and its audit entries are written just before the commit. If the audit write fails, nothing is committed. In the rare case that the database commit itself fails after that, the log holds entries for a change that did not happen.
  • Audit log: the anchor sits next to the log, so someone who can rewrite both files consistently (or delete the anchor and restart the server) is not detected. Copy verification output or the anchor off the host if that matters.
  • Transport: HTTPS is built in, but agents authenticate with a bearer token, not a client certificate (no mTLS). There is no certificate rotation or revocation; tls init server certificates last 397 days. Operators' own clients (curl, browser) must trust the CA.
  • Agent credentials: they cannot be rotated or revoked, and agent tags cannot be changed after enrollment, except by editing the database.
  • Enrollment edge cases:
    • If SQLite is busy, POST /enroll can return 500 after about 5 s. The enrollment token is not consumed, and a retry succeeds.
  • First start after upgrading: with more than one Uvicorn worker, the first start against a database created by an older version can fail in some workers with duplicate column name: secret_hash. Restart and it succeeds.

Functional gaps

  • 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.
    • The Poller treats any 4xx other than 401/403 (including 408 and 429) as final and drops the result.
  • Runbook engine defects:
    • A dependent step can start before all of its dependency's targets finish.
    • A failing compensation step re-queues itself repeatedly.
    • A step that matches no agents leaves its run running forever.
    • Malformed runbooks return HTTP 500.
  • Not used: third-party plugin loading and the signature gate.

Operational

  • Config: see the unused settings above.
  • Logging: the application logs nothing of its own. Uvicorn still prints request and error logs to the terminal.

License

MIT. See LICENSE.


Engineered with precision for secure, scalable systems.
Made by Saransh Singh

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages