Repository navigation
test(security): pin daemon HTTP security boundaries (#1075) - #1076
Conversation
Three contracts previously untested at the dispatch level are now pinned: 1. DELETE endpoint auth+origin gate matrix — `do_DELETE` calls `_check_auth` then `_check_cross_origin` before routing; five DELETE routes added to `ENDPOINTS_DELETE` with 401/403 parametrized tests identical in shape to the existing POST matrix. 2. POST endpoint matrix extended — user-state write routes (`/api/user/marks`, `/api/user/annotations`, `/api/user/saved-views`, `/api/user/recall-packs`, `/api/user/workspaces`) added to `ENDPOINTS_POST` with a `dispatch_post` mock so the gate tests work without touching the DB. 3. Inbox path traversal — `_staged_inbox_source` uses `PurePath.name` to strip directory components before matching; seven traversal shapes (`../../../etc/passwd`, `/etc/passwd`, embedded slashes, etc.) all produce `path_not_found` because the extracted basename never matches an inbox entry outside the tree. A symlink-escape test confirms `resolved.relative_to(inbox_root)` catches links pointing outside inbox. A positive case confirms the name-extraction sanitization is transparent for legitimate dotdot references. 4. JSON serialization robustness — `_json_bytes` raises `TypeError` (not silently truncates) for sets and custom objects; the `daemon_safe_handler` decorator catches the exception and returns a well-formed 500 error JSON response rather than leaving the connection hanging. Co-Authored-By: Claude <[email protected]>
|
Caution Review failedPull request was closed or merged during review 📝 WalkthroughWalkthroughAdds unit tests expanding mutation-endpoint auth/origin matrices, hardening /api/ingest against path traversal and symlink escapes, and asserting JSON serialization failures produce a 500 error envelope. ChangesDaemon HTTP API Security Tests
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 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.
Actionable comments posted: 2
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@tests/unit/daemon/test_daemon_http_security.py`:
- Around line 463-474: Add a null-byte traversal case to the pytest parameter
matrix for "traversal_path" in tests/unit/daemon/test_daemon_http_security.py by
inserting at least one input that includes a trailing or embedded NUL (e.g.,
"../etc/passwd\0" or "evil\0") into the list used by the
pytest.mark.parametrize("traversal_path", ...); ensure the new case follows the
existing style (same quoting/format) so the ingest boundary test covers
null-byte path-sanitization edge cases.
- Around line 360-403: Add a new test method to
TestDeleteEndpointAuthAndOriginGate that verifies a valid token with a
same-origin (loopback) Origin is allowed: use _make_handler("DELETE", path,
auth_header="Bearer secret", origin="http://127.0.0.1") (or the canonical
loopback origin used elsewhere), capture send_error via _capture_responses,
patch polylogue.daemon.user_state_http.dispatch_delete to return True, call
handler.do_DELETE(), and assert that send_error was never called with
HTTPStatus.UNAUTHORIZED or HTTPStatus.FORBIDDEN (same pattern as
test_valid_token_no_origin_passes_gates but supplying the loopback Origin to
ensure browser same-origin DELETEs are permitted).
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro
Run ID: 132dad79-197d-491e-ad8c-f4edf7114798
📒 Files selected for processing (1)
tests/unit/daemon/test_daemon_http_security.py
| @pytest.mark.parametrize( | ||
| "traversal_path", | ||
| [ | ||
| "../../../etc/passwd", | ||
| "../../etc/passwd", | ||
| "../evil", | ||
| "/etc/passwd", | ||
| "/tmp/evil.jsonl", | ||
| "inbox/../../../etc/passwd", | ||
| "a/b/c/session.jsonl", | ||
| ], | ||
| ) |
There was a problem hiding this comment.
Include a null-byte traversal case in the ingest boundary matrix.
The traversal set currently covers slash/dotdot/absolute forms but omits null-byte input, which is part of the stated contract and a key path-sanitization edge case.
Proposed matrix update
`@pytest.mark.parametrize`(
"traversal_path",
[
"../../../etc/passwd",
"../../etc/passwd",
"../evil",
+ "\x00evil.jsonl",
"/etc/passwd",
"/tmp/evil.jsonl",
"inbox/../../../etc/passwd",
"a/b/c/session.jsonl",
],🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@tests/unit/daemon/test_daemon_http_security.py` around lines 463 - 474, Add a
null-byte traversal case to the pytest parameter matrix for "traversal_path" in
tests/unit/daemon/test_daemon_http_security.py by inserting at least one input
that includes a trailing or embedded NUL (e.g., "../etc/passwd\0" or "evil\0")
into the list used by the pytest.mark.parametrize("traversal_path", ...); ensure
the new case follows the existing style (same quoting/format) so the ingest
boundary test covers null-byte path-sanitization edge cases.
CodeRabbit P1: TestDeleteEndpointAuthAndOriginGate was missing test_valid_token_same_origin_passes_gates, creating a gap where the POST matrix had loopback-origin coverage but DELETE did not. Both endpoint classes now have the full 4-case matrix: missing token (401), invalid token (401), cross-origin valid token (403), same-origin valid token (pass). Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
#1060) (#1085) ## Summary Adds 16 contract tests under `tests/unit/daemon/test_daemon_http_contracts.py` covering five operational daemon HTTP contract families — status envelope shape, read-only convergence behavior, stale/disconnected/degraded state, privacy boundaries, and operation-spec catalog discipline. ## Problem The security-boundary contracts of the daemon HTTP surface are pinned by `tests/unit/daemon/test_daemon_http_security.py` (added in #1075 / #1076 — auth gates, origin allowlist, JSON serialization fallback). The *operational* contracts of the same surface were unpinned at the HTTP layer: - The documented `GET /api/status` envelope (`daemon_liveness`, `component_state`, `fts_readiness`, `convergence`, `health`, …) had no test asserting which keys are required vs. optional. A regression that dropped or renamed a key would only fail downstream in the web reader or dashboard. - There was no assertion that `GET /api/status` and `GET /api/health` are read-only — a future change that triggered convergence work as a side effect of status polling could pass review. - Degraded states (no daemon pidfile, internal health-checker error, FTS index out of sync) had no contract that they surface as structured envelope fields rather than raw exceptions. - No test asserted that the status payload never leaks `VOYAGE_API_KEY`/`OPENAI_API_KEY`/`ANTHROPIC_API_KEY` sentinel env vars, never accidentally dumps `os.environ`, and that the static web shell HTML has no inlined secrets. - No test asserted that `GET /api/conversations/<id>` returns only the requested row. - The runtime / declared `OperationSpec` catalog had no assertion that every spec declares the metadata downstream consumers depend on (name shape, code_refs format, effects enum membership, `mutates_state` consistency with declared write effects). ## Solution One new file: `tests/unit/daemon/test_daemon_http_contracts.py`. Five `TestX` classes, all marked `@pytest.mark.contract`, all using the in-process `DaemonAPIHandler` harness from `test_daemon_http_security.py` (no real daemon process, no socket listener): 1. **`TestStatusEnvelopeContract`** — enumerates `REQUIRED_STATUS_KEYS` / `REQUIRED_HEALTH_KEYS` from the actual `daemon_status_payload()` shape. Extending the envelope requires extending the test in the same PR. Pins `component_state` subsystems to `{api, watcher, browser_capture}` and `quick_check` to the documented enum. 2. **`TestStatusReadOnlyContract`** — repeated polls of `/api/status` and `/api/health` leave the archive directory hash unchanged across 3 polls each. 3. **`TestDegradedStateContract`** — `daemon_liveness=False` with no pidfile; `/api/health/check` returns 503 on degraded health (mocks `_run_fast_checks` to inject a CRITICAL alert); the documented exception path translates to a bounded `{ok:false, status:"error", detail:"health check failed"}` envelope rather than a raw 500; `fts_readiness` is asserted to be a structured dict, never a free-form string. 4. **`TestPrivacyContract`** — plants sentinel values in `VOYAGE_API_KEY`/`OPENAI_API_KEY`/`ANTHROPIC_API_KEY` and a uniquely-named `POLYLOGUE_TEST_SENTINEL_ENV_DO_NOT_DUMP`, asserts none appear in the serialized status payload; asserts the static `WEB_SHELL_HTML` constant never inlines env-derived secrets; seeds three conversations (`c1`/`c2`/`c3`) and asserts `GET /api/conversations/c1` mentions `c1` but not the adjacent rows' distinctive markers. 5. **`TestOperationSpecContract`** — two-tier check. `RUNTIME_OPERATION_SPECS` strictly require kebab-case name, non-trivial description, well-formed `code_refs`, declared `effects` from the known enum, and `mutates_state=True` whenever `DbWrite|FileWrite|Destructive` is declared. `DECLARED_OPERATION_SPECS` (superset including scenario/benchmark entries) only require the structural fields — these advisory entries may legitimately omit `code_refs`. All names must be unique across the declared catalog. Each test that produces something worth aggregating calls `record_contract_evidence(...)` and writes a bounded JSON artifact under `.cache/verification/evidence/` keyed `daemon.status.envelope`, `daemon.status.read_only`, `daemon.status.disconnected`, `daemon.status.no_secret_leak`, `daemon.operations.runtime_spec_contract`. No daemon source changes required — every contract pins existing behavior. The exception-path contract (the third degraded-state test) confirms the existing `daemon_safe_handler`-style try/except in `_handle_health_check` works as documented. ## Verification ``` nix develop -c pytest tests/unit/daemon/test_daemon_http_contracts.py -v # 16 passed in 2.26s nix develop -c pytest tests/unit/daemon tests/unit/operations -q --basetemp=.cache/pytest-tmp # 375 passed in 15.38s nix develop -c ruff format tests/unit/daemon/test_daemon_http_contracts.py nix develop -c ruff check tests/unit/daemon/test_daemon_http_contracts.py # All checks passed! nix develop -c mypy tests/unit/daemon/test_daemon_http_contracts.py # Success: no issues found in 1 source file nix develop -c devtools verify --quick # total_duration_s: 38.32, exit_code: 0 ls .cache/verification/evidence/ | grep -E "daemon\.(status|operations)" | wc -l # 6 new evidence artifacts ``` Ref #1060 Ref #1058 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 4.7 <[email protected]>
Summary
Adds 284 lines of security-boundary tests for
polylogue/daemon/http.py— the external attack surface of the archive, which had ~50 lines of tests on 1,086 source lines.Problem
Three untested security contracts: loopback-origin enforcement on mutation endpoints, path traversal via staged inbox source names, JSON serialization robustness with unserializable data.
Solution
New
tests/unit/daemon/test_daemon_http_security.py:../../../etc/passwd, embedded slashes) all rejected; symlink escape rejected viaresolved.relative_to(inbox_root)_json_bytesraisesTypeErrorfor unserializable types;daemon_safe_handlerreturns well-formed{"error": "internal_error"}500Tests confirmed the existing production code already handles all three cases correctly — this pins the contracts so regressions are immediately visible.
Verification
Closes #1075
Summary by CodeRabbit