Repository navigation
fix(daemon): finalize HTTP API security surface and document residual decisions (#868) - #1004
Conversation
|
Warning Rate limit exceeded
You’ve run out of usage credits. Purchase more in the billing tab. ⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. ℹ️ Review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (5)
✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: b8e9dede92
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
bb59aac to
af8ea3e
Compare
Pins three security contracts at the dispatch level:
1. Every authenticated endpoint refuses requests without a valid bearer
token when one is configured. Pure-logic check (_check_auth_logic)
is parametrized against six (header, expected) shapes covering empty,
wrong-scheme, wrong-token, and exact-match. Per-endpoint dispatch is
parametrized over all 10 GET routes × {missing, invalid, valid}.
2. Every mutating POST endpoint refuses cross-origin browser requests.
Parametrized over all 4 POST routes × {missing token, invalid token,
valid + no origin, valid + same-origin, valid + cross-origin}, with
the cross-origin case asserting 403 cross_origin_denied.
3. OPTIONS returns 405 by design (no CORS preflight). Asserted on every
endpoint.
Plus a static-grep guardrail (TestNoTokenLogging) that scans
polylogue/daemon and polylogue/browser_capture for log/print calls
mentioning auth_token or Bearer; legitimate non-logging usage
(_check_auth_logic invocation) is whitelisted.
Plus a contract pin on _is_localhost — used by the remote-bind gate
in daemon/cli.py — that asserts loopback addresses match and
non-loopback values do not.
Adding a new endpoint to the daemon now costs one line in
ENDPOINTS_GET or ENDPOINTS_POST and gets full coverage automatically.
Ref #868-A2, #868-A3, #868-A8, #868-A9, #868-A10.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The daemon refuses to start an HTTP API on a non-loopback address
unless the operator opts in via --insecure-allow-remote AND configures
--api-auth-token. Both conditions are tested:
- non-loopback host without --insecure-allow-remote → UsageError
("not a loopback")
- non-loopback host with --insecure-allow-remote but no token (or
empty-string token) → UsageError ("requires --api-auth-token")
- loopback bind with no token → passes the security gate (post-gate
sentinel raises to assert the gate admitted the request)
- API disabled with non-loopback api_host value → gate not invoked
Tests target the security gate at run_daemon_services line 309-319
in isolation by patching _ensure_fts_startup_readiness to a sentinel
exception so the test exits the moment the gate decides "allow."
That keeps the post-gate startup chain (pidfile, FTS readiness, etc.)
out of scope for this focused security test.
Ref #868-A4, #868-A5.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
#868) Brings docs/security.md and docs/daemon-threat-model.md into agreement with the implementation that landed in earlier #868 phases and adds the explicit-decision section for the residual scope. docs/security.md: - Adds Trust Boundaries, Actors, Assets sections (#868-A1). - Refreshes the attack-surface table to match the actual route table: drops the nonexistent /api/backfill row, adds /api/sources, /api/raw_artifacts/:id, /api/maintenance/plan, /api/maintenance/run. Each row records the auth and origin requirements. - Documents the four explicit decisions for the residual scope: raw artifacts not redacted (#868-A6), /api/sources returns absolute paths (#868-A7), OPTIONS returns 405 (#868-A9), browser-capture has its own token by design (#868-A11). - Adds Non-Threats section. - Cross-links the test files that pin each contract. docs/daemon-threat-model.md: - Trust Boundary section now describes the actual auth mechanism (bearer token + Origin allowlist + remote-bind refusal) rather than the previous "loopback binding is the auth mechanism" claim, which was outdated as of the #868 phase-1 work. - Cross-links docs/security.md for the full policy. Ref #868-A1, #868-A6, #868-A7, #868-A9, #868-A11. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Adversarial review iteration 1 caught a coherence gap: ``_is_localhost`` admits ``::1`` as a loopback bind address (so the daemon happily binds to it via ``--api-host ::1``), but ``_check_cross_origin`` only listed the IPv4 and ``localhost`` prefixes. A web shell served from the IPv6 bind would send ``Origin: http://[::1]:port`` and same-origin POSTs from it would be rejected as cross-origin. Adds ``http://[::1]:`` and ``https://[::1]:`` to the production allowlist and the matching test helper, plus parametrized cases for the legitimate IPv6 origin and a bracketed-IPv6 subdomain trick that must still be rejected. Ref #868-A3. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
af8ea3e to
b7e5c82
Compare
…ture (#1005) (#1011) ## Summary Closes #1005. Two near-duplicate loopback helpers across the daemon HTTP API and the browser-capture receiver disagreed on RFC compliance; consolidates them into one shared helper, removes two dead helpers in `daemon/http.py`, and brings every consumer (bind enforcement, cross-origin allowlist, security tests, security docs) onto the shared definition. The first commit (chore) restores the pytest baseline by fixing three pre-existing master failures encountered during verification — split out from the loopback work because it is unrelated. ## Problem `polylogue/daemon/http.py::_is_localhost` rejected `127.0.0.2`, `127.1.2.3`, and the rest of the `127.0.0.0/8` block, while `polylogue/browser_capture/server.py::_is_loopback` accepted the full block. `polylogue/daemon/cli.py` then hardcoded the same narrow tuple for `--api-host` enforcement, so `polylogued run --api-host 127.0.0.2` was refused as a remote bind even though it is a loopback per RFC 5735. The cross-origin allowlist in `_check_cross_origin` had the same narrow set hard-coded. Two dead helpers in `daemon/http.py` (`_advertised_cors_headers` returning `{}` in every branch, and an unread `_auth_required` property whose docstring contradicted `_check_auth_logic`) remained as leftovers from earlier iterations and confused adversarial review on PR #1004. ## Solution - `polylogue/core/loopback.py` (new) — `is_loopback_host(host)` defers to `ipaddress.ip_address(host).is_loopback` so the full `127.0.0.0/8` block plus `::1` plus the `localhost` name are accepted; `is_loopback_origin(origin)` parses scheme/host/port from a browser `Origin` header, including bracketed IPv6 per RFC 3986. - `daemon/http.py` — re-routes `_is_localhost` and `_check_cross_origin` through the shared helpers; removes `_advertised_cors_headers` and `_auth_required`. - `daemon/cli.py` — `--api-host` enforcement uses `is_loopback_host`. - `browser_capture/server.py` — defers to the shared helper. - `tests/unit/core/test_loopback.py` (new) — RFC 5735 contract tests covering broad range plus malformed inputs. - `tests/unit/daemon/test_daemon_http_security.py::TestIsLocalhost` — parametrization extended to assert the broader range. - `docs/security.md` — cross-origin allowlist statement now points at the shared helper and names RFC 5735. The earlier `chore: restore master pytest baseline` commit fixes three orphan failures present on master: 1. terminal snapshot drift after new `context-pack`/`maintenance` commands shifted column padding; 2. `test_artifact_graph` expected list missing `message_type_backfill` (added in 5b5dc1e); 3. `test_cwd_prefix_filter`'s direct-write helper bypassed `prepare_enrichment` so the typed `working_directories_json` column was never populated; added a symmetric fallback in `conversations_writes.save_conversation_record` that promotes `provider_meta.working_directories`/`cwd` when the typed column is absent. ## Verification - `nix develop -c pytest -q tests/unit/core/test_loopback.py tests/unit/daemon tests/unit/browser_capture` → 174 passed. - `nix develop -c devtools verify --quick` → all checks passed (mypy, ruff, render-all, topology, layering, file budgets, witness lifecycle, proof-pack check). - Full `nix develop -c pytest -q --ignore=tests/integration` → green (one xdist worker had a transient long stall on `test_api_facets_scoped_to_provider` ~10min; final run completed cleanly). <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Documentation** * Enhanced security documentation with clearer descriptions of loopback-only default behavior and CSRF/origin boundary protections. * **Bug Fixes** * Improved working directory handling with fallback logic for better data serialization. * **Refactor** * Centralized loopback detection logic for more consistent security boundary enforcement across modules. * **Tests** * Added comprehensive test coverage for loopback host and origin detection. * Updated existing tests to validate expanded loopback address range support. [](https://app.coderabbit.ai/change-stack/Sinity/polylogue/pull/1011) <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
|
Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.
Only the rows listed above are dispositioned. Held findings remain open. |
Summary
Brings #868 (daemon API threat model and auth boundaries) to actual closure by adding the per-endpoint security test matrix, the remote-bind refusal coverage, an explicit-decisions section in
docs/security.mdfor the residual scope, and a fix for the IPv6-loopback origin allowlist gap surfaced during adversarial review. The bearer-token auth, origin allowlist, and remote-bind enforcement were already implemented; what was missing was test coverage and policy documentation that pins the contract end-to-end.Closes #868.
Depends on #1001 (verify baseline restoration) — merge that first; this branch rebases on it.
Problem
#868 was reopened twice during the closed-issue audit. The previous closeouts deferred CORS/origin hardening, remote-bind handling, per-endpoint review, and security tests to a "phase 2" with no issue number. Implementation had landed across both reopens, but the test surface only covered helper-function logic — there was no per-endpoint matrix proving every route actually invokes the auth/origin checks, no test pinning the remote-bind refusal at
daemon/cli.py:309-319, no token-leak guardrail, and no policy doc explicitly recording the decisions about raw-artifact content and/api/sourcespaths. Adversarial review additionally caught a coherence gap:_is_localhostadmits::1as a loopback bind address, but the cross-origin allowlist hardcoded only the IPv4 andlocalhoststrings — so a web shell served from an IPv6 bind would have its same-origin POSTs wrongly rejected.Solution
Acceptance criteria matrix
docs/security.mddefines trust boundaries, actor model, asset model, attack surface_check_auth_logic; new parametrized matrix covers all 4 POST endpoints × {missing, invalid, valid}_check_cross_origin; fixed to includehttp://[::1]:/https://[::1]:; new matrix covers all 4 POST endpoints × {no origin, same-origin (incl. IPv6), cross-origin}; bracketed-IPv6 subdomain trick (http://[::1].evil.com) is rejected--api-auth-tokenAND--insecure-allow-remotedaemon/cli.py:309-319; new test parametrizes 3 non-loopback hosts--insecure-allow-remoterequires explicit tokendocs/security.md; rationale: same operator can read blob store directly/api/sourcespolicy: token-gated, returns absolute paths (decision)test_daemon_http_security.py: 10 GET endpoints × 3 token states + 4 POST endpoints × {3 token states ⊕ 4 origin states}, total 120 parametrized testsOPTIONSreturns 405 by design (decision)do_OPTIONS; new test parametrized over all 14 endpoints; decision documentedTestNoTokenLogging) scanspolylogue/daemonandpolylogue/browser_capturefor log/print calls mentioningauth_tokenorBearer; legitimate non-logging usage whitelistedFiles changed
tests/unit/daemon/test_daemon_http_security.py(NEW; 120 parametrized tests; ~430 LoC)tests/unit/daemon/test_daemon_cli_remote_bind.py(NEW; 9 tests; ~175 LoC)polylogue/daemon/http.py(IPv6 loopback added to cross-origin allowlist; +6/-3 lines)docs/security.md(rewritten; +99 lines)docs/daemon-threat-model.md(refreshed Trust Boundary section; +17 lines)Verification
Adversarial review notes
The plan called for an adversarial subagent loop iterating until no legitimate gaps remained, capped at 5 iterations. The loop converged at iteration 2.
Iteration 1 — found one real gap (868-A3: IPv6 loopback
::1admitted by_is_localhostfor binding but not in the cross-origin allowlist; web shell served fromhttp://[::1]:portwould have legitimate same-origin POSTs rejected as cross-origin). Fixed in commitbb59aac6by addinghttp://[::1]:/https://[::1]:to bothpolylogue/daemon/http.py:_check_cross_originand the test helper, plus parametrized cases for the legitimate IPv6 origin and a bracketed-IPv6 subdomain trick (http://[::1].evil.com) that must still be rejected.Iteration 2 — independent review: "No legitimate gaps found across all 12 ACs after iteration 2 review." Confirmed all assertions catch their regressions, the bracketed-IPv6 trick is correctly rejected by the colon-required prefix match, threat-model docs are internally consistent, and no closeout language hedges without an issue number.
Loop exited clean. Total: 4 #868 commits (3 substantive + 1 adversarial-iteration fix), 2 adversarial iterations.
🤖 Generated with Claude Code