Repository navigation
fix(dashboard): require operator login and preserve provider credentials - #1
KiloMusician wants to merge 37 commits into
Conversation
Isolated mode does not add the repository root to sys.path, so the existing helper tests failed to import dashboard.security. Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Boot the actual ThreadedSwarmServer on 127.0.0.1:<ephemeral> against a throw-away tree and assert, over sockets, the access policy the helper tests only covered in isolation: every GET/POST/HEAD/OPTIONS/other-method route without credentials, Host and Origin variants, text/plain cross-origin POSTs, HTTP/1.0, absolute-form and traversal targets, Basic-auth parsing, and the /api/command token gate. Provider verification, subprocess launchers and urlopen are stubbed so no network or process is touched. TENAGENT_TEST_ROOT runs the same tests against another checkout (used to show they fail on the pre-hardening server). Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
… log files POST /api/log wrote the caller's status string straight into swarm-status.json (the page renders it) and let message/agent contain line breaks, so one request could plant markup in the status file or forge extra terminal.log entries. Reproduced over HTTP: status "<img src=x onerror=...>" was stored verbatim and `\n[10:00:00] [founder] ...` in a message produced a forged log line. Status now has to be one of IDLE/WORKING/WAITING/REVIEWING/ERROR/FAILED, the agent tag a plain identifier, message a string flattened to one line and capped at 2000 characters, progress an int-like value (clamped 0-100). Invalid input returns 400 and writes nothing. Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
… page The roster and desk templates interpolated agent.role, agent.status and agent.currentTask into innerHTML unescaped, and the model dropdown put the provider-supplied model id inside a single-quoted inline onclick argument (escapeHtml did not escape ' and the browser decodes entities before running the handler). swarm-status.json is written by agents, scripts and /api/log, and a provider's /models list is remote data. Reproduced in a real browser against the served page: a currentTask of <img src=x onerror=...> in swarm-status.json executed script in the dashboard origin, which can fetch /api/csrf-token and POST /api/command with the operator's cached Basic credentials (the command runner was stubbed in that run). Escape the fields, pass model ids via a data attribute, and make escapeHtml cover single quotes. Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
…eal target The static guard was a deny-list evaluated on a different string than the one the file system used. Reproduced over HTTP on Windows: /dashboard/serve.py#x (http.server drops the fragment, the .py check saw ".../serve.py#x"), /dashboard/serve.py. and /dashboard/serve.py::$DATA (Win32 strips trailing dots and resolves the default stream) all returned the server source; /specs/swarm-status.json.tmp was served through a prefix match; a directory junction under assets/ was followed out of the tree; /dashboard/nul opened the NUL device; /assets/ produced a directory listing. valid_static_path now rejects ':' , trailing dots/spaces, device names, hidden segments and any extension outside an allow-list; the fragment is stripped before checking; only the two state files are served from specs/; the resolved real path must stay inside dashboard/ or assets/; directory listings are disabled. The dashboard frontend only requests /dashboard/, favicons and the two state files, all still served. Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Every POST handler did int(Content-Length) and rfile.read(n).decode() outside any validation. Reproduced over HTTP: Content-Length "abc" or a non-UTF-8 body raised in the handler (traceback on stderr, connection dropped, no response); Content-Length -1 and a large declared length made the handler thread block in read() until the client went away; there was no size cap, no socket timeout and no handling of Transfer-Encoding: chunked (body silently treated as empty). Add one _read_json_body(): 1 MiB cap (413), strict digit-only length (400), chunked refused (411), short read (400), non-UTF-8 / invalid JSON / non-object (400) with generic messages instead of exception text, and a 30 s socket timeout. /api/command also rejects a non-string command. Also reproduced on Windows: when the server answers 401/403 and closes before the client has sent the body (http.client and some browsers send headers first), the unread bytes trigger a TCP reset and the client sees WinError 10053 instead of the status line. do_POST now drains up to 16 MiB of an unread body after replying. Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Every status/config update went through one shared "<file>.tmp" with no lock. Reproduced on Windows 11 / Python 3.13: 8 threads calling set_agent_status_direct 25 times each left swarm-status.json as invalid JSON in 5 of 5 runs (two writers interleaved in the same temp file); a reader holding the file open (the static handler does while streaming it) made os.replace raise PermissionError, which safe_write_json swallowed, silently dropping the update; and the local-provider probe wrote its stale snapshot of swarm-config.json back after the probe's socket I/O, reverting a configuration the operator saved in the meantime. Add dashboard/statefile.py: unique same-directory temp file, fsync, os.replace retried ~1.5 s on PermissionError, and update_json_file() which does the read-modify-write under one process-wide lock. serve.py and swarm_pipeline.py (which runs inside the same process) use it; the probe now merges only the status fields into a fresh read. POST /api/config writes atomically and answers 500 if the write fails. The duplicate safe_write_json definition is removed. Not covered: stream.py and agents that edit the files from other processes still race with the server (atomic replace only keeps readers safe). Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
… config save
POST /api/config replaced the stored config wholesale and only restored a key
when the posted value was a mask AND the provider id matched. Reproduced over
HTTP: posting back the redacted GET /api/config view (no "key" field) wiped the
stored key (status "empty") and persisted the server-computed has_key,
key_masked and cli fields; a masked key sent under a renamed provider was saved
as the literal placeholder "sk-t...mnop" and then "verified"; two entries with
the same provider id both received the last stored key. Malformed bodies
surfaced Python exception text ("'str' object has no attribute 'get'").
prepare_config_payload() now defines the contract: key absent/null keeps the
stored key (key_masked disambiguates duplicates), "" clears it, a mask is
replaced by the stored key it was derived from or refused with a clear 400, and
anything else is a new key. Server-owned fields are stripped, every shape is
validated before anything is written, errors are generic, and /api/models
applies the same rule so a placeholder is never sent to a provider.
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
…s, hide short keys public_config() removed fields only if their normalised name was in a fixed list. Reproduced over HTTP: with secret_key, openai_api_key, x-api-key and auth_token in swarm-config.json, GET /api/config and the POST response returned their values; a baseUrl such as http://user:pw@host/v1?token=... was returned whole; and the "masked" form of a 9-12 character key exposed 8 of its characters. A field is now treated as a credential when its name contains key, secret, token, password, passphrase, credential, authorization, bearer or cookie (plural "...tokens" counts such as max_tokens stay visible). URL strings lose their userinfo and secret-named query values, and a baseUrl echoed back in that redacted form is mapped to the stored URL on save so the round trip does not destroy it. Keys shorter than 24 characters are shown as "***"; longer ones keep the first and last four. Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
…ntries terminal.log is served back to the browser and kept on disk, but everything was written to it verbatim. Reproduced over HTTP: a command, an /api/log message or a helper's output containing "?key=AIza...", "Authorization: Bearer sk-...", "token=..." or the dashboard password was stored and served unchanged, and /api/command wrote the operator's text straight after "[founder] > ", so embedded newlines produced forged "[hh:mm:ss] [01_pm] ..." entries (the log is parsed line by line by the page). Add redact_text() (exact dashboard secrets, Authorization/Bearer values, credential-named name=value pairs and common provider key shapes) and run every line written by append_to_terminal_log, the founder echo and /api/log through it after flattening to a single line. Not a substitute for not printing secrets: it is a shape heuristic, documented as such. Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
…kens in constant time
/api/command found the CSRF token with `'tenagent_token=' in part` and
`part.split('tenagent_token=')[1]`, so a cookie named xtenagent_token or a value
that merely contained the text satisfied the lookup (reproduced: a request with
"Cookie: xtenagent_token=<token>" was accepted and ran the command), and the
token was compared with `!=`.
Parse the Cookie header with http.cookies.SimpleCookie and look up the one
cookie by name; compare with hmac.compare_digest on bytes (non-ASCII values are
simply a mismatch). The token is only a second factor behind Basic credentials
and the Origin check, so this is hardening rather than a standalone bypass.
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
…f responses No response carried any framing or content-type protection, so a hostile page could frame http://127.0.0.1:<port>/dashboard/ (the browser sends the cached Basic credentials to it) and clickjack the command box, or embed/sniff the JSON endpoints. Reproduced: none of X-Frame-Options, frame-ancestors, nosniff, Referrer-Policy or CORP were present on any of 12 response kinds (page, JSON, static, redirect, 401/403/404/405/501, 400). Add X-Frame-Options: DENY, CSP frame-ancestors 'none', X-Content-Type-Options: nosniff, Referrer-Policy: no-referrer and Cross-Origin-Resource-Policy: same-origin from end_headers so every response, including http.server's own error pages, gets them. A full script-src CSP is deliberately not added: the page relies on inline scripts and handlers. Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
The PowerShell runner and the agy launcher called Popen without an env, so TENAGENT_DASHBOARD_PASSWORD (when the operator pins it) was inherited by every command the dashboard runs, including whatever an AI CLI executes on a prompt's behalf, and could be printed into terminal.log. Reproduced by capturing the Popen call: env was None. Pass an explicit environment without that variable. Also pinned by a test: both launchers already use argument lists (never shell=True), and a prompt with shell metacharacters stays a single argv element. Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
verify_ai_provider_key() and call_custom_ai_provider() built request URLs from the stored baseUrl and passed them to urllib.request.urlopen, which also opens file:// and ftp:// URLs. Reproduced with a recording urlopen: a base URL of file:///C:/Windows/win.ini or ftp://127.0.0.1/... was fetched (and, for chat calls, the bearer key was attached to the request). Operator-supplied data only, but it also turned the key check into a local-file existence oracle. Reject anything that is not an absolute http(s) URL with a host, with a clear status in the dashboard instead of a generic connection failure. Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
serve.py only runs on Windows, so the real-HTTP tests need a windows-latest job; the Linux job runs everything else (they skip themselves there). Adds dashboard/statefile.py to the compile check. Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
…binds The server listens on 127.0.0.1 only but printed and opened http://localhost:<port>/. Clients resolve localhost to ::1 first, so another process of the same user that bound [::1]:<port> would receive the connection and the Basic password. The URL is now http://127.0.0.1:<port>/dashboard/ (also in the README), and the free-port probe treats a port already held on [::1] as taken. Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
…bber Prompt text reached terminal.log or swarm-status.json unscrubbed through the swarm pipeline, the council, stream.py, the agent-launch status line (which cut the prompt to 40 characters before any pattern could match), file-event messages, and the watcher's echo of status text. scrub_log_text now lives in dashboard/security.py (serve.py keeps its name), is shared by all writers, and also hides the dashboard password, session token and TENAGENT_DASHBOARD_PASSWORD. Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
…t operator passwords Wrong Authorization headers now wait AUTH_FAILURE_DELAY (0.5 s) in their own request thread before the 401; a first request with no credentials, and correct credentials, are not delayed, and no lock is held, so legitimate requests are unaffected. Starting with TENAGENT_DASHBOARD_PASSWORD set to fewer than 12 characters prints a warning (it still starts). Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
…ec-Fetch-Site Only mutations were checked against Sec-Fetch-Site, so any page could make the browser GET /api/csrf-token or /api/config with the operator's cached credentials (the response stayed unreadable, but the request still ran). GET and HEAD of /api/* now require Sec-Fetch-Site to be absent, none or same-origin. The HTML page, static files and the state files are unaffected, so links and address-bar navigation keep working. Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
…ase URL A masked or omitted key was replaced by the stored key regardless of the baseUrl in the same request, so a save naming another URL made the server send the stored credential there when it verified the key. The stored key is now restored only if the posted baseUrl equals the stored one (the redacted form the UI echoes back counts as equal; an absent baseUrl counts as unchanged); otherwise the request is refused with 400 asking for the key again. /api/models applies the same rule. Also pins that GET /api/config leaves the file untouched when nothing changed (it already did). Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
…nt-Security-Policy The policy only carried frame-ancestors. It now also has base-uri 'none', object-src 'none' and form-action 'self' (the page uses none of <base>, <object>, <embed> or <form>). script-src is deliberately absent because the page relies on inline scripts and onclick= handlers; this is recorded in a comment next to SECURITY_HEADERS and in the README. Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
…d never overwrite it A swarm-config.json that parses but is not a usable configuration (a list, providers that is not a list, non-object providers) or does not parse at all made GET /api/config swallow the error and return no providers; a save from the UI then replaced the file and every key in it. GET now answers 500 with config_error and a clear message, and POST answers 409 and writes nothing, for as long as the file is unusable. The first time a given content is seen it is copied aside as swarm-config.json.<sha256-prefix>.corrupt (ignored by git, never served). Empty or whitespace-only files hold nothing and behave like a missing file. Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Text that starts with a known command name, "$ ", "> " or "./", or contains | && || ; > or <, is run as a PowerShell command even when meant as a prompt. Behaviour is unchanged; the README now says so in the operator-access section. Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
|
Thank you for merging #2 and for the clear notes. I agree with all three, and I'll rework this PR rather than push on with it as it stands:
I'll also rebase the swarm-pipeline work (it overlaps your new quality gates) and send it as smaller changes rather than one large one. If you'd rather I stop, or take a different order, tell me and I'll follow that. |
|
The split is up, rebased on current
What is still left from this PR, rebased and tested locally but not sent so I don't flood you: the remaining hardening as independent pieces (Host/Origin and cross-site checks, static-file allow-list, request-body limits, provider-key handling on save, log scrubbing, response headers, XSS escaping, unreadable-config handling, loopback bind address) and HTTP Basic auth as an opt-in flag (off by default, so |
Summary
The local dashboard (
dashboard/serve.py) can start PowerShell and an AI CLI, and it stores provider API keys. This draft puts a login, origin checks and credential handling around that, and adds real-HTTP tests that boot the actual server. It is a draft because it has only been exercised on Windows 11 / Python 3.13 (plus a Linux run of the tests that are not Windows-only), and because parts of it are design decisions for you (listed at the end).Nothing here makes the dashboard safe to expose beyond the machine: it still listens on
127.0.0.1only, and/api/commandstill runs PowerShell for whoever holds the operator password.Problems found on
main(d9e2c27) and what the PR doesAll of these were reproduced against the running server (or, for XSS, in a real browser) with fake secrets and a stubbed command runner.
mainTENAGENT_DASHBOARD_PASSWORDis set (a warning if that is shorter than 12 characters); wrong credentials are delayed 0.5 sHost, permissive CORS127.0.0.1:<port>/localhost:<port>; foreign,nulland other-portOriginrefused;/api/*requests the browser markscross-siteorsame-siterefused (reads too); no CORS headerslocalhost, the server binds127.0.0.1127.0.0.1(another process could otherwise bind[::1]:<port>and receivelocalhostconnections)/api/logstatus or a provider's model id could run script in the dashboard origin/dashboard/serve.py#x,serve.py.,serve.py::$DATAreturned the server source;.tmpstate files,assets/listings and a junction out ofassets/were servedContent-Length: abcor non-UTF-8 dropped the connection with a traceback; no size cap, no timeout; chunked bodies read as empty; on Windows a 401 sent before the body arrived turned into a TCP resetswarm-status.jsonas invalid JSON in 5 of 5 runs; an open reader madeos.replacefail silentlyterminal.logstored keys, Bearer values and passwords verbatim, and newlines forged entriesxtenagent_token=<token>ran a command);!=compareagychildren inherited the dashboard password; the AI CLI was launched with--dangerously-skip-permissionsfile://andftp://base URLs were fetchedX-Frame-Options,frame-ancestors 'none',nosniff, CORP,no-store, CSPbase-uri/object-src/form-action(
setup_project.pydeleting an existing project's folders is a separate bug with its own PR.)Tests
tests/http_harness.pyboots the realserve.pyon127.0.0.1:0in a temp tree with the command runners andurlopenstubbed;tests/test_dashboard_http_integration.pyruns a route x method matrix, cross-origin and Host cases, body-limit cases, static-path cases, config round-trips and log scrubbing over raw sockets. Standard library only. Each fix's tests were run against the commit before it and fail there; the first 38 matrix tests run againstmain'sserve.pygive 97 failures.On head
d7f9be9(python -I -m unittest discover -s tests):ci.ymlpins), no networkserve.pyexits at import elsewhere)/api/*call 200, hostile payloads inert, cross-origin reads refusedBrowser check, head
d7f9be9, headless Edge 155 driven over DevTools against a copy of the tree, fake password and keys, command runner never invoked: the dashboard rendered 10 agent cards with no script errors and no CSP violations; every same-origin/api/*request returned 200; a fake provider key round-tripped through the config modal without appearing in any of 137 response bodies; hostile payloads in agent fields (<img onerror>,<script>,<svg onload>,<iframe srcdoc>) rendered as text; cross-site and same-site requests (fetch,<img>, POST) from a second localhost origin got 403 and were unreadable; the cross-site iframe was blocked. One console error on a fresh tree:/specs/terminal.logreturns 404 until the first log line exists.Not verified / decisions for you
/api/commandruns PowerShell for the authenticated operator. Text containing|,&&,||,;,>or<is treated as a shell command (the README now says so); I did not change that heuristic. Prose pasted into the box can therefore run as code; an explicit prefix or a confirmation step would be safer, your call.name=value, Bearer values, the dashboard's own secrets); the auth delay is per request, not a lockout;/specs/*.jsonandterminal.logcan still be requested cross-site (the response is unreadable to the other site). The Basic login has no throttle across parallel connections.baseUrlthe authenticated operator configures (redirects forwardAuthorization).stream.pyand any other process writing the status files can still lose updates (atomic replace only protects readers).ci.ymlhas not run on GitHub; Python 3.11 was only run in a Linux container.dashboard/serve.py,swarm_pipeline.pyand the README with the swarm PR from the same account; I merged the two locally, resolved the conflicts onto one shared atomic writer and both suites pass together. I'll rebase whichever is second.Prepared with AI coding assistants (OpenAI GPT and Anthropic Claude) on behalf of @KiloMusician, who submits it as a draft. Commands and counts above were run on the head named. MIT licence and notices untouched.