Repository navigation
feat(email): harden the sidecar local REST API with per-session caller authentication (#1706) - #1980
Conversation
…esult handling) Adopts the token-reduction and data-out-of-context outcomes from Anthropic's "code execution with MCP" writeup using GAIA's existing embedding-based tool loader and tool-wrapper layers — not the code-execution mechanism, which is a poor fit for local 4B-35B models and a large local-machine attack surface. Scopes three workstreams: WS1 routes MCP tools through the dynamic loader (progressive disclosure, with an MCP-only gating mode so static-tool recall is preserved), WS2 keeps large tool results out of context via a session-scoped artifact store + handle resolution in _execute_tool, WS3 (optional) adds PII pass-through. Non-goal: model-authored code execution / sandbox.
…r authentication (#1706) The email sidecar binds 127.0.0.1 and exposes draft/send against the user's connected mailbox, but its REST API had no caller authentication — any other local process, or a web page in the user's browser via DNS-rebinding, could reach draft/send. The existing draft→send confirmation token is a payload-integrity check, not caller auth. Adds three controls, wired ONLY onto the frozen sidecar app so the product server and OpenAPI export mount the same router unchanged: - Per-session bearer token: the spawning parent (npm lifecycle, Python EmailSidecarManager) mints a cryptographically-random token and hands it to the sidecar over the private GAIA_EMAIL_SIDECAR_TOKEN env channel; every /v1/email/* request must send Authorization: Bearer <token> or it is 401. - Host allowlist: a non-loopback Host is 400 (DNS-rebinding). - Origin rejection: a non-loopback browser Origin is 403 (drive-by page); no permissive CORS. The token is threaded end-to-end through the npm client (EmailClient.authToken, bound by spawnSidecar) and the Agent UI path (EmailSidecarProxy bearer header). Liveness/version probes and the HTML pages stay exempt so the readiness handshake works pre-token. The confirmation-token gate is untouched. Docs synced across spec_html + specification.html, npm README/SPEC/CHANGELOG/SKILL, and the packaging README.
Verdict: Approve with suggestionsThis closes a real hole: the email sidecar could send mail as the user with no caller check, and now every 🔒 SECURITY — one gap worth a decision before merge (@kovtcharov-amd): the token gate is applied to the email router but not to the connector routes ( Two smaller things: the new 🔍 Technical details🟡 Connector routes are not token-gated (
|
… + contract spec (#1706) Extends the #1706 doc sync beyond the hub package to the site docs and the architecture asset, so every surface that describes the email REST API states the per-session bearer-token requirement and the loopback Host/Origin allowlist: - docs/guides/email-integration.mdx — new Authentication section (npm token is auto-bound to sidecar.client; construct-your-own clients pass authToken; the GAIA backend proxies to an authenticated sidecar so 4200 calls need no token; hand-run dev sidecar is open without the env var). Sidecar tab gets a note. - docs/guides/email.mdx — the /v1/email/* REST-surface bullet now states the token + Host/Origin controls and links to the integration guide. - docs/spec/email-contract.mdx — note that transport auth is separate from the frozen schema and intentionally not in the OpenAPI document. - hub/agents/npm/agent-email/assets/architecture.html — renderer snippet passes authToken; sidecar node shows the bearer/Host-Origin control.
…tions (#1706) Re-rendered from the updated architecture.html so the shipped diagram (the image in the npm README) matches its source: the sidecar node now shows the 🔒 bearer token / loopback Host-Origin control, and the renderer snippet passes authToken.
…1706) The sidecar app now enforces a caller-auth Host allowlist, which rejects TestClient's default `testserver` Host with 400. Three existing tests that build the packaging server app (connector mount + openapi contract + init route via packaging/server.py) hit that guard; point their TestClients at http://127.0.0.1 so the loopback Host passes. No production behavior change.
…aller-auth-1706 # Conflicts: # hub/agents/python/email/packaging/server.py # hub/agents/python/email/specification.html
…iddleware, env hardening (#1706) - Token-gate the connector routes (/v1/email/connectors/* — configure / complete-OAuth / disconnect) and the stateful agent surface (/v1/email/agent/*), not just the email router. Both can act on the mailbox, so an unauthenticated local caller now gets 401 (closes the asymmetry the review flagged). Wired in packaging/server.py in the merge with origin/main. - Rewrite HostOriginMiddleware as pure ASGI instead of BaseHTTPMiddleware, so it inspects two headers and passes (scope, receive, send) through untouched — BaseHTTPMiddleware can buffer/reorder streaming responses, which would break the line-by-line StreamingResponse from POST /v1/email/init. - Harden manager env merge: popen_kwargs.pop("env", None) or {} so an explicit env=None never raises TypeError. - Tests: connector + agent routers 401 without the token; POST /v1/email/init still streams its 503 body intact through the middleware + token gate.
|
Thanks for the thorough review — merged latest 🔒 Connector routes now gated (the security asymmetry). The token dependency is applied to every mailbox-touching router, not just the email router: connector lifecycle ( 🟡 Streaming — middleware rewritten as pure ASGI. 🟢 Unrelated planning doc — 🟢 All email/auth suites + the npm suite (65) + tsc are green locally. |
The with-token connector call hit the live connector store (no store on CI -> TestClient re-raises). Gate presence is proven by the 401-without-token path on both routers; the with-token pass-through is already covered by /draft.
… (contract 2.4) (amd#2061) Closes amd#2016. Part of the Agent UI v2 epic (amd#2014) — the keystone feature. Today the email sidecar is a bag of fixed-function endpoints; the reasoning loop lives in each front-door. This makes the sidecar a complete agent product: NL request in, the agent reasons and chains tools into a multi-step workflow, typed SSE events out. Every front-door (UI, CLI, `gaia api`) then relays to this one loop instead of reimplementing it — the agent behaves identically no matter how you reach it. Adds `POST /v1/email/query` (agent loop with an SSE handler emitting the canonical vocabulary from the /query contract spec) + `POST /v1/email/query/{run_id}/cancel` (stops tool execution between steps), per-`run_id` state namespacing, and an additive contract bump 2.3 → 2.4 with all doc surfaces updated together (openapi, specification.html, SPEC, SKILL, README, CHANGELOG). Auth rides the existing per-session bearer (amd#1980). Confirmation is stubbed per epic decision D1 (unsigned): a destructive step ends the stream with a `final` refusal pointing at the fixed-function route — no stateful resume yet. Depends on the /query SSE contract (amd#2057 / amd#2015); the event vocabulary here must match it. **Test plan** - [ ] `curl -N` a dev-mode sidecar: triage query streams `status`→`tool_call`→`tool_result`→…→`final`. - [ ] Cancel stops execution between steps. - [ ] `python -m pytest tests/ -k email -q` + the agent package tests pass. - [ ] **Eval (LLM-affecting, CLAUDE.md):** run the email agent eval vs. the committed baseline and confirm no regression. If it was not run in the worktree (no reachable backend), a reviewer must run it before merge — flag this explicitly. --------- Co-authored-by: Ovtcharov <[email protected]>
… refresh (amd#2058) Closes amd#2017. Part of the Agent UI v2 epic (amd#2014), Phase 0. Four sibling plan docs describe the pre-v2 (localhost-trust, UI-owned supervisor, sidecar-reads-grants) model as if it were current — a reader following the wrong one builds the wrong thing. Separately, a week of merged email work made several of the v2 breakdown doc's "verified" facts stale (wrong contract version, closed issues, new in-sidecar clocks). This aligns the docs with head of main so implementers of the later batches aren't misled. Adds the⚠️ superseded/reconcile banner to `security-model.mdx`, `email-sidecar-agent-ui-implementation.md`, `connectors.mdx`, and `autonomy-engine.mdx`; fixes the `agent-ui.mdx` sentence that wrongly put RAG/memory in sidecars; and refreshes `agent-ui-v2-implementation-breakdown.md` (contract is 2.3 not 2.1, amd#1706 closed by amd#1980, two merged in-sidecar clocks amd#1918/amd#1919 + durable stores widen V2-15, hub paths updated to agent-first). **Test plan** - [ ] All four banners render and point at v2 §0. - [ ] `agent-ui.mdx` no longer claims RAG/memory live in sidecars. - [ ] Breakdown-doc facts match head of main. --------- Co-authored-by: Ovtcharov <[email protected]>
…md#2202) ## Why this matters Before this, nothing exercised the email agent through the v2 **sidecar/daemon** path — every eval ran the loop in-process — and no test guarded the daemon↔sidecar contracts *as a set*. The frozen §0.2 event vocabulary, the relay's crash/cancel terminal, and the auth leg were each pinned only by their own issue's tests, so a drift *between* seams (e.g. a front-door and the sidecar disagreeing on what "done" looks like) could slip through green. After: an **eval harness** drives `POST /v1/<agent>/query` over REST and asserts the canonical event **sequence** (not a brittle final string) against baselines committed in the agent package — serial by construction per the CLAUDE.md eval rule. Plus a single **distributed-seams suite** that guards the contracts across seams and self-skips the ones not yet merged, with each skip keyed on the source's real presence so it flips to a live assertion the moment its issue lands. The harness (`src/gaia/eval/sidecar_harness.py`) keeps its pure core (SSE parse, ordered-subsequence match tolerant of LLM-variable event counts, a cross-process `SerialEvalLock`) split from a thin live driver, mirroring `behavior_harness`. A missing/unreachable backend raises loudly — never a silent green pass. ### Seams: covered vs. skipped-pending-merge | Seam | Issue | State | |------|-------|-------| | Relay ↔ translator ↔ harness vocabulary coherence | V2-7 amd#2150 | ✅ covered | | Relay synthetic crash terminal parses as canonical `error` | V2-7 amd#2150 | ✅ covered | | Daemon→sidecar bearer via private env, never argv | amd#1980 | ✅ covered | | Secret-file (fd/0600) launch-secret delivery | V2-3 amd#2149 | ⏭️ skip-pending | | Model-slot broker serialization | V2-11 amd#2151 | ⏭️ skip-pending | | Custody `/host/v1/*` per-agent scoping | V2-12 amd#2153 | ⏭️ skip-pending | | Migration idempotency | V2-13 amd#2155 | ⏭️ skip-pending | The on-hardware golden path (UI → daemon → sidecar → Lemonade) is an opt-in `real_model` test (`tests/integration/eval/test_sidecar_eval.py`); a new Ubuntu CI job (`test_distributed_seams.yml`) runs the deterministic suite on every touching PR. ## Test plan - [x] `python -m pytest tests/unit/test_sidecar_harness.py` — 27 passed (pure core: SSE parse, sequence match, serial lock, baseline load; no Lemonade) - [x] `python -m pytest tests/integration/test_distributed_seams.py -m distributed_seams -rs` — 6 passed, 4 skipped (skips print their pending-merge reason) - [x] `python -m pytest tests/integration/eval/test_sidecar_eval.py` — 1 skipped (loud opt-in reason; runs on hardware with `GAIA_SIDECAR_EVAL_LIVE=1`) - [x] `python util/lint.py --all --fix` — black/isort/flake8 clean on the new files - [ ] On strix-halo: `GAIA_SIDECAR_EVAL_LIVE=1 python -m pytest tests/integration/eval/test_sidecar_eval.py -m real_model` (golden path through the real sidecar) Part of amd#2014 Closes amd#2180 --------- Co-authored-by: Ovtcharov <[email protected]> Co-authored-by: Kalin Ovtcharov <[email protected]>
Why this matters
Before: the email agent's frozen sidecar bound
127.0.0.1and exposed draft/send against the user's connected mailbox with no caller authentication — any other local process, or a web page in the user's browser (via DNS-rebinding / a drive-by fetch), could reach it and send mail as the user. The draft→sendconfirmation_tokenonly checks payload integrity; it doesn't identify the caller.After: the sidecar authenticates its caller. The spawning parent mints a cryptographically-random per-session bearer token, hands it to the sidecar over the private
GAIA_EMAIL_SIDECAR_TOKENenv channel, and every/v1/email/*request must presentAuthorization: Bearer <token>or it gets 401. A non-loopbackHostis 400 (DNS-rebinding) and a non-loopback browserOriginis 403 (drive-by page). The token is threaded end-to-end through both the npm client and the Agent UI (Python) path, so draft/send keep working. The confirmation-token gate is untouched.Scoped to the sidecar only: the controls are wired onto the frozen sidecar app (
packaging/server.py), so the product server (gaia.api.openai_server) and the OpenAPI export mount the same router unchanged — the published contract does not drift.Note: Host + Origin checks are implemented as one small loopback middleware (rather than Starlette's
TrustedHostMiddlewarealone) because the sidecar needs the Origin check too and both must key off the same per-session policy. Standalone dev runs without the env var log a loud warning and skip the token check (Host/Origin still enforced); the shipped product always spawns with a token.Test plan
pytest hub/agents/python/email/tests/test_caller_auth.py— no-token→401, correct→200, wrong→401, non-loopback Host→400, cross-origin→403, exempt probes, open-mode, and the shippedserver.build_app()wiring.pytest tests/unit/test_email_sidecar_proxy.py tests/unit/test_email_sidecar_manager.py -k "token or auth or proxy"— manager passes the token via env (never argv), proxy replays the bearer header.pytest tests/unit/agents/email/test_spec_html.py— the HTML spec documents the auth posture.pytest hub/agents/python/email/tests/test_rest_contract.py— OpenAPI contract unchanged (the one failing assertion is a pre-existing env version-metadata mismatch, unrelated).vitest run(65 pass) +tsc --noEmit+npm run build— client sends the bearer header when given, omits it otherwise;spawnSidecarmints the token, passes it via env not argv, and binds it tosidecar.client.flake8(repo flags) +black+isortclean on all changed files.Closes #1706