Skip to content

feat(email): harden the sidecar local REST API with per-session caller authentication (#1706) - #1980

Merged
kovtcharov-amd merged 9 commits into
mainfrom
kalin/email-sidecar-caller-auth-1706
Jul 10, 2026
Merged

kovtcharov-amd merged 9 commits into
mainfrom
kalin/email-sidecar-caller-auth-1706

Conversation

@kovtcharov-amd

Copy link
Copy Markdown
Collaborator

Why this matters

Before: the email agent's frozen sidecar bound 127.0.0.1 and 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→send confirmation_token only 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_TOKEN env channel, and every /v1/email/* request must present Authorization: Bearer <token> or it gets 401. A non-loopback Host is 400 (DNS-rebinding) and a non-loopback browser Origin is 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 TrustedHostMiddleware alone) 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 shipped server.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).
  • npm: vitest run (65 pass) + tsc --noEmit + npm run build — client sends the bearer header when given, omits it otherwise; spawnSidecar mints the token, passes it via env not argv, and binds it to sidecar.client.
  • flake8 (repo flags) + black + isort clean on all changed files.

Closes #1706

Ovtcharov added 3 commits July 9, 2026 11:13
…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.
@github-actions github-actions Bot added documentation Documentation changes tests Test changes agent::email Email agent changes labels Jul 9, 2026
@github-actions

github-actions Bot commented Jul 9, 2026

Copy link
Copy Markdown
Contributor

Verdict: Approve with suggestions

This closes a real hole: the email sidecar could send mail as the user with no caller check, and now every /v1/email/* call needs a per-session bearer token (401 otherwise), with Host→400 / Origin→403 as DNS-rebinding / drive-by defenses on top. The implementation is careful — constant-time token compare, token handed over an env channel (never argv), fail-loud dev warning, and the change is threaded end-to-end through both the npm and Python UI paths with tests to match. Docs are synced across all six surfaces (CHANGELOG/README/SKILL/SPEC/HTML specs), which is exactly the bundled-doc discipline this repo asks for.

🔒 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 (/v1/email/connectors/*), which include configure / complete-OAuth / disconnect. The PR's stated threat model is "no other local process can act on your mailbox," but a local process (sending Host: 127.0.0.1, no Origin) can still list, reconfigure, complete, or tear down the mailbox connection unauthenticated. It's a deliberate, documented choice (the always-served playground drives those routes), and interactive OAuth limits the blast radius — but it's the one asymmetry that partially undercuts the model. Confirm those routes genuinely can't act on the mailbox, or gate them too.

Two smaller things: the new HostOriginMiddleware is a BaseHTTPMiddleware, which historically buffers streaming responses — worth confirming POST /v1/email/init still streams line-by-line under it. And the PR bundles an unrelated 328-line MCP planning doc that has nothing to do with #1706.

🔍 Technical details

🟡 Connector routes are not token-gated (packaging/server.py:119-124, connector_routes.py:100-215)

app.include_router(email_router, dependencies=[Depends(require_caller_token)]) gates the email router; app.include_router(connector_router) mounts the connector routes with only the Host/Origin middleware. Those routes are GET /connectors, POST /connectors/{provider}/configure, POST /connectors/{provider}/complete, DELETE /connectors/{provider} — the mailbox-connection lifecycle. A local process passing Host: 127.0.0.1 and no Origin clears the middleware and reaches all four without a token. configure/complete (OAuth setup) and disconnect are the concerning verbs. The code comment states this is intentional (playground needs them), and interactive OAuth bounds the risk, but it's worth either token-gating these too or documenting explicitly why an unauthenticated local caller may drive mailbox connect/disconnect. Not clearly blocking, but it's the item to resolve before this counts as "the mailbox is caller-authenticated."

🟡 Streaming under BaseHTTPMiddleware (caller_auth.py:1047, api_routes.py:2565)

HostOriginMiddleware(BaseHTTPMiddleware) wraps every request, including POST /v1/email/init (email_provision), which returns a StreamingResponse of newline-delimited progress. BaseHTTPMiddleware has a long history of buffering/altering streaming responses and background-task timing. Modern Starlette handles the pass-through case, but since the whole point of /init is incremental progress, please verify it still streams line-by-line through the middleware. If it buffers, a small pure-ASGI middleware (inspect headers, short-circuit, else await self.app(scope, receive, send)) avoids the issue and is a better fit since you only read two headers.

🟢 Scope: unrelated planning doc bundled in

docs/plans/mcp-context-efficiency.md (+328 lines) is not on origin/main and is unrelated to #1706. Per the scope-clean guidance it belongs in its own PR; mixing it into a security change makes the diff harder to reason about and the security fix harder to cherry-pick/revert cleanly.

🟢 manager.py:257 — popen_kwargs.pop("env", {}) assumes non-None

spawn_env = {**os.environ, **popen_kwargs.pop("env", {})} raises TypeError if a caller ever passes env=None in popen_kwargs. No current caller does, so this is defensive-only — pop("env") or {} would harden it.

Strengths

  • Correct token handling: hmac.compare_digest for the compare, token via the GAIA_EMAIL_SIDECAR_TOKEN env channel rather than argv (with a test asserting it never appears in argv), and secrets.token_urlsafe(32) / crypto.randomBytes(32).base64url for generation.
  • Fail-loud dev mode: open mode (no env token) logs a loud warning and still enforces Host/Origin — matches the repo's no-silent-fallback rule.
  • Doc sync is exemplary: CHANGELOG, README, SKILL, SPEC, spec_html.py, and specification.html all updated together, with tests (test_spec_html.py) asserting the auth section and status codes are present.
  • End-to-end + tested: the token is threaded through the npm lifecycle.ts→client.ts path and the Python manager.py→proxy.py path, each with unit tests (env-not-argv, header replay, omit-when-absent), plus a build_app() wiring test that guards against the dependency silently not being installed.
  • TOKEN_ENV_VAR kept as a literal in core (manager.py) with a comment pinning it to the wheel's constant — correct call to avoid core depending on the hub package.

… + 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.
kovtcharov
kovtcharov previously approved these changes Jul 9, 2026
…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.
kovtcharov
kovtcharov previously approved these changes Jul 9, 2026
Ovtcharov added 2 commits July 9, 2026 14:20
…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.
@kovtcharov-amd

Copy link
Copy Markdown
Collaborator Author

Thanks for the thorough review — merged latest main and addressed all four points.

🔒 Connector routes now gated (the security asymmetry). The token dependency is applied to every mailbox-touching router, not just the email router: connector lifecycle (/v1/email/connectors/* — configure / complete-OAuth / disconnect) and the new stateful agent surface (/v1/email/agent/*) that landed on main. A local caller with Host: 127.0.0.1 and no Origin now gets 401 on all of them. New test asserts GET /v1/email/connectors and POST /v1/email/agent/session are 401 without the token. cc @kovtcharov-amd — this closes the "no other local process can act on your mailbox" gap end-to-end.

🟡 Streaming — middleware rewritten as pure ASGI. HostOriginMiddleware no longer subclasses BaseHTTPMiddleware; it inspects the two headers and passes (scope, receive, send) straight through, so it can't buffer/reorder the StreamingResponse. Added a test that POST /v1/email/init streams its 503 body intact through the middleware + token gate.

🟢 Unrelated planning doc — docs/plans/mcp-context-efficiency.md had already merged to main via another PR, so merging main dropped it from this PR's diff. Gone.

🟢 popen_kwargs.pop("env", …) — hardened to pop("env", None) or {} so an explicit env=None can't TypeError.

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.
@kovtcharov-amd
kovtcharov-amd enabled auto-merge July 9, 2026 21:40
@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Jul 10, 2026
Merged via the queue into main with commit bb2d492 Jul 10, 2026
40 checks passed
@kovtcharov-amd
kovtcharov-amd deleted the kalin/email-sidecar-caller-auth-1706 branch July 10, 2026 12:39
pull Bot pushed a commit to bhardwajRahul/gaia that referenced this pull request Jul 14, 2026
… (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]>
pull Bot pushed a commit to bhardwajRahul/gaia that referenced this pull request Jul 14, 2026
… 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]>
pull Bot pushed a commit to bhardwajRahul/gaia that referenced this pull request Jul 18, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agent::email Email agent changes documentation Documentation changes tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Harden the email sidecar's local REST API with caller authentication

3 participants