Skip to content

fix(daemon): finalize HTTP API security surface and document residual decisions (#868) - #1004

Merged
Sinity merged 4 commits into
masterfrom
feature/fix/daemon-api-security-honest-closure
May 10, 2026
Merged

Sinity merged 4 commits into
masterfrom
feature/fix/daemon-api-security-honest-closure

Conversation

@Sinity

@Sinity Sinity commented May 10, 2026 •

Copy link
Copy Markdown
Owner

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.md for 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/sources paths. Adversarial review additionally caught a coherence gap: _is_localhost admits ::1 as a loopback bind address, but the cross-origin allowlist hardcoded only the IPv4 and localhost strings — so a web shell served from an IPv6 bind would have its same-origin POSTs wrongly rejected.

Solution

Acceptance criteria matrix

AC What State after this PR
868-A1 docs/security.md defines trust boundaries, actor model, asset model, attack surface ✅ Refreshed: Trust Boundaries, Actors, Assets sections added; attack-surface table corrected
868-A2 All POST/PUT/DELETE endpoints require valid bearer token when configured ✅ Pre-existing in _check_auth_logic; new parametrized matrix covers all 4 POST endpoints × {missing, invalid, valid}
868-A3 All POST endpoints reject cross-origin browser requests via Origin check, including IPv6 loopback ✅ Pre-existing in _check_cross_origin; fixed to include http://[::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
868-A4 Non-loopback bind refuses without --api-auth-token AND --insecure-allow-remote ✅ Pre-existing in daemon/cli.py:309-319; new test parametrizes 3 non-loopback hosts
868-A5 --insecure-allow-remote requires explicit token ✅ Pre-existing; new test covers both missing and empty-string token
868-A6 Raw artifact endpoint policy: token-gated, content not redacted (decision) ✅ Decision documented in docs/security.md; rationale: same operator can read blob store directly
868-A7 /api/sources policy: token-gated, returns absolute paths (decision) ✅ Decision documented; rationale: operator needs paths for source diagnosis
868-A8 Per-endpoint security test matrix ✅ New matrix in test_daemon_http_security.py: 10 GET endpoints × 3 token states + 4 POST endpoints × {3 token states ⊕ 4 origin states}, total 120 parametrized tests
868-A9 OPTIONS returns 405 by design (decision) ✅ Pre-existing in do_OPTIONS; new test parametrized over all 14 endpoints; decision documented
868-A10 Token never logged or in URLs ✅ New static-grep guardrail (TestNoTokenLogging) scans polylogue/daemon and polylogue/browser_capture for log/print calls mentioning auth_token or Bearer; legitimate non-logging usage whitelisted
868-A11 Browser capture: separate-by-design (decision) ✅ Decision documented: different threat surface (extension→receiver vs CLI→daemon), sharing a token would conflate them; token-leak guardrail covers both modules
868-A12 Closeout matrix in PR + issue comment ✅ This PR body + planned comment on #868

Files 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

$ pytest tests/unit/daemon/test_daemon_http_security.py \
         tests/unit/daemon/test_daemon_cli_remote_bind.py -q
120 passed in ~0.4s

$ devtools verify --quick
verify: all checks passed

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 ::1 admitted by _is_localhost for binding but not in the cross-origin allowlist; web shell served from http://[::1]:port would have legitimate same-origin POSTs rejected as cross-origin). Fixed in commit bb59aac6 by adding http://[::1]: / https://[::1]: to both polylogue/daemon/http.py:_check_cross_origin and 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

Copilot AI review requested due to automatic review settings May 10, 2026 02:19
@coderabbitai

coderabbitai Bot commented May 10, 2026 •

Copy link
Copy Markdown

Warning

Rate limit exceeded

@Sinity has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 52 minutes and 5 seconds before requesting another review.

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 @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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 configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: cf0a7aa6-3782-4a6d-8ffa-a9a7420a3e1b

📥 Commits

Reviewing files that changed from the base of the PR and between c2f2c26 and b7e5c82.

📒 Files selected for processing (5)
  • docs/daemon-threat-model.md
  • docs/security.md
  • polylogue/daemon/http.py
  • tests/unit/daemon/test_daemon_cli_remote_bind.py
  • tests/unit/daemon/test_daemon_http_security.py
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/fix/daemon-api-security-honest-closure

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread polylogue/operations/archive.py Resolved

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot encountered an error and was unable to review this pull request. You can try again by re-requesting a review.

Sinity and others added 4 commits May 10, 2026 13:07
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]>
@Sinity
Sinity force-pushed the feature/fix/daemon-api-security-honest-closure branch from af8ea3e to b7e5c82 Compare May 10, 2026 11:09
@Sinity
Sinity merged commit db96872 into master May 10, 2026
4 checks passed
@Sinity
Sinity deleted the feature/fix/daemon-api-security-honest-closure branch May 10, 2026 11:11
Sinity added a commit that referenced this pull request May 11, 2026
…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.

[![Review Change
Stack](https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui.svg)](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]>
@Sinity

Sinity commented Oct 1, 2026

Copy link
Copy Markdown
Owner Author

Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.

  • 69.F045 / P2: fixed-already at the checked revision: polylogue/api/archive.py:68 imports IndexStatus at runtime, outside TYPE_CHECKING. The current get_index_status route at lines 5576-5584 delegates to archive.index_status through a read transaction and has no undefined-name DatabaseError fallback.

Only the rows listed above are dispositioned. Held findings remain open.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(daemon): define local API threat model and auth boundaries

2 participants