Skip to content

feat: Muse gated passthrough stage 2 (hold, approval plane, ntfy notifier) - #29

Merged
chaodu-agent merged 18 commits into
mainfrom
feat/muse-stage2
Nov 18, 2026
Merged

chaodu-agent merged 18 commits into
mainfrom
feat/muse-stage2

Conversation

@chaodu-agent

Copy link
Copy Markdown
Contributor

Stage 2 of the Muse gated passthrough (design: docs/design/muse-gated-passthrough.md, sections 3.4-3.9, 5, 6, stage 2 acceptance 1-29). Draft: not merged, not deployed. Branch base is 8006147; main has since gained two commits (#26, #27), so a rebase may be needed before merge.

What was built (one commit per FEAT)

  • FEAT-001 config, verdict, outcome codes (ap-core). Grant.path_patterns, hold allowed on passthrough grants (patterns only), hold limits in [passthrough], [approval] and [notify] tables, Snapshot::evaluate_verdict (hold beats allow), 12 new outcome codes with the 3.5 rows.
  • FEAT-002 hold table. hold::Table state machine (Pending, Approved, Denied, Expired, Abandoned, Superseded, Dropped), admission order (cooldown, dedupe/supersede, caps), 2 s approve confirm, credential-blind digest plus in-memory HMAC fingerprint, HoldRec audit and fallible audit writes.
  • FEAT-003 hold path in the pipeline. Content-type/encoding/credential/length checks, buffered body, held audit before insert, wait on decision/timer/caller drop, 423 deny, 410 expiry, 503 for superseded/dropped/shutdown, approved forward with two milestones, fallible forward_started, completed on the response stream. Refusals drain unread bodies first.
  • FEAT-004 approval plane. Separate loopback listener and router, one Basic credential (sha256, constant time), per-view single-use CSRF, escaped page and JSON API, harden() headers on every response.
  • FEAT-005 notifier. Notifier trait, ntfy implementation (own client, 5 s timeout, no redirects, fixed text, Click link, optional bearer), 0600 secret-file loader, one attempt per new entry, notify_failed audit line on failure.
  • FEAT-006 lifecycle and matrix. 1 s reload ticker, SIGTERM/SIGINT drain, black-box rows PT-18..PT-27, no-probe build matrix, CI greps for test hooks.
  • FEAT-007 leak suite and docs. Sentinel leak suite, refusal table generating all 26 codes through the real pipeline, README stage 2 section, generic runbook docs/runbooks/muse-stage2.md, design status note.

Review: two reviewers (opus, sol) ran three rounds; both LGTM at the head of this PR. Round 1 and 2 findings (shutdown vs approved-before-send, claim/forward_started atomicity, Content-Encoding strictness, idle/total deadline test, header-distinctness test) are fixed in the last two commits.

Acceptance mapping (design stage 2 list)

"Tested here" = covered by unit, in-process or black-box tests in this PR. "Deployment-only" = a half that cannot be proven without the real front, Muse or the network.

# Item Status
1 Not forwarded until approval Tested here (unit + matrix)
2 Unchanged request Tested here (Expect on the direct path only)
3 Verbatim response Tested here
4 Deny sends nothing Tested here
5 Expiry Tested here
6 Unavailable rows Tested here (SIGTERM row in matrix)
7 Single execution Tested here
8 Disconnect a/b Tested here (direct path, pause hook)
9 kill -9 while held Tested here (matrix)
10 kill -9 after approve Tested here (matrix, injected pause)
11 Approval plane unreachable from caller path Code half tested here; network half deployment-only
12 No sentinel leak Tested here (leak suite + matrix PT-27)
13 Caller key stripped Tested here
14 Bounds Tested here
15 Body rules Tested here
16 Audit milestones Tested here (milestone definition: see deviations)
17 Upstream failure boundary Tested here
18 Denied large POST readable Direct path tested here; through the front deployment-only
19 Disconnect through the front Direct path tested here; through the front deployment-only
20 Dedupe/retry Tested here (notification points at the first entry; see deviations)
21 Reload drops holds Tested here
22 Approval page Tested here
23 Cooldown Tested here
24 Probe absent Tested here (test + CI release grep + no-probe matrix)
25 Deadlines Tested here
26 SIGTERM during approved forward Tested here (matrix)
27 Refusal table Tested here (outcome rows + all 26 codes through the pipeline)
28 Framing/boundary repeat Tested here (no-probe matrix: PT-12n, PT-13n)
29 Audit failure on writes Tested here

Evidence (run on the build host, from the commit messages)

Final head sequence (round 3): cargo fmt --check clean; clippy -D warnings clean on workspace all-targets, stage1-probe, matrix-upstream; cargo test --workspace ok (ap-proxy lib 195); stage1-probe lib tests 199 ok; release binary has none of __ap_probe, __ap_test_panic, AP_TEST_UPSTREAM_CA, AP_TEST_HOLD_PAUSE; ap-egress has no ap-broker dependency; stage 1 matrix 41/41; matrix_passthrough test ok; passthrough.py 25/25 for the default build (28/28 with --noprobe-bin: 25 default + 3 no-probe rows).

Earlier counts: ap-core 189-192 tests; ap-proxy lib 111 (hold table), 137 (hold path, 26 new), 174 (approval, 38 approval tests), 187 (notifier, 13 notify tests), 188-195 later. Black-box rows grew from 16 (stage 1) to 24 (+3 no-probe).

Spike results recorded in the FEAT-003 commit: hyper drops the handler future on peer close, and no request byte leaves before forward_started, so neither fallback in the plan was needed.

CI (ci.yml) is workflow_dispatch only; the sequence above was run by hand, not by Actions.

What is not claimed

  • Exactly-once delivery. The duplicate-delivery window (forwarded, response lost, Muse retries, a human approves again) is stated in the runbook.
  • Resistance to a compromise of the Muse platform itself.
  • WebAuthn or any phishing-resistant approver authentication; approval is one Basic credential plus CSRF.
  • Network ACL isolation of the approval plane. The code keeps it on its own loopback listener; reachability is a deployment property.
  • Through-the-front behaviour (acceptance 11 network half, 18, 19): there is no real front or Muse in CI. These need the post-deploy measurement.
  • Hold window versus helper timeout, and removal of the old connector, are deployment prerequisites, not enforced in code.

Flagged deviations from the design

  1. Supersede does not send a second notification; the old id's page shows a superseded banner and a link to the newest entry (the notifier interface has one method).
  2. An approval path or probe on the public router answers the existing unknown-route refusal (423 route_unknown), not 404. Tests assert no route and zero upstream hits.
  3. Milestone 1 is the first poll of the request body stream, not a socket-level hook, because reqwest pools connections.
  4. Policy file removed while holds are pending: pending holds answer 503 dropped_on_reload.
  5. Non-UTF-8 body is shown lossy with a visible banner; no new refusal.
  6. An empty held body is sent chunked because hyper never polls a zero-length body.
  7. After shutdown closes the table, an approved request that has not yet claimed its start is cancelled (503 shutdown, nothing sent); one that has claimed runs to its end.

Nothing here contains hostnames, addresses, logins, keys, tokens or topics; the runbook is generic.

…ew outcome codes

Config: Grant.path_patterns (paths optional, one required), hold allowed on
passthrough grants with path_patterns only, [passthrough] hold limits,
[approval] and [notify] tables with validation. Policy: Verdict and
Snapshot::evaluate_verdict (whole-path segment match, hold beats allow).
Codes: HumanDenied, Expired, ContentType, ContentEncoding, CredentialMissing,
TableFull, IdentityCap, Cooldown, Superseded, Shutdown, DroppedOnReload,
AuditUnavailable with the design 3.5 outcome rows.

Verified on macmini: cargo fmt --all --check ok; cargo clippy --workspace
--all-targets -D warnings ok; cargo test -p ap-core 189 passed;
cargo test --workspace all ok (sidecar rendering tests unchanged).
…udit

Library only, no pipeline wiring (design 3.4 steps 4-8, 3.9).

- hold::Table: admit (cooldown, dedupe/supersede, caps; audit persist
  runs before any change), approve with 2 s confirm oneshot, deny,
  expire, abandon, drop_identities_missing, drop_all, drain_pending,
  view. Every row of the approve table is an ApproveResult. Cooldown
  starts only on deny/expire. Hand-written Debug on everything that
  holds headers, bodies or the fingerprint.
- hold::digest: length-prefixed encoding; credential-blind audit digest
  (sha256) and per-process HMAC-SHA256 equality fingerprint.
- ap-core: HoldRec with a fixed key set; ap-proxy AuditSink gains
  try_write_line/try_write_hold (Err on write or flush failure) and a
  best-effort write_hold.
- ap-proxy deps: hmac, sha2, getrandom (normal), tokio test-util (dev).

Verified on macmini (cargo target on the RAID volume):
- cargo fmt --all --check: ok
- cargo clippy --workspace --all-targets -- -D warnings: ok
- cargo clippy -p ap-proxy --features stage1-probe --all-targets
  -- -D warnings: ok
- cargo test -p ap-proxy hold::: 38 passed
- cargo test --workspace: all suites passed (ap-proxy lib 111 passed)
A hold grant now buffers the request, parks it in the hold table and
forwards it only after a human approves it (design 3.4, 3.5, 3.9).

- passthrough/hold_path.rs: content-type, content-encoding, credential,
  declared-length and buffered-body checks; admission with the fallible
  `held` audit write; wait on decision, hold timer or caller drop (guard
  moves Pending to Abandoned); deny 423, expiry 410, superseded, dropped
  and shutdown 503; approved forward with two milestones, fallible
  `forward_started`, `completed` on the response stream, no synthetic
  answer after a reset.
- forward: buffer_body, drain_body, held client (HTTP/1.1, no idle pool).
- refusals after caller auth drain the unread body first (skipped for
  Expect: 100-continue), so a denied 1 MiB POST reads its 423.
- PtApp gains the hold table, a notifier slot (None) and test pause gates
  (cfg(test) or matrix-upstream; AP_TEST_HOLD_PAUSE_MS only under the
  feature). notify.rs holds the trait only.

Spike results: hyper drops the handler future on peer close, and no
request byte leaves before forward_started, so neither plan fallback
(decisions 5 and 6) was needed. An empty held body is sent chunked
because hyper never polls a zero-length body.

Verified on macmini: cargo fmt --check; clippy -D warnings (workspace
all-targets, stage1-probe, matrix-upstream+stage1-probe) clean; cargo
test --workspace ok (ap-proxy lib 137, 26 new hold tests);
ap-proxy --features stage1-probe --lib ok (141); stage 1 black-box
matrix 16/16 and matrix_passthrough test ok.
A second loopback listener (approval.listen) serves the approval API and
page (design 3.6). It is its own socket, router and credential: the public
router mounts no /pending route, the caller key is refused here and the
approver credential is refused on the public listener.

- listener/approval.rs: hyper http1 accept loop, 16 connections, 10 s header
  read, 16 KiB header buffer. run_passthrough binds it only when [approval]
  exists and serves it next to the public listener (either stopping ends the
  process).
- approval/auth.rs: one Basic user, sha256 of the password compared in
  constant time, one Authorization header only, 250 ms wait before a 401
  with the Basic realm.
- approval/csrf.rs: random per-view token bound to the entry id, single
  use, 4 per entry and 256 in total, dies with the entry or hold_secs.
- approval/{mod,page}.rs: GET /pending, GET /pending/<id> (HTML or JSON on
  Accept), POST /pending/<id>/approve|deny with a form or JSON csrf field
  and a 1 KiB body limit; ApproveResult/DenyResult map to {"result"} with
  200 only for success; the approver name goes into the audit transition.
  Pages escape everything, carry no script or style, show credential
  headers as present and the body as escaped text with a banner when not
  UTF-8, and a superseded entry shows a banner, a link to the newest id and
  disabled buttons. harden() adds the six headers to every response.
- hold::Table::list() (admission order), digest::random_hex made pub,
  base64 is now a normal dependency of ap-proxy.

Verified on macmini: cargo fmt --all --check; clippy -D warnings
(workspace all-targets, stage1-probe, matrix-upstream+stage1-probe) clean;
cargo test --workspace ok (ap-proxy lib 174); cargo test -p ap-proxy
approval ok (38 tests: headers on 200/401/404/405/413/400/403, realm,
CSRF missing/reused/wrong entry, script body escaped, no credential in
page or JSON, concurrent HTTP approves = one success + one upstream
request, approve after each state, cross-credential refusals both ways,
no /pending route on the public router); ap-proxy --features
stage1-probe --lib ok (178); matrix_passthrough (16 stage 1 rows) ok.
Notifier trait, NtfyNotifier (own client, 5 s timeout, no redirects, POST
base/topic, fixed text body, Click header, optional Bearer), secret-file
loader (opened file must be regular with no group/other bits), and
MockNotifier for tests. PtApp announces each new distinct hold entry once
after insert (not on supersede); failure writes one notify_failed audit
line and leaves the entry untouched. run_passthrough builds the notifier
from [notify]; absent means none.

Verification on macmini (cargo only there):
- cargo fmt --all --check: ok
- cargo clippy --workspace --all-targets -D warnings: ok
- cargo clippy -p ap-proxy --all-targets --features stage1-probe: ok
- cargo clippy -p ap-proxy --all-targets --features matrix-upstream,stage1-probe: ok
- cargo test --workspace: all pass (ap-proxy lib 187)
- cargo test -p ap-proxy notify: 13 passed
…trix rows

- run_passthrough: 1 s policy reload ticker (policy gone drops every hold,
  removed identities drop theirs) and SIGTERM/SIGINT drain: stop accepting,
  graceful close of connections, pending holds answered 503 shutdown, approved
  forwards run to the end or request_deadline_secs, exit 0.
- listener::public::serve_public_until with a watch-based shutdown.
- tests/matrix/passthrough.py: rows PT-18..PT-25 (approve, deny, expiry via the
  real approval listener; kill -9 held and inside AP_TEST_HOLD_PAUSE_MS; SIGTERM
  held and approved; reload drop) and, with --noprobe-bin, PT-26, PT-12n, PT-13n.
- matrix_passthrough.rs: ROWS 24 (+3 with AP_MATRIX_NOPROBE_BIN); matrix.rs
  finds the binaries through CARGO_BIN_EXE.
- ci.yml: clippy with matrix-upstream, AP_TEST_HOLD_PAUSE release grep,
  no-probe matrix build in target/noprobe and both matrix passes.

Verified on the build host: cargo fmt --check ok; clippy workspace, stage1-probe
and matrix-upstream+stage1-probe with -D warnings clean; cargo test --workspace
ok (ap-core 192, ap-proxy lib 188 incl. the new reload tick test); stage1-probe
lib tests ok (192); release build ok and the release auth-proxy has none of
__ap_probe, __ap_test_panic, AP_TEST_HOLD_PAUSE, AP_TEST_UPSTREAM_CA; ap-egress
does not depend on ap-broker; cargo test --features matrix-upstream --test
matrix ok; tests/matrix/matrix.py 41 PASS of 41; matrix_passthrough cargo test
ok with and without AP_MATRIX_NOPROBE_BIN; passthrough.py 24 PASS of 24
(--bin only) and 27 PASS of 27 (with --noprobe-bin).
Adds leak_tests.rs (sentinel sweep over every hold outcome, caller-key
positions, and a table generating all 26 codes of design 3.5 through the
real pipeline), black-box row PT-27 (approval page/list, panic while a
hold exists, file and log scan), README stage 2 section, the stage 2
runbook, and the design status note with implementation deviations.

Verified on macmini (OpenSSL 3 first on PATH for the python drivers):
fmt --check, clippy x3 (-D warnings), cargo test --workspace, probe lib
tests, release build + hook greps (no __ap_probe, __ap_test_panic,
AP_TEST_HOLD_PAUSE, AP_TEST_UPSTREAM_CA), ap-egress dep check, matrix
test + matrix.py 41/41, matrix_passthrough test, passthrough.py 28/28
(25 default rows + 3 no-probe rows). All passed. macmini root disk had
3.0 GiB free at the time.
Run on macmini (3.0 GiB free on /), round 1, HEAD ada1b03:
- fmt --check clean; clippy -D warnings clean (workspace all-targets, ap-proxy stage1-probe, matrix-upstream+stage1-probe)
- cargo test --workspace all ok; ap-proxy --features stage1-probe --lib 195 passed
- release build: no __ap_probe, __ap_test_panic, AP_TEST_UPSTREAM_CA, AP_TEST_HOLD_PAUSE in auth-proxy; ap-egress does not depend on ap-broker
- cargo test --test matrix ok; matrix.py 41 PASS of 41
- cargo test --test matrix_passthrough ok; passthrough.py 25 PASS of 25
- note: matrix scripts need OpenSSL 3 (not macOS LibreSSL) first on PATH
…ted; allowed-route deadline test

Review round 1 findings (sol, MEDIUM x2):
- Table::claim_start takes the same lock as drain_pending. The approved
  forward claims at the first body poll, before forward_started is written;
  if shutdown closed the table first, nothing is sent, the approve call gets
  approved_but_abandoned, the audit shows abandoned_after_approve with code
  shutdown, and the caller gets 503 shutdown. A request that claimed first
  runs to its end. PT-24 pause case now expects 503 shutdown and zero
  upstream requests; the streaming case still proves a started request
  completes. New unit test shutdown_between_approve_and_the_send_sends_nothing.
- New unit test allowed_requests_are_closed_at_the_idle_and_total_deadlines
  (idle after head, trickle past the total deadline, no head at all; three
  allow/upstream_reset audit lines).

Run on macmini, round 2 (OpenSSL 3 first on PATH for python drivers, /usr/bin/python3):
fmt --check clean; clippy -D warnings clean (workspace all-targets, stage1-probe, matrix-upstream);
cargo test --workspace ok (ap-proxy lib 193); probe lib tests 197 passed;
release build: no __ap_probe, __ap_test_panic, AP_TEST_UPSTREAM_CA, AP_TEST_HOLD_PAUSE;
ap-egress has no ap-broker dependency; cargo test --test matrix ok; matrix.py 41 PASS of 41;
cargo test --test matrix_passthrough ok; passthrough.py 28 PASS of 28 (with --noprobe-bin).
Root disk had 3.2 GiB free.
…er the table lock; stricter identity encoding; header-distinctness test

Round 3 fixes for round-2 findings:
- MEDIUM: Table::claim_start now runs the closed check and the forward_started audit write
  under the same lock drain_pending takes, so shutdown cannot land between them. New test
  pauses inside the claim (after the closure check, before the audit write), starts the drain
  and shows it waits, then the claim completes as a whole.
- MEDIUM: pipeline test that a changed ordinary header (x-note) gives two pending ids, two
  notifications, no supersede, and independent decisions.
- LOW: Content-Encoding must be absent or exactly one value equal to identity; empty
  elements, repeats and duplicate headers refuse content_encoding (cases added).

Verified on macmini (OpenSSL 3 first on PATH, /usr/bin/python3): fmt --check clean; clippy
-D warnings clean (workspace all-targets, stage1-probe, matrix-upstream); cargo test
--workspace ok (ap-proxy lib 195); stage1-probe lib 199 ok; release hook greps 0 for
__ap_probe, __ap_test_panic, AP_TEST_UPSTREAM_CA, AP_TEST_HOLD_PAUSE; ap-egress has no
ap-broker dependency; matrix test + matrix.py 41/41; matrix_passthrough test ok;
passthrough.py 25/25.
Conflicts (both in the passthrough matrix, no source conflicts):
- tests/matrix/passthrough.py: main added PT-18 and PT-19 (canonicalization
  rows) where stage 2 had PT-18..PT-25 and PT-26/PT-27. Both kept; the stage 2
  rows (and their functions) are renumbered PT-20..PT-27, PT-28 (no-probe),
  PT-29 (sentinel sweep). main's canon_* helpers and rows are unchanged.
- crates/ap-proxy/tests/matrix_passthrough.rs: ROWS 25 -> 27 (main's two rows
  added to stage 2's count); ROWS_NOPROBE stays 3.
Also: leak_tests.rs and the runbook point at the renumbered rows; new test
canonicalization_attack_forms_are_refused_before_a_hold_exists.

Checked on the merged tree: fmt, clippy (default, stage1-probe,
matrix-upstream+stage1-probe), cargo test --workspace, sidecar matrix 48/48,
passthrough matrix 30/30, 4 fuzz targets x 120s with 0 crashes, release hook
greps clean, deploy/k8s validator and its tests pass.
@chaodu-agent

Copy link
Copy Markdown
Contributor Author

Merged main into this branch (merge commit 056c358, no rebase). Two conflicts, both in the passthrough matrix: tests/matrix/passthrough.py (main's new PT-18 and PT-19 collided with the stage 2 PT-18..PT-25; both kept, stage 2 rows renumbered PT-20..PT-27, no-probe row PT-28, sentinel sweep PT-29) and crates/ap-proxy/tests/matrix_passthrough.rs (row count 25 -> 27). No source conflicts: main's canonicalization runs before the grant check, so the hold path sees the same canonical path that is matched, stored and forwarded. Added a regression test that layered encodings, ..%3b, mixed-case and hex-tail IP hosts are refused before a hold exists (empty table, no notification, no upstream). Checks on the merged tree: fmt, clippy (3 feature sets), cargo test --workspace, sidecar matrix 48/48, passthrough matrix 30/30, 4 fuzz targets x 2 min with 0 crashes, release hook greps clean, k8s validator passes.

…old bypass

- Refuse a route-relative path or query that repeats the authenticated caller key (layered
  percent-decoding, case-insensitive, fail-closed) before the Trail has a path, a hold exists or
  the upstream is called: caller_key_ambiguous.
- Passthrough refuses percent-escapes of RFC 3986 unreserved bytes (path_ambiguous_passthrough),
  so the matched form equals the sent form. The sidecar keeps accepting them (matrix row C1-3).
- Policy load refuses an allow grant that overlaps a hold pattern of the same identity, route and
  method; the matcher denies the trailing-slash spelling of a held path; hold still wins.
- RFC 3986 oracle in the differential test and the canon_path fuzz target; regression forms per
  pattern position; two matrix rows (PT-30, PT-31, 29 rows plus 3 without the probe).
- Hold canonicalization test asserts the refusal code per form and sends path-form requests
  without the key header.

Verified on the build host: fmt, clippy x3, workspace tests, probe lib tests, sidecar matrix 48/48,
passthrough matrix 32/32, four fuzz targets 180 s each with no crash, release hook greps, k8s validator.
@chaodu-agent

Copy link
Copy Markdown
Contributor Author

Review round 5, pushed as 4890dfa. These are my own review findings on the head 056c358.

1. MEDIUM, caller key repeated in the routed path (POST /ap/{key}/discord/hold/{key} was held, audited, shown and sent upstream).
Fixed in passthrough.rs, canon::echoes_caller_key. After the key authenticates, the route-relative path and the query are searched for it: raw, then after each percent-decode layer to a fixed point (hex in either case, same by-value decoding as path_ambiguous), case-insensitive, matching the 64 hex digits or any well-formed apk_<64 hex>. Still decodable past the layer limit counts as found. A hit is caller_key_ambiguous (400) before the Trail has a path, before a hold exists, before a notification and before the upstream. Covers the header form and the path form, the hold route and the allow route. Tests: unit table of spellings (canon_regression), an end-to-end test (empty hold table, no held/forward_started, no notification, no upstream request, key absent from audit and bodies), matrix row PT-30.

2. MEDIUM, %6D in a literal segment escaped a hold pattern and went out unheld through an overlapping allow prefix.

  • Decision: the passthrough listener now refuses a percent-escape of an RFC 3986 unreserved byte (A-Z a-z 0-9 - . _ ~) in the path, at any decode layer, as path_ambiguous (canon::path_ambiguous_passthrough). I chose refusal over decode-then-forward because the project rule is to reject ambiguous input and decoding would rewrite the forwarded bytes and need a second canonical check on the result (%2%41 decodes into a new escape).
  • Scope: refusing in the shared path_ambiguous broke matrix row C1-3, which forwards /v1/%41 unchanged on the sidecar. The sidecar has no hold verdict and no grant precedence (an unmatched spelling is only no_grant), so I kept that row as is and applied the rule on the passthrough pipeline only. The fallback of decoding was therefore not needed.
  • Query: not refused. Policy never matches the query, it is stored, shown and forwarded as one raw value, so the matched form and the sent form already agree and spellings cannot change a verdict. Refusing there would only break clients that over-encode.
  • Engine: hold already won over allow; verdict_hold_beats_allow_in_either_grant_order now covers an overlapping allow in both orders on a snapshot built without the loader check. The matcher also denies (no_grant) the trailing-slash spelling of a held path whatever allow grants exist.
  • Loader: policy load now fails with a clear message when an allow grant (prefix or pattern) of the same identity, route and method overlaps a hold pattern, including the trailing-slash spelling. Fail closed was chosen over a warning because the overlap is exactly what the bypass needed. The runbook and design text now say so. Tests: overlapping and disjoint tables in policy.rs.

Oracle (family closed). tests/common/invariants.rs gains an RFC 3986 normaliser written from the RFC and sharing no code with canon.rs or policy.rs (decode unreserved escapes and %25 to a fixed point, upper-case remaining hex, remove dot segments, collapse empty segments, drop a trailing slash). For any request whose normalised form matches a hold pattern, the gate (canonicalization, then verdict) must hold or refuse, under two policies: the shipped shape and an engine-only shape where an allow prefix / covers everything. A seeded generator (60,000 probes: every pattern, literal and wildcard segments, first and last position, either hex case, layered escapes, dot and empty segments, trailing slash) runs in canon_differential; the same builder is driven by input bytes in the canon_path fuzz target. Named regressions cover %6D, %4D, %2D, %2E, %7E, layered forms, per pattern position, for the hold path and the allow path. Matrix row PT-31 does the same over the real binary. The sidecar and passthrough matrices still pass: 48/48 and 32/32 (29 rows plus 3 without the probe build; ROWS is now 29).

3. LOWs.

  • Weak per-row regression test: fixed. Each form asserts its body code (path_ambiguous, host_rejected), path-form requests are sent without the key header, and the paths are ones a hold pattern would match, so a bypass would be held and not no_grant. The stale comment is gone.
  • Caller key in its own path: fixed by item 1.
  • Build host named in earlier commit bodies: skipped. Those commits are pushed and rewriting them needs a force push. The new commit says "build host". Leave the lines out of the squash message.

Checks on the build host: fmt, clippy (default, stage1-probe, matrix-upstream,stage1-probe) with -D warnings, cargo test --workspace, probe lib tests, release hook greps (0 hits), ap-egress without ap-broker, matrix cargo targets, both Python matrices, k8s validator and its tests, and the four fuzz targets for 180 s each with 0 crashes.

The PR stays a draft.

Conflicts: crates/ap-proxy/src/lib.rs (keep both mod netguard and mod notify),
crates/ap-proxy/tests/matrix.rs (doc comment: both-binaries wording plus the Cargo layout note).
Docs: netfilter runbook states how the gate and holds compose.
…sthrough 32/32; fmt, clippy x3, tests, fuzz x4 clean on macmini)
@chaodu-agent

Copy link
Copy Markdown
Contributor Author

Merged main (#30, netfilter self-check) into this branch with a normal merge commit; head is now 6a14134.

Conflicts, both mechanical:

  • crates/ap-proxy/src/lib.rs: kept both module declarations (netguard from main, notify from this branch).
  • crates/ap-proxy/tests/matrix.rs: merged the bin_dir doc comment; same code on both sides.

Composition: the netfilter gate runs only in the sidecar profile. Holds, approval listener and notifier exist only in a passthrough-only config, and that config refuses any --netfilter-* flag (exit 2, already tested). The two never share a process, so nothing can be held or approved while the check is failing; passthrough is unaffected. Documented in docs/runbooks/netfilter-selfcheck.md. Matrix row count in the stage 1 runbook updated to 59.

Checks on the merged tree: fmt, clippy (3 feature sets), workspace tests, sidecar matrix 59/59, passthrough matrix 32/32, k8s validator and its 58 tests, release hook greps, and 4 fuzz targets (2 min each) all clean.

… approve, one route per authority

- notifier and upstream clients: no_proxy(), so HTTP_PROXY/HTTPS_PROXY/ALL_PROXY (either case)
  and system proxies never carry the topic, bearer, approval link or a request. Tests set all six
  variables to a capture listener, with a control client proving the listener sees a request when
  the variables are honoured.
- reload_tick re-evaluates every pending hold against the new policy and drops those whose
  identity, route, method or path no longer yields hold (dropped_on_reload). Approve re-checks
  the current policy under the table lock and answers policy_changed (410) if the grant is gone.
- loader refuses two passthrough routes with the same host and port, since the upstream resource
  is the authority and path, not the route name.
- docs: design and runbook text for the three rules.

Checks on this commit: fmt, clippy (default, stage1-probe, matrix-upstream+stage1-probe),
cargo test --workspace, sidecar matrix 59/59, passthrough matrix 32/32, validator and its 58
tests, release hook greps 0 hits. 18 mutations of the guarantees each fail a named test.
@chaodu-agent

Copy link
Copy Markdown
Contributor Author

Review round 6 follow-up. These are my own review findings on head 6a14134.

1. MEDIUM, the notifier honoured proxy environment variables. Fixed. NtfyNotifier now builds its client with .no_proxy() (this also turns off system proxy detection), explicit connect and total timeouts, and no redirects. The upstream clients (forward::client_builder, which the forwarder and the held-request client both use) got .no_proxy() too, with no setting that turns it off. These are the only reqwest clients in the workspace (spike/exp2 is outside the workspace and is not built or shipped). Tests: notify::tests::the_notifier_ignores_every_proxy_environment_variable and the_upstream_clients_ignore_every_proxy_environment_variable set HTTP_PROXY, HTTPS_PROXY, ALL_PROXY and the lowercase forms to a local capture listener and assert it receives nothing. The first has a control client that does reach the listener, so the test cannot pass vacuously. Env access is serialised by a lock and restored.

Why this was reported fixed before. The fix never existed. git log --all -S'no_proxy' finds no_proxy only in the early spike commits and in an unrelated test name; it was never in notify.rs. The finding was raised in rounds 1, 2 and 3, and the round summaries listed it as handled, but no commit changed the client builder and no test covered it. So it was a reporting error, not a fix that was lost in a merge or rebase. The sweep below exists because of this: each guarantee now names a test, and I broke each guarantee on purpose to check that the test fails.

2. Removing a hold grant on reload kept its pending holds, and an approve could run it. Fixed.

  • reload_tick now re-evaluates every pending hold against the new policy (still_held: the route exists and the identity's grants still give hold for that method and route-relative path). Anything else is dropped: 503 unavailable, audit dropped_on_reload, entry state Dropped, nothing sent. An invalid or missing policy still drops everything.
  • Approve re-checks too. The approval listener reads the policy in force and calls Table::approve_if, which asks still_held under the table lock before taking the entry. If the grant is gone the entry is dropped the same way and the approve answers policy_changed (HTTP 410).
  • Tests (hold_tests): removing_the_hold_grant_on_reload_drops_its_pending_hold, removing_the_route_on_reload_drops_its_pending_hold, removing_the_identity_on_reload_drops_its_pending_hold, narrowing_the_hold_pattern_on_reload_drops_the_hold_it_no_longer_covers, a_method_removed_from_the_hold_grant_drops_the_hold, an_invalid_policy_replacing_the_file_fails_closed_for_holds_and_approvals, an_approve_racing_a_reload_does_not_forward, and the positive control a_hold_that_the_new_policy_still_holds_survives_and_can_be_approved. Over HTTP: approval::tests::approving_after_the_hold_grant_is_removed_is_refused_and_sends_nothing.
  • Not covered: a route whose host or port changes under the same name keeps its holds, and an approved request goes to the host it was held for. The owner reviewed that request. Say so if you want those dropped as well.

3. Two passthrough routes on one host and port bypassed the hold. Fixed in the loader by the simpler option: two passthrough routes with the same host and port are refused (host compared lowercased with a trailing dot removed; the default port is the same number). Hosts must already be canonical, so uppercase and trailing-dot spellings are refused earlier by the host rule. Existing policies, the matrices and the k8s manifests have no such pair. Tests in config.rs: two_passthrough_routes_on_one_host_and_port_are_refused (the reproduced case and the explicit default port), host_spellings_of_one_authority_are_still_refused, passthrough_routes_on_different_ports_or_hosts_load.

4. Guarantee sweep. Each row was broken on purpose in a scratch copy; the named test failed every time (a test not run for one mutation is noted).

Guarantee Test that proves it Mutation that it catches
Hold wins over allow, either grant order policy::tests::verdict_hold_beats_allow_in_either_grant_order allow returns first: fails
Allow cannot overlap a hold pattern policy::tests::loader_refuses_an_allow_grant_that_overlaps_a_hold_pattern (round 5, unchanged)
One route per host and port config::tests::two_passthrough_routes_on_one_host_and_port_are_refused check disabled: fails
Audit failure refuses a held write hold_tests::a_failing_sink_before_the_hold_refuses_the_write_and_lets_reads_pass persist error ignored: fails
Cooldown after deny or expiry hold::tests::deny_starts_a_cooldown_that_ends, expiry_starts_a_cooldown, hold_tests::deny_sends_nothing_and_a_cooldown_follows cooldown never starts: 4 tests fail
Identical retry supersedes, one approval makes one request hold_tests::an_identical_retry_supersedes_and_one_approval_makes_one_request, hold::tests::identical_retry_at_a_cap_supersedes dedupe disabled: 3 tests fail
Holds are dropped on reload when the grant, route, method, pattern or identity is gone, or the policy is invalid the seven reload tests in item 2 reload keeps all holds: 4 fail; reload checks identity only: 4 fail
Approve re-checks the policy an_approve_racing_a_reload_does_not_forward, approval::tests::approving_after_the_hold_grant_is_removed_is_refused_and_sends_nothing re-check removed in the table: fails; removed in the listener: fails
Notifier payload is the fixed text and a link notify::tests::posts_the_fixed_text_with_click_and_bearer, hold_tests::notify_once_per_distinct_entry_with_only_id_text_and_link request id added to the body: fails
Notifier and upstream clients ignore proxy variables, notifier never follows redirects the_notifier_ignores_every_proxy_environment_variable, the_upstream_clients_ignore_every_proxy_environment_variable, a_redirect_is_not_followed .no_proxy() removed from either: fails
Approval page headers on every status approval::tests::every_status_carries_the_six_headers CSP header removed: fails
Caller key never in any output leak_tests::a_caller_key_in_every_position_stays_out_of_the_stream, hold_tests::caller_key_repeated_in_the_path_or_query_is_refused_before_anything_is_built, leak_tests::no_sentinel_reaches_any_surface_on_any_hold_path key-echo check disabled: fails
Fail closed on the netfilter check netguard::tests::starts_closed_and_opens_only_when_both_checkers_are_healthy and the gate tests; tests::passthrough_config_with_the_netfilter_check_exits_with_status_2 gate starts open: 5 tests fail. Passthrough exit-2 check removed: the test hangs on the running proxy and was killed by the 200 s harness timeout, so it fails, but as a hang and not an assertion
Shutdown behaviour hold::tests::drain_answers_shutdown_and_closes_admission, hold_tests::shutdown_between_approve_and_the_send_sends_nothing, shutdown_racing_the_start_claim_cannot_split_claim_and_forward_started; matrix PT-25 and PT-26 closed check removed: 2 fail; drain answer removed: 1 fails

No guarantee in the list was found without a test. Items 1 and 2 were the two that had none.

Other LOWs. The commit-message note about the build host: no history rewrite and no new mention (the new commit says "build host"); leave those lines out of the squash message.

Checks on this head (build host, internal disk was low, so everything ran on the RAID volume): cargo fmt --check; clippy -D warnings for default, stage1-probe and matrix-upstream,stage1-probe; cargo test --workspace (ap-proxy lib 237 with stage1-probe); release build and hook greps (0 hits); ap-egress has no ap-broker; matrix cargo targets; sidecar matrix 59/59; passthrough matrix 32/32 (no matrix rows were added, so the counts stay); k8s validator and its 58 tests; four fuzz targets, 180 s each, 0 crashes (2.8M, 19.0M, 30.2M and 13.9M runs). The diff has no private identifiers (grepped).

The PR stays a draft.

…n at the start claim; holds are bound to their upstream

- approve_checked reads the policy inside approve_if's critical section; the start claim
  re-checks still_held (and the recorded upstream) under the same lock before forward_started.
  A reload landing before the claim yields an approved send under the current policy or
  policy_changed (410) with caller 503 dropped_on_reload and no request byte sent.
- HeldRequest records upstream (scheme, host, port, keep_auth_headers) and the policy generation;
  still_held compares them, so a host or port change, a rename or other kept headers drops the hold
  at reload and refuses the approve. The page shows 'Sent to'; the held audit record carries
  upstream and policy_generation.
- The proxy-variable tests run in a child process, so no test mutates the shared environment.
- Tests: interleavings at five injection points (revoke and keep), the reported schedule, host,
  port, rename, kept-header, unchanged and swap cases.
Checks: fmt, clippy x3, cargo test --workspace (ap-proxy lib 248), release hook greps clean,
sidecar matrix 59/59, passthrough matrix 32/32, k8s validator, fuzz x4 x 180 s 0 crashes.
@chaodu-agent

Copy link
Copy Markdown
Contributor Author

Review round 7 follow-up. These are my own review findings on head 6f3e678.

1. MEDIUM, an approve could use a stale policy snapshot and forward after the hold grant was removed. Fixed.

  • approval::approve_checked (used by the listener) now reads the policy inside the callback that Table::approve_if runs under the table lock, in the same step that takes the entry out of the table. The snapshot taken before the call is gone.
  • The start claim re-checks. Immediately before forward_started and the first upstream byte, the claim reads the policy again under the same lock and re-evaluates still_held. If it no longer yields hold, nothing is sent: the entry is dropped (503 dropped_on_reload to the caller with the decision body, audit dropped_on_reload), and the approve answers policy_changed (410). The upstream connection may already be open at that point, but no request byte has been written.
  • The injection points are test-only (pause.rs, compiled for unit tests and matrix-upstream); the release-binary hook greps are clean. Tests, each run with a revoking change and with a hold-preserving change, and a reload tick racing the approve: a_revoked_grant_never_forwards_whenever_the_reload_lands and a_hold_that_stays_held_is_approved_under_the_policy_current_at_send_time, at five points (before the approve, inside the table lock before the policy read, inside the lock after the read, after the approve and before the send, inside the start claim). Every revoke case ends with no request recorded upstream, no forward_started, and the tick unable to run inside the critical section; every keep case ends with one approved request. The reported schedule is an_approve_that_read_the_policy_before_the_grant_was_removed_does_not_forward.

2. MEDIUM, a route whose host or port changed under the same name kept its holds and sent to the old authority. Fixed.

  • Each held entry records the upstream its route named when it was held (scheme, host, port, and the route's keep_auth_headers) and the policy generation. still_held compares the recorded upstream with the current route, so a host, port or kept-header change, a rename or a removal drops the hold at reload and refuses the approve (policy_changed). The same comparison runs at the start claim.
  • The approval page and JSON show "Sent to" (https://host:port). The held audit record carries upstream and policy_generation (the only records that do).
  • Tests: a_route_host_change_..., a_route_port_change_..., a_route_rename_..., a_change_to_the_routes_kept_auth_headers_... (each at reload and at approve), the positive control an_unchanged_authority_keeps_the_hold_and_it_goes_to_that_upstream, a_policy_swap_that_changes_the_host_and_back_is_judged_when_it_is_seen (seen while changed: dropped for good; never seen: the entry survives and goes to the authority the owner reviewed), a_held_request_records_its_upstream_in_the_held_record_and_the_view, and approval::page::tests::the_page_and_the_json_name_the_upstream_the_request_goes_to. Route removal is covered by the existing removing_the_route_on_reload_drops_its_pending_hold and the rename tests.

3. LOW, the proxy-variable tests changed the process environment while other tests ran. Fixed. Both tests now run in a child copy of the test binary (run_isolated), one test per process, and require that exactly one test ran and passed. The parent test binary never changes its environment, so no other test can observe it. The ENV_LOCK is gone.

4. Documentation and commit messages. The design sentence about the reload and approve race is now worded to match the behaviour (section 3.9), and the runbook describes the claim-time re-check and the recorded upstream. The commit-message note about the build host stands: leave those lines out of the squash message.

Guarantees added to the sweep (each broken on purpose in a scratch copy; the named test failed every time):

Guarantee Test that proves it Mutation that it catches
The approve reads the policy inside the table's critical section a_revoked_grant_never_forwards_whenever_the_reload_lands policy read before approve_if: fails (a reload ran inside the critical section)
The start claim re-checks the policy before the first upstream byte an_approve_that_read_the_policy_before_the_grant_was_removed_does_not_forward, a_revoked_grant_never_forwards_whenever_the_reload_lands claim re-check removed: both fail (request reaches the upstream)
An approval never goes to an authority the current policy does not name a_route_host_change_..., a_route_port_change_..., a_change_to_the_routes_kept_auth_headers_..., a_policy_swap_that_changes_the_host_and_back_... authority comparison removed: all four fail
Unchanged authority is not dropped an_unchanged_authority_keeps_the_hold_and_it_goes_to_that_upstream comparison inverted: fails
Rename and removal drop the hold a_route_rename_drops_the_hold_at_reload_and_at_approve still_held always true: fails (the route lookup and the grant verdict both refuse a rename, so removing only one layer is not enough)
The owner sees the destination the_page_and_the_json_name_the_upstream_the_request_goes_to, a_held_request_records_its_upstream_in_the_held_record_and_the_view "Sent to" row removed: fails; upstream left out of the held record: fails
The proxy-variable tests cannot disturb other tests the_notifier_... / the_upstream_clients_ignore_every_proxy_environment_variable (child process) .no_proxy() removed from client_builder: fails through the child

One finding of my own while testing: a reload that lands while the claim holds the connection open cannot stop the connection itself, only the request bytes. The tests therefore assert on requests recorded upstream, not on connection counts.

Checks on this head (build host, everything on the RAID volume): cargo fmt --check; clippy -D warnings for default, stage1-probe and matrix-upstream,stage1-probe; cargo test --workspace (ap-proxy lib 248 with stage1-probe, 2 child-process tests run through their parents); release build and hook greps (0 hits); ap-egress has no ap-broker; matrix cargo targets; sidecar matrix 59/59; passthrough matrix 32/32 (no matrix rows were added); k8s validator and its tests; four fuzz targets, 180 s each, 0 crashes (2.7M, 19.2M, 29.4M and 12.7M runs); every step of ci.yml run in order. The diff has no private identifiers (grepped).

The PR stays a draft.

chaodu-agent added a commit that referenced this pull request Nov 17, 2026
Action boundary at the first request byte, supported local storage with a
statfs check, secure directory and file checks, blocked-writer state machine,
immutable segments, secrecy allow-list, reader conclusions, readiness rules,
reordered test plan, new disk and DoS bound section, first stage cut to held
writes, open questions marked DECIDED or PROPOSED DEFAULT.
Verified: re-read PR #29 at e7818ad (admit, claim_start, approved) and Rust std
sync_data at rustc 0ef1bc386. Docs only, nothing built or run.
PolicyStore::current() returned the cached snapshot whenever the file's
(mtime, length) matched. A same-length rewrite with the mtime restored
therefore bypassed reload_tick, approve_if and still_holds. Reproduced on
macmini: a held POST /discord/hold/ok, pattern /hold/* changed to /deny/*,
mtime restored, approve returned Success and forwarded.

The store now reads the file's bytes on each check and compares them with
the bytes the snapshot was parsed from. The table critical section and the
approval-time read ordering are unchanged.

Regression: passthrough::hold_tests::
a_same_length_same_mtime_swap_that_removes_the_hold_grant_drops_it_at_approve
- before the fix (e7818ad): FAILED at hold_tests.rs assert_eq!
  left: Success, right: PolicyChanged
- after the fix: ok

Gates on macmini (rsync of the worktree, cargo in ~/work/pr29-digest-fix):
- cargo fmt --all --check: exit 0
- cargo clippy --workspace --all-targets -- -D warnings: exit 0
- cargo clippy -p ap-proxy --all-targets --features stage1-probe -- -D warnings: exit 0
- cargo clippy -p ap-proxy --all-targets --features matrix-upstream,stage1-probe -- -D warnings: exit 0
- cargo test --workspace: exit 0
- cargo test -p ap-proxy --features stage1-probe --lib: exit 0 (249 passed, 2 ignored)
run() parsed the policy text once, but PolicyStore::new read the file again
and stored that second read as the source of the startup Config. If the file
changed in between (for example a grant was revoked), current() saw the new
bytes match the cached source and kept returning the old policy.

PolicyStore::new now takes the startup text and uses it as Loaded.source. It
never re-reads the file for the initial source. The byte comparison on every
later read is unchanged. Every constructor that reaches PolicyStore::new
(PtApp::new, with_held_client, build, pipeline App::new) takes the text too.
App::new carries an allow for clippy::too_many_arguments because it now has 8
parameters.

Regression test: policy_store::tests::
startup_policy_is_not_replaced_by_a_file_changed_before_the_store_is_built.
It parses synthetic allow policy A, replaces the file with policy B that grants
a different path, builds the store with A's Config and text, and expects
Err(PolicyDenied) from current().

Before (8db9126 + test, 2-arg PolicyStore::new): FAILED on the assertion,
left Some(Ok(Allow)), right Some(Err(PolicyDenied)). Not a compile error.
After: passed.

Gates, run on macmini in ~/repo/auth-proxy-pr29, PATH=$HOME/.cargo/bin first.
Matrix gate also had Homebrew openssl@3 first on PATH and OPENSSL_DIR set.
Before: fmt pass; clippy default pass; clippy stage1-probe pass; clippy
matrix-upstream,stage1-probe pass; cargo test --workspace FAILED only on the
new test (245 passed, 1 failed); cargo test -p ap-proxy <new test> FAILED.
After:
  cargo fmt --all -- --check                                              pass
  cargo clippy --workspace --all-targets -- -D warnings                  pass
  cargo clippy --workspace --all-targets --features stage1-probe -- -D warnings  pass
  cargo clippy --workspace --all-targets --features matrix-upstream,stage1-probe -- -D warnings  pass
  cargo test --workspace                                                  pass (ap-proxy lib 246 passed, 2 ignored)
  cargo test -p ap-proxy startup_policy_is_not_replaced                  pass
All feature names exist at workspace level, so no -p substitution was needed.
@chaodu-agent
chaodu-agent marked this pull request as ready for review November 18, 2026 02:29
@chaodu-agent
chaodu-agent merged commit 20c0c45 into main Nov 18, 2026
5 checks passed
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.

1 participant