Skip to content

test(security): pin daemon HTTP security boundaries (#1075) - #1076

Merged
Sinity merged 2 commits into
masterfrom
worktree-agent-ac873862
May 16, 2026
Merged

Sinity merged 2 commits into
masterfrom
worktree-agent-ac873862

Conversation

@Sinity

@Sinity Sinity commented May 16, 2026 •

Copy link
Copy Markdown
Owner

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:

  • POST/DELETE endpoint matrix — all write routes verified for auth (missing/invalid token → 401) and origin (cross-origin → 403) gates; DELETE matrix was entirely absent before
  • Path traversal: 7 traversal patterns (../../../etc/passwd, embedded slashes) all rejected; symlink escape rejected via resolved.relative_to(inbox_root)
  • JSON serialization: _json_bytes raises TypeError for unserializable types; daemon_safe_handler returns well-formed {"error": "internal_error"} 500

Tests confirmed the existing production code already handles all three cases correctly — this pins the contracts so regressions are immediately visible.

Verification

pytest tests/unit/daemon/test_daemon_http_security.py -v  # all pass
devtools verify --quick  # exit 0

Closes #1075

Summary by CodeRabbit

  • Tests
    • Expanded DELETE endpoint security tests to verify bearer-token auth, origin rejection, and successful same-origin/no-origin handling.
    • Expanded POST tests to include user-state write endpoints and exercise per-route dispatch paths.
    • Added inbox boundary tests covering traversal rejection, accepted traversal basenames, and symlink-escape rejection.
    • Added JSON serialization robustness checks, including round-trip, unserializable input handling, and 500-error JSON fallback.

Review Change Stack

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]>
@coderabbitai

coderabbitai Bot commented May 16, 2026 •

Copy link
Copy Markdown

Caution

Review failed

Pull request was closed or merged during review

📝 Walkthrough

Walkthrough

Adds 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.

Changes

Daemon HTTP API Security Tests

Layer / File(s) Summary
Mutation endpoint auth and origin gates
tests/unit/daemon/test_daemon_http_security.py
ENDPOINTS_POST extended with user-state write routes and new ENDPOINTS_DELETE added. POST tests patch polylogue.daemon.user_state_http.dispatch_post to return True for relevant routes. New TestDeleteEndpointAuthAndOriginGate parametrized class verifies DELETE endpoints return 401 unauthorized for missing/invalid tokens, 403 cross_origin_denied for hostile Origin, and allow valid-token same-origin/no-Origin when dispatcher succeeds.
Inbox path traversal boundary enforcement
tests/unit/daemon/test_daemon_http_security.py
TestIngestEndpointInboxBoundary gains tests that reject traversal attempts escaping the inbox (including embedded/absolute shapes), accept traversal basenames that match real inbox entries, and reject symlink targets that resolve outside the inbox staging area.
JSON serialization error envelope robustness
tests/unit/daemon/test_daemon_http_security.py
TestJsonSerializationRobustness verifies _json_bytes round-trips valid payloads, raises TypeError for unserializable inputs, and that daemon_safe_handler returns a well-formed 500 internal_error JSON response when a handler's _send_json fails due to unserializable response data.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

🐰 I nibble at tests with care and speed,
POSTs and DELETEs checked for gate and key,
Inbox paths sealed so no escapes breed,
Broken JSON wrapped in a tidy 500 plea,
Hooray — the daemon sleeps more safely with me.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 66.67% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'test(security): pin daemon HTTP security boundaries' clearly and specifically summarizes the main change: adding security-boundary tests for daemon HTTP endpoints.
Description check ✅ Passed The description covers all template sections: Summary (what changed and why), Problem (three untested security contracts), Solution (test implementation details), Verification (test commands), and follows format requirements.
Linked Issues check ✅ Passed The PR fully addresses all three acceptance criteria from issue #1075: loopback-origin enforcement via auth/origin gate matrix, path traversal prevention via 7 test patterns and symlink validation, and JSON serialization robustness with TypeError and error envelope tests.
Out of Scope Changes check ✅ Passed All changes are scoped to test-only additions in tests/unit/daemon/test_daemon_http_security.py, directly addressing the three security contracts specified in issue #1075 with no production code modifications.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch worktree-agent-ac873862

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.

@coderabbitai coderabbitai 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.

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0631b1a and 9aabc1b.

📒 Files selected for processing (1)
  • tests/unit/daemon/test_daemon_http_security.py

Comment on lines +463 to +474
@pytest.mark.parametrize(
"traversal_path",
[
"../../../etc/passwd",
"../../etc/passwd",
"../evil",
"/etc/passwd",
"/tmp/evil.jsonl",
"inbox/../../../etc/passwd",
"a/b/c/session.jsonl",
],
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

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]>
@Sinity
Sinity merged commit 2a9244d into master May 16, 2026
3 of 4 checks passed
@Sinity
Sinity deleted the worktree-agent-ac873862 branch May 16, 2026 09:35
Sinity added a commit that referenced this pull request May 16, 2026
#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]>
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.

test(security): pin daemon HTTP security boundaries — loopback enforcement, path traversal, error envelope

1 participant