diff --git a/.crumb b/.crumb index 55dc2d8..c883d99 100644 --- a/.crumb +++ b/.crumb @@ -18,13 +18,13 @@ "children": [ { "digest": "201dae855791459ce55c9060c32e18e229b0006db8606289e44dfe7f412cf6c4", - "last_commit": "21c485c", + "last_commit": "a9c5dbb", "name": ".github", "purpose": "GitHub automation configuration" }, { - "digest": "6cce6e334f7479fb2ed4c460dc9d73a8700012cee6d9f17713b7f4a2c0d70cc4", - "last_commit": "016ace0", + "digest": "7ce1c68a26a852505622949aff766ec2de015bde1925e13a85c338e1261d2719", + "last_commit": "a9c5dbb", "name": "crates", "purpose": "Native Rust website crates" }, @@ -48,7 +48,7 @@ }, { "digest": "c4e1b4fdfa83e5b9685aab9883ee681e3f5c1042baf104601afd85712e17b45c", - "last_commit": "21dc7ea", + "last_commit": "a9c5dbb", "name": "om/hive-render", "purpose": "Seeded Omega edge rendering of validated canonical Hive JSON with fail-closed escaping and deter" }, @@ -66,26 +66,26 @@ }, { "digest": "26ca4e27b534a756de12becc93659d8c62a3564ff91f26a4f77ef262f3fd8014", - "last_commit": "016ace0", + "last_commit": "a9c5dbb", "name": "public", "purpose": "Static public website assets" }, { - "digest": "d19bb51f24d3c0b551f4664adba478bf03fed9ac1585a80f23f7fe8f34466813", - "last_commit": "f914851", + "digest": "b77336127516b827d0e7a19a214d6bd15665865f7fd2f2d4eb323c6eca9c3893", + "last_commit": "e391556", "name": "scripts/allen/science", "purpose": "Isolated compute-only Allen tools and versioned glass-pane protocol; temporary host transport ar" } ], - "children_root": "sha256:90d7338e10fd44cd0baf72b6489c260dae36bc5987a2bf85bc3ccf04a73aa829", - "compiled_at": "2026-10-29T17:40:49Z", + "children_root": "sha256:664e2c949312cc4612b619622deba86ba26f89887ee425d1e462c21b3dd441fe", + "compiled_at": "2026-10-30T02:44:24Z", "compiler": "crumb-compile/1", - "digest": "sha256:242708c27090a191962e823644bfa915ed55adbfb3a97804e2643d2845d1b7ab", + "digest": "sha256:43c854e70911244bb59eca1d2320c5b3ce255a63638dc76a599d8bc006f44887", "evidence_files": 6, "evidence_root": "sha256:7fde48972a09dd4b0f7206aca4e313cd02c8cd195ec602e3924e59246c016aa5", - "files": 799, - "generated_at_commit": "016ace066ba349018342a646c1852c0752fd067b", - "source_tree": "sha256:9d97196126ec497b638b5d8ad3730df460a9fcdea14eb51f86a057aa01b6aa3e" + "files": 807, + "generated_at_commit": "6dc2ff3c49dd486b51fd71da0d8a2cb6a7603307", + "source_tree": "sha256:b7ea1b64066eb6f878bae599fa400dd6722991a639e94fa4e6a44178a7fd6ddc" }, "progress": { "initial_edits": "Dashboard draft predates explicit Crumb reminder; subsequent integration is claimed and recorded.", diff --git a/crates/.crumb b/crates/.crumb index 7c2acec..84aaba9 100644 --- a/crates/.crumb +++ b/crates/.crumb @@ -7,21 +7,21 @@ "generated": { "children": [ { - "digest": "5ca18b44995cca9d515ca22d6aa30c74d9a8d64d0b75d5720cdef2a800536d7d", - "last_commit": "016ace0", + "digest": "e1dae3cc37fc98eec0f75b271ea80d854c05bf411d8302cef98b64e4ce135f08", + "last_commit": "a9c5dbb", "name": "site-builder", "purpose": "Rust static site generator" } ], - "children_root": "sha256:2c35d2f54f4207c136827924f3df17d92249b23f00c1b27eb6736591b6014c8d", - "compiled_at": "2026-10-29T17:40:49Z", + "children_root": "sha256:e6341fef83cfb6aa5d49818beaadd8de3e43f1a3ea9a805985e91ebb5b84d051", + "compiled_at": "2026-10-30T02:44:24Z", "compiler": "crumb-compile/1", - "digest": "sha256:6cce6e334f7479fb2ed4c460dc9d73a8700012cee6d9f17713b7f4a2c0d70cc4", + "digest": "sha256:7ce1c68a26a852505622949aff766ec2de015bde1925e13a85c338e1261d2719", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "files": 70, - "generated_at_commit": "016ace066ba349018342a646c1852c0752fd067b", - "source_tree": "sha256:d9b320f69a87b32369b2eff46f36dc69b4abaf8dd2e775c1519b6c5bc3c5a904" + "generated_at_commit": "6dc2ff3c49dd486b51fd71da0d8a2cb6a7603307", + "source_tree": "sha256:a490971c0acc5bd68a4b530d979b89d68da0351fe989bc3de3a30dff9b1caf55" } }, "invariants": [ diff --git a/crates/site-builder/.crumb b/crates/site-builder/.crumb index d36075a..db15da4 100644 --- a/crates/site-builder/.crumb +++ b/crates/site-builder/.crumb @@ -7,8 +7,8 @@ "generated": { "children": [ { - "digest": "61ac19ed2c14758568670805231c874bed774cf56730bf6d23cf81da3674b8a6", - "last_commit": "016ace0", + "digest": "22eec7f4047077796ebafaa8baa49fff4383d5dfde21524f92e1d5907d4640d1", + "last_commit": "a9c5dbb", "name": "src", "purpose": "Page assembly and site build verification" }, @@ -19,15 +19,15 @@ "purpose": "Reviewed HTML templates for source-backed pages" } ], - "children_root": "sha256:c5bd9db0bad6a84e372f91fbfd06aa6d72ca24eb3aaa04736b636b0b1b9f95a9", - "compiled_at": "2026-10-29T17:40:49Z", + "children_root": "sha256:5ce8254b0ef14e8096496b2928a816c3e9ada501fd6219fcde46b83907c00d32", + "compiled_at": "2026-10-30T02:44:24Z", "compiler": "crumb-compile/1", - "digest": "sha256:5ca18b44995cca9d515ca22d6aa30c74d9a8d64d0b75d5720cdef2a800536d7d", + "digest": "sha256:e1dae3cc37fc98eec0f75b271ea80d854c05bf411d8302cef98b64e4ce135f08", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "files": 61, - "generated_at_commit": "016ace066ba349018342a646c1852c0752fd067b", - "source_tree": "sha256:f7e467217414a3ed7ff7a54c1f36196f42b845a51608537b519fee0093ff82a6" + "generated_at_commit": "6dc2ff3c49dd486b51fd71da0d8a2cb6a7603307", + "source_tree": "sha256:ec3b0083a6dc4c77e73859f75bf6c80e576204c45c8f70f27e8889874cf217cc" } }, "invariants": [ diff --git a/crates/site-builder/src/.crumb b/crates/site-builder/src/.crumb index 39f2e69..3be2bc3 100644 --- a/crates/site-builder/src/.crumb +++ b/crates/site-builder/src/.crumb @@ -10,21 +10,21 @@ "generated": { "children": [ { - "digest": "14637f8df7df0428740923367179233eecc51aca38f2020f80826b917bb5e5c1", - "last_commit": "016ace0", + "digest": "e644d637d2fc3e091b8da816a26b19365c80ada6300e299d0854fc4780154763", + "last_commit": "a9c5dbb", "name": "components", "purpose": "Reusable page content and navigation" } ], - "children_root": "sha256:67ac8a8fe5c93d7ea05a1314cb46f3e220343a67ae510b1bcd28e21cff1de9d3", - "compiled_at": "2026-10-29T17:40:49Z", + "children_root": "sha256:3446cfd2d8606fe2e4e8f66d7356c03bd5e5d1027916ddb8756614aedbc0f852", + "compiled_at": "2026-10-30T02:44:24Z", "compiler": "crumb-compile/1", - "digest": "sha256:61ac19ed2c14758568670805231c874bed774cf56730bf6d23cf81da3674b8a6", + "digest": "sha256:22eec7f4047077796ebafaa8baa49fff4383d5dfde21524f92e1d5907d4640d1", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "files": 54, - "generated_at_commit": "016ace066ba349018342a646c1852c0752fd067b", - "source_tree": "sha256:47e3dde8f71462ef90684f842a14de91d2bdbacf2999634335b4e7b2ca1a1f05" + "generated_at_commit": "6dc2ff3c49dd486b51fd71da0d8a2cb6a7603307", + "source_tree": "sha256:b08c299f996cdd532ad756b19568fc6b6972809e5967cc7ed08d071c09cb1ed5" } }, "invariants": [ diff --git a/crates/site-builder/src/components/.crumb b/crates/site-builder/src/components/.crumb index 02b4d61..af260e5 100644 --- a/crates/site-builder/src/components/.crumb +++ b/crates/site-builder/src/components/.crumb @@ -10,14 +10,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-29T17:40:49Z", + "compiled_at": "2026-10-30T02:44:24Z", "compiler": "crumb-compile/1", - "digest": "sha256:14637f8df7df0428740923367179233eecc51aca38f2020f80826b917bb5e5c1", + "digest": "sha256:e644d637d2fc3e091b8da816a26b19365c80ada6300e299d0854fc4780154763", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "files": 47, - "generated_at_commit": "016ace066ba349018342a646c1852c0752fd067b", - "source_tree": "sha256:0e9bc325c313292b8c464943a7deb9b43ff626d2450b609b2c53b2c620a6292f" + "generated_at_commit": "6dc2ff3c49dd486b51fd71da0d8a2cb6a7603307", + "source_tree": "sha256:740671a7b175fcd45efe71d5796c108a4273fb41ec150fee774c1fbc1630488b" } }, "invariants": [ diff --git a/om/agora/check.sh b/om/agora/check.sh index e571d20..1905d1a 100755 --- a/om/agora/check.sh +++ b/om/agora/check.sh @@ -208,12 +208,15 @@ for field in ActiveState SubState IPAccounting ControlGroup; do raw=$(printf '%s' "$observer_state" | sed "/^$field=/d") observer_expect 1 "state-$field-removed" state "$raw" /system.slice/aien-agora.service done +# The observer must see systemd's literal, unexpanded argv display. +# shellcheck disable=SC2016 observer_argv='/opt/aien/bin/agora serve --state /var/lib/aien-agora --listen ${AGORA_LISTEN} --port 18132 --bits 20' +# shellcheck disable=SC2016 observer_exec='ExecStart={ path=/opt/aien/bin/agora ; argv[]=/opt/aien/bin/agora serve --state /var/lib/aien-agora --listen ${AGORA_LISTEN} --port 18132 --bits 20 ; start_time=[irrelevant timezone] ; pid=42 ; status=0/0 } ' observer_expect 0 exec exec "$observer_exec" /opt/aien/bin/agora "$observer_argv" 42 for field in 'path=' 'argv\[\]=' 'pid='; do - raw=$(printf '%s' "$observer_exec" | sed "s|$field[^;]*;||") + raw=$(printf '%s' "$observer_exec" | sed "s|${field}[^;]*;||") observer_expect 1 "exec-$field-removed" exec "$raw" /opt/aien/bin/agora "$observer_argv" 42 done observer_ss='LISTEN 0 128 192.0.2.20:18132 0.0.0.0:* users:(("agora",pid=42,fd=4))' @@ -223,6 +226,19 @@ observer_snapshot() { } observer_snapshot 0 stable /opt/aien/bin/agora '976 964' "$observer_ss" /opt/aien/bin/agora '976 964' 42 42 1 observer_snapshot 2 preexec /usr/lib/systemd/systemd-executor '0 0' "$observer_ss" /opt/aien/bin/agora '976 964' 42 42 1 +observer_anon='LISTEN 0 64 192.0.2.20:18132 0.0.0.0:*' +observer_snapshot 2 anonymous-exec-transition /usr/lib/systemd/systemd-executor '0 0' "$observer_anon" /opt/aien/bin/agora '976 964' 42 42 1 +observer_snapshot 1 anonymous-stable /opt/aien/bin/agora '976 964' "$observer_anon" /opt/aien/bin/agora '976 964' 42 42 1 +observer_snapshot 1 anonymous-expired /usr/lib/systemd/systemd-executor '0 0' "$observer_anon" /opt/aien/bin/agora '976 964' 42 42 10000000000 +observer_snapshot 1 anonymous-main-changed /usr/lib/systemd/systemd-executor '0 0' "$observer_anon" /opt/aien/bin/agora '976 964' 42 142 1 +observer_snapshot 1 anonymous-final-root /usr/lib/systemd/systemd-executor '0 0' "$observer_anon" /opt/aien/bin/agora '0 0' 42 42 1 +observer_snapshot 1 anonymous-final-wrong-exe /usr/lib/systemd/systemd-executor '0 0' "$observer_anon" /wrong/executable '976 964' 42 42 1 +observer_snapshot 1 anonymous-wrong-endpoint /usr/lib/systemd/systemd-executor '0 0' 'LISTEN 0 64 192.0.2.21:18132 0.0.0.0:*' /opt/aien/bin/agora '976 964' 42 42 1 +observer_snapshot 1 transition-wrong-owner /usr/lib/systemd/systemd-executor '0 0' 'LISTEN 0 64 192.0.2.20:18132 0.0.0.0:* users:(("agora",pid=142,fd=4))' /opt/aien/bin/agora '976 964' 42 42 1 +observer_snapshot 1 anonymous-multiple-rows /usr/lib/systemd/systemd-executor '0 0' "$observer_anon +$observer_anon" /opt/aien/bin/agora '976 964' 42 42 1 +observer_snapshot 1 anonymous-trailing /usr/lib/systemd/systemd-executor '0 0' "$observer_anon unexpected" /opt/aien/bin/agora '976 964' 42 42 1 +observer_snapshot 1 anonymous-malformed /usr/lib/systemd/systemd-executor '0 0' 'LISTEN nope 64 192.0.2.20:18132 0.0.0.0:*' /opt/aien/bin/agora '976 964' 42 42 1 observer_snapshot 1 root-past-deadline /usr/lib/systemd/systemd-executor '0 0' "$observer_ss" /usr/lib/systemd/systemd-executor '0 0' 42 42 10000000000 observer_snapshot 1 stable-root /opt/aien/bin/agora '0 0' "$observer_ss" /opt/aien/bin/agora '0 0' 42 42 1 observer_snapshot 1 changed-main /opt/aien/bin/agora '976 964' "$observer_ss" /opt/aien/bin/agora '976 964' 1 42 1 diff --git a/om/agora/deploy/DEPLOY.md b/om/agora/deploy/DEPLOY.md index 6e2ad64..c55f7c5 100644 --- a/om/agora/deploy/DEPLOY.md +++ b/om/agora/deploy/DEPLOY.md @@ -177,6 +177,14 @@ credentials, an unexpected stable identity, process/read failure or timeout is FAIL and triggers rollback. Do not extend the deadline, rerun start, change the service identity or activate routing to make this check pass. +A recognized `/usr/lib/systemd/systemd-executor` to exact expected executable +transition may coincide with a single valid ownerless LISTEN row. With stable +MainPID, permitted pre-exec credentials, exact final credentials and time +remaining, that narrow case is PENDING only. Reacquire the entire bracket. +A stable ownerless listener, an explicit different owner, wrong endpoint, +malformed or multiple rows, changed MainPID or deadline expiry still refuses. +Only a fresh stable bracket with explicit same-PID ownership can become READY. + The native `om/agora/startup-check.om` unit is the startup policy authority. Its CLI takes `deadline_ns executable_match effective_uid effective_gid same_pid_listener` and exits 0 for pending, 1 for ready, 2 for refusal, or 90 @@ -256,6 +264,74 @@ locations; replace only host paths, ports, certificates and external upstreams with local fixtures. Do not publish private captured configuration. +## Full isolated activation rehearsal + +Before another live retry, execute the file-backed activation observers end to +end with `scripts/test-agora-activation.py` as root. Supply a new private +`--root`, the approved `--backend`, oracle `--nginx`, compiled native +`--native` observer and `--startup` policy, and the exact published `--page` +and `--client`. Do not substitute a mock API or replace the browser client. +The host needs `ip`, `tcpdump`, `bpftool`, systemd and the existing dedicated +account. The verification tools are not production dependencies. + +The conductor creates a uniquely named network namespace, isolated systemd +backend and stub nginx. Its executables live in its own `/opt/aien-agora-oracle-*` +directory because Spark mounts `/run` noexec. Units and temporary boot links +are runtime-only; no production firewall rule, unit, hub file or state changes. +Fixed loopback tunnels carry raw TLS through the fixture SNI router and its +PROXY listener. The backend socket is created inside its network namespace. +The exact two-prefix policy is tested after a separately labelled third-source +reachability control. Passive SYN and SYN-ACK observations prove allowed and +denied paths without adding firewall rules. + +Use the root-only `control.sock` with `--control PATH --action pre-browser`. +Then run `runBrowser` from `scripts/agora_activation_browser.mjs` against the +returned `browser_url` in a new, CPU-only browser profile. Resolve only +`www.aienos.com` to the returned loopback address, refuse other domains and +permit the fixture certificate only in that owned browser. Recovery callbacks +must pass secrets through stdin to the root-only `save-key` control; never put +them in arguments, screenshots, HAR, console output or receipts. The +`restart-backend` and `read-profile` controls operate only on the fixture. + +Pass the browser verdict to `after-browser`, which rejects any missing or +failed prerequisite. It exercises real TLS quota exhaustion with forged +identity headers, checks effective access/error/temp sinks directly and +enables only the isolated runtime unit after all gates pass. Finally `finish` +injects an acceptance failure and verifies rollback: API closed, ordinary +site healthy, unit stopped and disabled, profiles unchanged. Private recovery +files and a root-only retained-state copy remain beneath the scratch root. +The receipt is explicitly `ISOLATED_NAMESPACE_ONLY_NOT_DEPLOYED`. + +The conductor treats SIGHUP, SIGINT and SIGTERM as failed acceptance: it records +FAIL, rolls back and cleans up its own units and namespace while retaining +private state. A killed process cannot execute cleanup. If recovering an older +interrupted run, first prove the namespace, runtime units and paths belong to +that fixture, preserve their files privately, and stop only those resources. +Never label an interrupted run PASS or loosen directory permissions to read it; +use the operator's existing permitted root read path. + +Privacy includes a negative control: place a public sentinel in an effective +fixture temporary-body sink, require the actual scanner to refuse it, and +remove only that control file. This demonstrates scanner sensitivity, not the +absence of transient production body spills or historical logging causality. +The privacy pass also scans current-invocation journals for the backend and +every fixture routing unit. Raw journal bodies are private, including the +startup warning observation; receipts retain only the scanner verdict and +non-secret unit names. Empty control responses fail without an acceptance +verdict rather than being treated as success. + +Run `python3 -m py_compile` and `pyflakes` on all three Python observer files, +and `node --check scripts/agora_activation_browser.mjs`. Record the complete +rehearsal receipt and static-check output on the source PR before any live +retry. A fixture failure is not permission to continue live. + +`activation-rehearsal.evidence.json` records the completed 2026-10-28 isolated +sequence at source `9caa5598159a8589f8dfd0c4c36b5b568b84786e`: all 17 +conductor gates and seven real-browser gates passed, including durable readback, +lost-acknowledgement refusal and injected rollback. The earlier interrupted +rehearsals remain failed or incomplete. This receipt is not a production retry, +deployment authorization, or evidence that production routing is enabled. + ## Required deployment checks Record observed outputs, not just the commands: diff --git a/om/agora/deploy/activation-rehearsal.evidence.json b/om/agora/deploy/activation-rehearsal.evidence.json new file mode 100644 index 0000000..3021882 --- /dev/null +++ b/om/agora/deploy/activation-rehearsal.evidence.json @@ -0,0 +1,417 @@ +{ + "status": "PASS", + "scope": "ISOLATED_NAMESPACE_ONLY_NOT_DEPLOYED", + "observed_utc": "2026-10-28T18:49:48.539810+00:00", + "exercised_source_commit": "9caa5598159a8589f8dfd0c4c36b5b568b84786e", + "published_source_commit": "07736aa17fd16e862725cf440bcae71527945285", + "source_sha256": { + "scripts/test-agora-activation.py": "969bf45664b624de00e7234e8a38204725a9ab4ac03fd4c407fb376d2326ac76", + "scripts/agora_activation_observers.py": "544b0f49d9b418e00a4e8b22c13a556da364f20500491f1247d5e2eda33a8740", + "scripts/agora_activation_namespace.py": "4f4f1e2b1bde3de53ba80a7c1e4b35ee60ba6fa55d9e0e5103a597db2e26be3c", + "scripts/agora_activation_browser.mjs": "a3c8f6f9dc7365c59ce295a604c524bed105cbe3c0d40f8f65b937b1334e5c1d", + "om/agora/observer-check.om": "443f33d9c000c3169f2607dc0c24c2c8f959a7007e7f8ca66f2299a7be097e7f" + }, + "compiler_sha256": "2c82480596bbdc50cda9626866209ef662d5834f278f839ff4ce0250c495029f", + "native_source_binary_bindings": [ + { + "source_files": [ + "json.om", + "policy.om", + "observer-check.om" + ], + "source_sha256": "d4057f778d9f2a3f898ee8b411ba5e4e1629c6cdf8f4d4b1af76e321ce1b6cfc", + "binary_sha256": "cb2f5d6c7c1a5c23b02dfe669f100901fa5865aa33178fd0fbe87dbff3a82478", + "compile_exit": 0, + "existing_fixture_binary_identical": true + }, + { + "source_files": [ + "startup-check.om" + ], + "source_sha256": "26e87cac1dc5ab8ea1b1012d59f96949ed3610d9d5fea5c047bf3a72ff68bb99", + "binary_sha256": "66ed83f561ebc498cba51e021446965e2ffe4b70a46ab84a99d4dde03bad503e", + "compile_exit": 0, + "existing_fixture_binary_identical": true + }, + { + "source_files": [ + "sha256.om", + "http.om", + "agora.om" + ], + "source_sha256": "4f8f868a6d3cef1febf7c4cfd5be94b178aff24184c3145f7fce513a7be1d45c", + "binary_sha256": "cadb8de5d68420b563d633156e661aff5aab4f8293f1d77455f4b36768666239", + "compile_exit": 0, + "existing_fixture_binary_identical": true + } + ], + "published_artifacts": [ + { + "url": "https://www.aienos.com/aienet/", + "sha256": "5b9b5cee5f36aba159e25552169852430eb65947579e20eae7d73fe57d108330", + "approved_sha256": "5b9b5cee5f36aba159e25552169852430eb65947579e20eae7d73fe57d108330", + "matches": true + }, + { + "url": "https://www.aienos.com/js/aienet.js", + "sha256": "4e9b46afd7db51b86c438bf6d340bb29e29fd26dc7f02a5a157585713a08ace4", + "approved_sha256": "4e9b46afd7db51b86c438bf6d340bb29e29fd26dc7f02a5a157585713a08ace4", + "matches": true + } + ], + "gates": [ + { + "gate": "copied backend/page/client exact source bytes, root ownership and regular-file modes", + "status": "PASS", + "observation": null + }, + { + "gate": "bounded startup/effective native guards/current namespace/cgroup BPF", + "status": "PASS", + "observation": null + }, + { + "gate": "independent same-endpoint second-source reachability control", + "status": "PASS", + "observation": { + "source": "127.0.0.3", + "syn": 1, + "synack": 1, + "accept": true + } + }, + { + "gate": "actual source-bound packet allow/deny", + "status": "PASS", + "observation": { + "source": "127.0.0.2", + "syn": 1, + "synack": 1, + "accept": true + } + }, + { + "gate": "actual source-bound packet allow/deny", + "status": "PASS", + "observation": { + "source": "127.0.0.3", + "syn": 5, + "synack": 0, + "accept": false + } + }, + { + "gate": "independent real BPF denial with no firewall mutation", + "status": "PASS", + "observation": null + }, + { + "gate": "exact service policy restored and allowed source recovers", + "status": "PASS", + "observation": null + }, + { + "gate": "nginx active-worker adoption plus independently counted TLS GET", + "status": "PASS", + "observation": null + }, + { + "gate": "actual TLS method/id/trailing/disabled/oversize and non-PROXY refusals, zero upstream payload", + "status": "PASS", + "observation": null + }, + { + "gate": "synthetic body/key real backend failure path", + "status": "PASS", + "observation": null + }, + { + "gate": "effective actual fixture access/error/temp sinks have no synthetic body/key markers", + "status": "PASS", + "observation": null + }, + { + "gate": "privacy scanner rejects an actual marker in an effective temporary-body sink", + "status": "PASS", + "observation": null + }, + { + "gate": "real browser consent/ack/readback/uncertainty/durability", + "status": "PASS", + "observation": { + "status": "PASS", + "gates": [ + { + "name": "browser_setup", + "status": "PASS" + }, + { + "name": "missing_consent_no_write", + "status": "PASS" + }, + { + "name": "acknowledged_exact_profile", + "status": "PASS" + }, + { + "name": "restart_durable_readback", + "status": "PASS" + }, + { + "name": "actual_write_response_lost", + "status": "PASS" + }, + { + "name": "uncertain_write_no_auto_repeat", + "status": "PASS" + }, + { + "name": "same_origin_saved_signup_restored", + "status": "PASS" + } + ], + "requests": [ + { + "phase": "acknowledged_exact_profile", + "method": "GET", + "path": "/agora/api/challenge", + "count": 1 + }, + { + "phase": "acknowledged_exact_profile", + "method": "POST", + "path": "/agora/api/hello", + "count": 1 + }, + { + "phase": "acknowledged_exact_profile", + "method": "GET", + "path": "/agora/api/agent/:id", + "count": 1 + }, + { + "phase": "restart_durable_readback", + "method": "GET", + "path": "/agora/api/agent/:id", + "count": 1 + }, + { + "phase": "actual_write_response_lost", + "method": "GET", + "path": "/agora/api/challenge", + "count": 1 + }, + { + "phase": "actual_write_response_lost", + "method": "POST", + "path": "/agora/api/hello", + "count": 1 + }, + { + "phase": "same_origin_saved_signup_restored", + "method": "GET", + "path": "/agora/api/agent/:id", + "count": 1 + } + ], + "noRepeatObservationMs": 1500 + } + }, + { + "gate": "actual TLS forged identity headers share quota; refusals produce zero upstream requests", + "status": "PASS", + "observation": { + "accepted": 13, + "limited": 19 + } + }, + { + "gate": "actual response recovery keys absent from every effective log/temp-body sink", + "status": "PASS", + "observation": null + }, + { + "gate": "enable only after every acceptance gate passes, isolated runtime target only", + "status": "PASS", + "observation": null + }, + { + "gate": "injected first-failure rollback closes API/stops backend/preserves profiles/site200", + "status": "PASS", + "observation": null + } + ], + "browser": { + "status": "PASS", + "gates": [ + { + "name": "browser_setup", + "status": "PASS" + }, + { + "name": "missing_consent_no_write", + "status": "PASS" + }, + { + "name": "acknowledged_exact_profile", + "status": "PASS" + }, + { + "name": "restart_durable_readback", + "status": "PASS" + }, + { + "name": "actual_write_response_lost", + "status": "PASS" + }, + { + "name": "uncertain_write_no_auto_repeat", + "status": "PASS" + }, + { + "name": "same_origin_saved_signup_restored", + "status": "PASS" + } + ], + "requests": [ + { + "phase": "acknowledged_exact_profile", + "method": "GET", + "path": "/agora/api/challenge", + "count": 1 + }, + { + "phase": "acknowledged_exact_profile", + "method": "POST", + "path": "/agora/api/hello", + "count": 1 + }, + { + "phase": "acknowledged_exact_profile", + "method": "GET", + "path": "/agora/api/agent/:id", + "count": 1 + }, + { + "phase": "restart_durable_readback", + "method": "GET", + "path": "/agora/api/agent/:id", + "count": 1 + }, + { + "phase": "actual_write_response_lost", + "method": "GET", + "path": "/agora/api/challenge", + "count": 1 + }, + { + "phase": "actual_write_response_lost", + "method": "POST", + "path": "/agora/api/hello", + "count": 1 + }, + { + "phase": "same_origin_saved_signup_restored", + "method": "GET", + "path": "/agora/api/agent/:id", + "count": 1 + } + ], + "noRepeatObservationMs": 1500 + }, + "static_checks": [ + { + "command": [ + "python3", + "-m", + "py_compile", + "scripts/agora_activation_observers.py", + "scripts/agora_activation_namespace.py", + "scripts/test-agora-activation.py" + ], + "exit": 0, + "stdout": "", + "stderr": "" + }, + { + "command": [ + "/tmp/aienet-activation-lint/bin/pyflakes", + "scripts/agora_activation_observers.py", + "scripts/agora_activation_namespace.py", + "scripts/test-agora-activation.py" + ], + "exit": 0, + "stdout": "", + "stderr": "" + }, + { + "command": [ + "node", + "--check", + "scripts/agora_activation_browser.mjs" + ], + "exit": 0, + "stdout": "", + "stderr": "" + }, + { + "command": [ + "/tmp/aienet-activation-lint/shellcheck-oracle/usr/bin/shellcheck", + "om/agora/check.sh" + ], + "exit": 0, + "stdout": "", + "stderr": "" + } + ], + "native_replay": { + "cases": 271, + "mismatches": 0 + }, + "core_gate": { + "command": "OMEGA_OMC= NGINX_BIN= sh om/agora/check.sh", + "exit": 0, + "verdict": "PASS agora: core and network gates", + "limitation": "Owned host fixtures only; network-suite edge/federation controls do not enable those services." + }, + "negative_controls": { + "sighup": { + "status": "PASS", + "observed_receipt_status": "FAIL", + "expected_error": "Refused: Fixture interrupted by SIGHUP", + "owned_units_namespace_runtime_removed": true, + "private_state_retained": true + }, + "actual_service_journal": { + "status": "PASS", + "actual_journal_marker_refused": true, + "clean_control_passed": true, + "raw_journal_never_recorded": true + }, + "empty_control": { + "status": "PASS", + "empty_control_fails_closed": true + } + }, + "private_raw_receipt_sha256": "a8acdca116146627de19178b3b0255bb6d81974ce006173cdcbe2c6841cf2cb6", + "cleanup": { + "all_owned_units_stopped": true, + "namespace_unit_runtime_state_paths_absent": true, + "state_retained_privately": true, + "recovery_files": 2, + "root_receipt_key_modes": "0600", + "root_retained_state_mode": "0700" + }, + "interrupted_runs": { + "g": "INTERRUPTED_NOT_PASS; owned resources stopped and all old files retained privately", + "h": "Stopped with SIGTERM before browser to close journal privacy inspection gap; FAIL expected, not acceptance" + }, + "limits": [ + "No production Retry I was executed.", + "No production configuration, ingress, boot or model changes; no GPU access.", + "Registration only: no JSON edge, MCP/A2A or federation activation.", + "Namespace/systemd/browser results do not qualify remote production routing or hardware.", + "Privacy proves observed sinks and negative-control sensitivity; transient body spills and historical suppression causality remain unqualified.", + "Draft PR169 remains unmerged and unauthorized for deployment." + ] +} diff --git a/om/agora/deploy/activation-static.evidence.json b/om/agora/deploy/activation-static.evidence.json new file mode 100644 index 0000000..2f63f10 --- /dev/null +++ b/om/agora/deploy/activation-static.evidence.json @@ -0,0 +1,15 @@ +{ + "scope": "verification_oracles_only_not_production_deployment", + "checks": [ + {"command": "python3 -m py_compile scripts/agora_activation_observers.py scripts/agora_activation_namespace.py scripts/test-agora-activation.py", "exit": 0, "stdout": "", "stderr": ""}, + {"command": "/tmp/aienet-activation-lint/bin/pyflakes scripts/agora_activation_observers.py scripts/agora_activation_namespace.py scripts/test-agora-activation.py", "version": "3.2.0", "exit": 0, "stdout": "", "stderr": ""}, + {"command": "node --check scripts/agora_activation_browser.mjs", "exit": 0, "stdout": "", "stderr": ""}, + {"command": "/tmp/aienet-activation-lint/shellcheck-oracle/usr/bin/shellcheck om/agora/check.sh", "package": "shellcheck_0.9.0-1_arm64.deb", "exit": 0, "stdout": "", "stderr": ""} + ], + "prior_findings_fixed": ["SC1087: brace the variable before the literal character class in the mutation expression", "SC2016: document intentional literal systemd argv placeholders with narrow directives"], + "wolfram": { + "query": "UnitConvert[Quantity[{120,1.5},\"Seconds\"],\"Milliseconds\"]", + "raw_output": "Working...\nOut[1]= {Quantity[120000, \"Milliseconds\"], Quantity[1500., \"Milliseconds\"]}\nWall time: 40.01 seconds", + "route": "omp --print --no-session; mounted mcp__wolfram_wolframlanguageevaluator" + } +} diff --git a/om/agora/observer-check.om b/om/agora/observer-check.om index 2c2dce0..77529d4 100644 --- a/om/agora/observer-check.om +++ b/om/agora/observer-check.om @@ -32,6 +32,8 @@ text ob_epid "pid=" text ob_list "LISTEN" text ob_owner "pid=" text ob_pre "(agora)" +text ob_sexec "/usr/lib/systemd/systemd-executor" +text ob_peer "0.0.0.0:*" text ob_root "root" text ob_jpid "_PID" text ob_juid "_UID" @@ -364,6 +366,38 @@ ret eq ob_num ob_tok a 1 ob_num ob_tok b 1 end note snapshot PID MAIN_BEFORE EXE_BEFORE PS_BEFORE SS EXE_AFTER PS_AFTER MAIN_AFTER EXE UID GID ENDPOINT ELAPSED LIMIT. note Captured elapsed/limit are compared as data, never against the replay machine's current clock. +note A single ownerless socket row during a recognized exec transition is pending only. +fn ob_anon raw ulong endpoint ulong to bool +if ne ob_count raw 5 +ret false +end +if not ob_text ob_tok raw 0 ob_list +ret false +end +if lt ob_num ob_tok raw 1 0 +ret false +end +if lt ob_num ob_tok raw 2 0 +ret false +end +if not ob_eq ob_tok raw 3 endpoint +ret false +end +if not ob_text ob_tok raw 4 ob_peer +ret false +end +p = ob_trim raw +while ne get ob_buf p 0 bound 4096 +if eq get ob_buf p 10 +if ne get ob_buf ob_trim add p 1 0 +ret false +end +end +p = add p 1 +end +ret true +end + fn ob_snapshot to int if ne argcnt 16 ret 90 @@ -400,6 +434,15 @@ ret 1 end owned = ob_socket ob_at 6 ob_at 2 ob_at 13 if eq owned 1 +if ob_text ob_at 4 ob_sexec +if ob_eq ob_at 7 ob_at 10 +if ob_creds ob_at 8 ob_at 11 ob_at 12 +if ob_anon ob_at 6 ob_at 13 +ret 2 +end +end +end +end ret 1 end if not ob_eq ob_at 4 ob_at 7 diff --git a/scripts/agora_activation_browser.mjs b/scripts/agora_activation_browser.mjs new file mode 100644 index 0000000..7ecb82e --- /dev/null +++ b/scripts/agora_activation_browser.mjs @@ -0,0 +1,354 @@ +// Verification-only oracle. The production Omega-generated client is never replaced. +// Run on an owned raw Puppeteer page with no tracing, HAR, payload logging or screenshots. +import { randomUUID } from 'node:crypto'; + +const STORE = 'aienet.signup.v1'; +const PREFIX = 'Aienet signup v1: '; +const WAIT = 120000; +const OBSERVE = 1500; +const pause = ms => new Promise(resolve => setTimeout(resolve, ms)); + +function requireGate(condition, code) { + if (!condition) throw new Error(code); +} + +// Parse the first profile record only, including its byte-counted body. Never +// accept a marker found in a later note, letter or unrelated profile. +function profileRecord(value) { + if (value && typeof value === 'object' && !Buffer.isBuffer(value)) { + return { ...value, about: value.about ?? value.body }; + } + const raw = Buffer.isBuffer(value) ? value : Buffer.from(String(value), 'utf8'); + let pos = 0; + const line = () => { + const end = raw.indexOf(10, pos); + requireGate(end >= pos, 'profile_line_incomplete'); + const text = raw.subarray(pos, end).toString('utf8'); + pos = end + 1; + return text; + }; + let head = line(); + if (head === 'agora 1') { + requireGate(line() === 'ok', 'profile_server_refused'); + head = line(); + } + const fields = head.split('\t'); + requireGate(fields.length === 6 && fields[0] === 'agent', 'profile_header_malformed'); + const result = { id: fields[1], name: fields[2], kind: fields[3] }; + for (const name of ['model', 'framework', 'human', 'link']) { + const entry = line().split('\t'); + requireGate(entry.length === 2 && entry[0] === name, 'profile_field_malformed'); + result[name] = entry[1]; + } + const body = /^body ([0-9]+)$/.exec(line()); + requireGate(body !== null, 'profile_body_malformed'); + const length = Number(body[1]); + requireGate(Number.isSafeInteger(length) && length <= 2048 && + pos + length < raw.length && raw[pos + length] === 10, 'profile_body_incomplete'); + result.about = raw.subarray(pos, pos + length).toString('utf8'); + return result; +} + +function matchesProfile(value, id, expected) { + const actual = profileRecord(value); + return actual.id === id && actual.kind === 'agent' && + ['name', 'human', 'model', 'framework', 'link'].every(name => actual[name] === expected[name]) && + actual.about === PREFIX + expected.about; +} + +function synthetic(label) { + return { + name: `Public synthetic verification ${randomUUID().slice(0, 8)}`, + human: '@synthetic-activation-verification', + model: 'Synthetic verification, not a deployed model', + framework: 'Public Aienet activation behavior oracle', + link: 'https://example.org/', + about: `Explicitly public synthetic ${label} verification. Not a person, production agent, or membership claim.`, + }; +} + +/** + * Mutates only the supplied origin and its real signup backend, so the caller + * must authorize that exact target before invoking this function. No requests + * run at import time and no hostname receives a special passing path. + * + * saveRecovery(key) must await private root-only persistence and never log. + * readProfile(id) returns the real full Agora response text/Buffer, or a parsed + * {id,name,kind,model,framework,human,link,about} record, never a canned fixture. + * restartBackend() must restart only the caller's authorized backend and await + * readiness. Both public synthetic profiles must survive caller rollback. + * + * Keep the returned page private: its unchanged client displays the recovery + * input. This function deliberately returns no profile, key, DOM or raw error. + */ +export async function runBrowser(page, options = {}) { + const gates = []; + const counts = new Map(); + let phase = 'setup'; + let session; + let initScript; + let requestListener; + let pausedListener; + let originalSaved = null; + let restoreNeeded = false; + let ack = null; + let ackMode = 'deliver'; + let interceptionFailure = null; + let discarded = false; + let captured = 0; + const pending = new Set(); + const allowedCodes = new Set(); + const check = (condition, code) => { + allowedCodes.add(code); + requireGate(condition, code); + }; + const gate = async (name, operation) => { + phase = name; + try { + await operation(); + gates.push({ name, status: 'PASS' }); + } catch (error) { + gates.push({ name, status: 'FAIL', reason: allowedCodes.has(error?.message) ? error.message : 'operation_failed' }); + throw new Error('browser_gate_failed'); + } + }; + let origin; + let target; + const total = (method, path) => [...counts.values()] + .filter(entry => entry.method === method && entry.path === path) + .reduce((sum, entry) => sum + entry.count, 0); + const storage = () => page.evaluate(key => localStorage.getItem(key), STORE); + const submitEvent = () => page.evaluate(() => { + document.getElementById('aienet-form').dispatchEvent(new Event('submit', { bubbles: true, cancelable: true })); + }); + const fill = async values => { + for (const [name, value] of Object.entries(values)) { + const selector = `#aienet-form [name="${name}"]`; + await page.click(selector); + await page.type(selector, value); + } + }; + const waitTerminal = async () => { + await page.waitForFunction(() => { + const text = document.getElementById('aienet-status').textContent; + return text.startsWith('Registered:') || /unknown|not confirmed|Nothing was submitted|Server|Malformed/.test(text); + }, { timeout: WAIT }); + check(interceptionFailure === null, interceptionFailure || 'response_interception_failed'); + }; + const retained = async () => page.evaluate(key => { + const value = JSON.parse(localStorage.getItem(key) || 'null'); + return { value, input: document.getElementById('aienet-key').value, + confirmed: document.getElementById('aienet-status').textContent.startsWith('Registered:'), + profile: document.getElementById('aienet-profile').getAttribute('href'), + visible: !document.getElementById('aienet-profile').hidden }; + }, STORE); + + try { + await gate('browser_setup', async () => { + check(typeof options.url === 'string' && + ['saveRecovery', 'restartBackend', 'readProfile'].every(name => typeof options[name] === 'function'), 'invalid_callback_contract'); + target = new URL(options.url); + check(['https:', 'http:'].includes(target.protocol) && !target.username && !target.password && + !target.search, 'invalid_target_url'); + origin = target.origin; + check(typeof page.target === 'function' && typeof page.evaluateOnNewDocument === 'function', 'raw_puppeteer_required'); + session = await page.target().createCDPSession(); + // Use the existing analytics refusal protocol, not signup consent or a + // replacement fetch/client. Scope it to this exact origin on each reload. + initScript = await page.evaluateOnNewDocument(expectedOrigin => { + if (location.origin !== expectedOrigin) return; + localStorage.setItem('aien-allen-intro-consent', 'no'); + sessionStorage.setItem('aien-allen-intro-consent', 'no'); + localStorage.removeItem('aien-allen-intro-twclid'); + }, origin); + requestListener = request => { + const url = new URL(request.url()); + if (url.origin !== origin || !url.pathname.startsWith('/agora/api/')) return; + const path = /^\/agora\/api\/agent\/[0-9a-f]{16}$/.test(url.pathname) + ? '/agora/api/agent/:id' : ['/agora/api/challenge', '/agora/api/hello'].includes(url.pathname) + ? url.pathname : '/agora/api/other'; + const method = request.method(); + const key = JSON.stringify([phase, method, path]); + const previous = counts.get(key); + counts.set(key, { phase, method, path, count: (previous?.count || 0) + 1 }); + }; + page.on('request', requestListener); + pausedListener = event => { + const operation = (async () => { + let stopped = false; + try { + const url = new URL(event.request.url); + requireGate(url.origin === origin && url.pathname === '/agora/api/hello' && + event.request.method === 'POST', 'unexpected_intercepted_response'); + requireGate(event.responseStatusCode === 200, 'registration_http_failure'); + const response = await session.send('Fetch.getResponseBody', { requestId: event.requestId }); + const text = response.base64Encoded ? Buffer.from(response.body, 'base64').toString('utf8') : response.body; + // Even a malformed acknowledgement must not strand a real key + // when the response is withheld from the browser. + const keys = [...text.matchAll(/(?:^|\n)key\t([0-9a-f]{64})(?=\n|$)/g)]; + for (const key of keys) await options.saveRecovery(key[1]); + const accepted = /^agora 1\nok\nagent\t([0-9a-f]{16})\nkey\t([0-9a-f]{64})\n$/.exec(text); + requireGate(accepted !== null, 'registration_ack_malformed'); + // Neither the body nor the key enters evidence or an error string. + captured++; + ack = { id: accepted[1], key: accepted[2] }; + if (ackMode === 'lose') { + await session.send('Fetch.failRequest', { requestId: event.requestId, errorReason: 'ConnectionClosed' }); + stopped = true; + discarded = true; + } else { + await session.send('Fetch.continueRequest', { requestId: event.requestId }); + stopped = true; + } + } catch (_) { + interceptionFailure = 'real_ack_capture_or_private_save_failed'; + } finally { + if (!stopped) { + try { await session.send('Fetch.failRequest', { requestId: event.requestId, errorReason: 'Aborted' }); } + catch (_) { interceptionFailure = 'response_interception_cleanup_failed'; } + } + } + })(); + pending.add(operation); + void operation.finally(() => pending.delete(operation)); + }; + session.on('Fetch.requestPaused', pausedListener); + await session.send('Fetch.enable', { patterns: [{ urlPattern: `${origin}/agora/api/hello`, requestStage: 'Response' }] }); + await page.setCacheEnabled(false); + const navigation = await page.goto(target.href, { waitUntil: 'domcontentloaded', timeout: WAIT }); + check(navigation?.ok() && new URL(page.url()).origin === origin, 'page_navigation_failed'); + await page.waitForSelector('#aienet-form', { timeout: WAIT }); + check(await storage() === null, 'existing_signup_must_not_be_overwritten'); + check(await page.evaluate(() => localStorage.getItem('aien-allen-intro-consent') === 'no' && + sessionStorage.getItem('aien-allen-intro-consent') === 'no' && typeof window.twq === 'undefined'), 'analytics_refusal_failed'); + }); + + const successful = synthetic('acknowledgement and durable readback'); + await gate('missing_consent_no_write', async () => { + await fill(successful); + const before = total('POST', '/agora/api/hello'); + await page.click('#aienet-submit'); + check(await page.evaluate(() => { + const consent = document.getElementById('aienet-form').elements.consent; + return !consent.checked && !consent.validity.valid; + }), 'native_consent_validation_missing'); + // Exercise the client's explicit guard as well as native required input. + // Do not unrequire, precheck, or otherwise weaken the real consent field. + await submitEvent(); + await page.waitForFunction(() => document.getElementById('aienet-status').textContent === + 'Authorization and public-field consent are required. Nothing was sent.', { timeout: WAIT }); + await pause(OBSERVE); + check(total('POST', '/agora/api/hello') === before && total('GET', '/agora/api/challenge') === 0 && + await storage() === null, 'missing_consent_sent_request_or_saved_identity'); + }); + + await gate('acknowledged_exact_profile', async () => { + await page.click('#aienet-form [name="consent"]'); + await page.click('#aienet-submit'); + await waitTerminal(); + const saved = await retained(); + check(ack !== null && captured === 1 && saved.confirmed && saved.visible && + saved.value?.id === ack.id && saved.value?.key === ack.key && saved.input === ack.key && + saved.value?.about === PREFIX + successful.about && saved.profile === '/agora/api/agent/' + ack.id, + 'acknowledgement_and_client_readback_required'); + check(total('POST', '/agora/api/hello') === 1 && total('GET', '/agora/api/agent/:id') === 1, + 'signup_request_sequence_mismatch'); + check(matchesProfile(await options.readProfile(ack.id), ack.id, successful), 'real_profile_not_exact'); + originalSaved = await storage(); + await submitEvent(); + await pause(OBSERVE); + check(total('POST', '/agora/api/hello') === 1, 'confirmed_signup_repeated'); + }); + + await gate('restart_durable_readback', async () => { + const savedAck = ack; + await options.restartBackend(); + check(matchesProfile(await options.readProfile(savedAck.id), savedAck.id, successful), 'restart_profile_not_durable'); + await page.reload({ waitUntil: 'domcontentloaded', timeout: WAIT }); + check(await storage() === originalSaved, 'restart_browser_storage_changed'); + const before = total('GET', '/agora/api/agent/:id'); + await page.click('#aienet-recheck'); + await waitTerminal(); + const saved = await retained(); + check(saved.confirmed && saved.visible && saved.value?.id === savedAck.id && saved.input === savedAck.key && + total('GET', '/agora/api/agent/:id') === before + 1 && total('POST', '/agora/api/hello') === 1, + 'restart_browser_readback_failed'); + }); + + const uncertain = synthetic('lost actual write acknowledgement'); + await gate('actual_write_response_lost', async () => { + // Preserve this same origin and all unrelated localStorage. Only swap the + // already privately persisted synthetic signup entry for the second case. + restoreNeeded = true; + await page.evaluate(key => localStorage.removeItem(key), STORE); + await page.reload({ waitUntil: 'domcontentloaded', timeout: WAIT }); + await fill(uncertain); + ack = null; + ackMode = 'lose'; + await page.click('#aienet-form [name="consent"]'); + await page.click('#aienet-submit'); + await waitTerminal(); + check(discarded && ack !== null && captured === 2, 'actual_response_not_saved_then_discarded'); + check(matchesProfile(await options.readProfile(ack.id), ack.id, uncertain), 'uncertain_write_not_actually_committed'); + check(await page.evaluate(key => { + return /write outcome is unknown/.test(document.getElementById('aienet-status').textContent) && + document.getElementById('aienet-submit').disabled && document.getElementById('aienet-profile').hidden && + document.getElementById('aienet-result').hidden && document.getElementById('aienet-key').value === '' && + localStorage.getItem(key) === null; + }, STORE), 'uncertain_write_falsely_confirmed_or_key_delivered'); + }); + + await gate('uncertain_write_no_auto_repeat', async () => { + const beforeWrites = total('POST', '/agora/api/hello'); + const beforeChallenges = total('GET', '/agora/api/challenge'); + await submitEvent(); + await submitEvent(); + await page.click('#aienet-submit'); + await pause(OBSERVE); + check(beforeWrites === 2 && total('POST', '/agora/api/hello') === beforeWrites && + total('GET', '/agora/api/challenge') === beforeChallenges, 'uncertain_write_repeated'); + }); + + await gate('same_origin_saved_signup_restored', async () => { + await page.evaluate((key, value) => localStorage.setItem(key, value), STORE, originalSaved); + await page.reload({ waitUntil: 'domcontentloaded', timeout: WAIT }); + check(await storage() === originalSaved && new URL(page.url()).origin === origin, 'original_signup_not_restored'); + await page.click('#aienet-recheck'); + await waitTerminal(); + check((await retained()).confirmed && total('POST', '/agora/api/hello') === 2, 'restored_signup_readback_failed'); + restoreNeeded = false; + }); + } catch (_) { + // The failing gate already contains only a fixed local reason code. Never + // return Puppeteer errors, callback errors, response bodies or DOM snapshots. + } finally { + if (pending.size) await Promise.allSettled([...pending]); + if (session) { + try { await session.send('Fetch.disable'); } + catch (_) { gates.push({ name: 'response_interception_cleanup', status: 'FAIL', reason: 'cleanup_failed' }); } + if (pausedListener) session.off('Fetch.requestPaused', pausedListener); + try { await session.detach(); } + catch (_) { gates.push({ name: 'debug_session_cleanup', status: 'FAIL', reason: 'cleanup_failed' }); } + } + if (restoreNeeded && originalSaved !== null) { + try { + await page.evaluate((key, value) => localStorage.setItem(key, value), STORE, originalSaved); + await page.reload({ waitUntil: 'domcontentloaded', timeout: WAIT }); + } catch (_) { gates.push({ name: 'saved_signup_cleanup', status: 'FAIL', reason: 'cleanup_failed' }); } + } + if (requestListener) page.off('request', requestListener); + if (initScript) { + try { await page.removeScriptToEvaluateOnNewDocument(initScript.identifier); } + catch (_) { gates.push({ name: 'init_script_cleanup', status: 'FAIL', reason: 'cleanup_failed' }); } + } + } + return { + status: ['browser_setup', 'missing_consent_no_write', 'acknowledged_exact_profile', + 'restart_durable_readback', 'actual_write_response_lost', 'uncertain_write_no_auto_repeat', + 'same_origin_saved_signup_restored'].every(name => gates.some(entry => entry.name === name && entry.status === 'PASS')) && + gates.every(entry => entry.status === 'PASS') ? 'PASS' : 'FAIL', + gates, + requests: [...counts.values()], + noRepeatObservationMs: OBSERVE, + }; +} diff --git a/scripts/agora_activation_namespace.py b/scripts/agora_activation_namespace.py new file mode 100755 index 0000000..6605a03 --- /dev/null +++ b/scripts/agora_activation_namespace.py @@ -0,0 +1,556 @@ +#!/usr/bin/env python3 +"""Owned, disposable network/systemd infrastructure for the activation oracle. + +This is verification infrastructure, not an alternate registration implementation. +Only the copied native backend answers API requests. Call setup/rollback/cleanup +under root; rollback deliberately retains all profile state until cleanup. +""" + +import argparse +import ctypes +import ipaddress +import os +from pathlib import Path +import pwd +import grp +import selectors +import shutil +import socket +import sys +import threading +import time +import uuid + + +REPOSITORY = Path(__file__).resolve().parents[1] + + +class Fixture: + """A single owner of a namespace, backend unit, nginx and fixed tunnels. + + root is the caller's scratch/evidence directory, not the repository. The + callback runs argv without a shell and returns CompletedProcess with bytes. + setup returns observations/configuration, never an acceptance verdict. + """ + + def __init__(self, root: Path, backend: Path, nginx: Path, run, page: Path, client: Path): + self.root = Path(root).resolve() + self.backend = Path(backend).resolve() + self.nginx = Path(nginx).resolve() + self.page = Path(page).resolve() + self.client = Path(client).resolve() + self.run = run + self.ident = uuid.uuid4().hex + self.name = 'aien-agora-oracle-' + self.ident + self.namespace = self.name + self.unit = self.name + '.service' + # /run is noexec on Spark; only this uniquely owned fixture directory + # lives on the executable root filesystem. Never use /opt/aien/bin. + self.runtime = Path('/opt') / self.name + self.state = Path('/var/lib') / self.name + self.unit_path = Path('/run/systemd/system') / self.unit + self.dropin_dir = self.unit_path.with_name(self.unit + '.d') + self.dropin = self.dropin_dir / 'policy.conf' + self.config = {} + self._namespace_created = False + self._runtime_created = False + self._state_created = False + self._unit_created = False + self._runtime_enabled = False + self._state_retained = False + self._routing_units = [] + self._ports = [] + self._setup = False + self._closed = False + + def command(self, argv): + """Prefix commands whose sockets/listener observations belong in netns.""" + return ['ip', 'netns', 'exec', self.namespace, *map(str, argv)] + + def _call(self, argv, **kwargs): + return self.run(list(map(str, argv)), **kwargs) + + def _write(self, path, text, mode=0o644): + path.write_text(text) + path.chmod(mode) + + def _reserve_host_port(self): + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + sock.bind(('127.0.0.1', 0)) + self._ports.append(sock) + return sock.getsockname()[1] + + def _release_port(self, port): + for sock in self._ports[:]: + if sock.getsockname()[1] == port: + sock.close() + self._ports.remove(sock) + + def setup(self): + if self._setup or self._closed: + raise RuntimeError('Fixture setup is single use') + if os.geteuid() != 0: + raise PermissionError('Fixture must be hosted by the root oracle process') + if pwd.getpwnam('aien-agora').pw_uid != 976: + raise RuntimeError('Unexpected aien-agora UID') + if grp.getgrnam('aien-agora').gr_gid != 964: + raise RuntimeError('Unexpected aien-agora GID') + # Every mutable or executable service path is outside host /tmp, which + # PrivateTmp hides. No production state, env, unit or nginx file is used. + try: + self.runtime.mkdir(mode=0o755) + self._runtime_created = True + self.state.mkdir(mode=0o750) + self._state_created = True + os.chown(self.state, 976, 964) + executable = self.runtime / 'agora' + shutil.copyfile(self.backend, executable) + executable.chmod(0o755) + nginx = self.runtime / 'nginx' + shutil.copyfile(self.nginx, nginx) + nginx.chmod(0o755) + module = self.nginx.parent.parent / 'lib/nginx/modules/ngx_stream_module.so' + shutil.copyfile(module, self.runtime / module.name) + shutil.copyfile(Path(__file__).resolve(), self.runtime / 'tunnel.py') + self._provision_site() + self._call(['ip', 'netns', 'add', self.namespace]) + self._namespace_created = True + self._call(self.command(['ip', 'link', 'set', 'lo', 'up'])) + # These high ports exist only inside this fixture's isolated netns. + backend_port, frontend_port, tls_port, plain_port, normal_port = ( + 28132, 28443, 28444, 28080, 28445) + host_tls = self._reserve_host_port() + host_plain = self._reserve_host_port() + display_argv = (f'{executable} serve --state {self.state} ' + f'--listen 127.0.0.1 --port {backend_port} --bits 20') + self._write(self.runtime / 'runtime.env', + 'AGORA_LISTEN=127.0.0.1\n', 0o600) + template = (REPOSITORY / 'om/agora/deploy/aien-agora.service').read_text() + template = template.replace('StateDirectory=aien-agora', + 'StateDirectory=' + self.name) + template = template.replace('/var/lib/aien-agora', str(self.state)) + template = template.replace('/etc/aien-agora/runtime.env', + str(self.runtime / 'runtime.env')) + template = template.replace( + '/opt/aien/bin/agora serve --state ' + str(self.state) + + ' --listen ${AGORA_LISTEN} --port 18132 --bits 20', display_argv) + template = template.replace('Restart=always', 'Restart=no') + template = template.replace('[Service]\n', + '[Service]\nNetworkNamespacePath=/run/netns/' + self.namespace + '\n') + if '/opt/aien/' in template or '--port 18132' in template: + raise RuntimeError('Backend template relocation was incomplete') + # Exclusive paths ensure cleanup cannot acquire another owner's unit. + with self.unit_path.open('x') as stream: + stream.write(template) + self._unit_created = True + self.dropin_dir.mkdir(mode=0o755) + self._write_policy(['127.0.0.1/32', '127.0.0.2/32']) + nginx_config = self._provision_nginx(backend_port, frontend_port, + tls_port, plain_port, normal_port) + nginx_args = [str(nginx), '-p', str(self.runtime) + '/', + '-c', str(nginx_config)] + self.config = { + 'namespace': self.namespace, 'unit': self.unit, + 'state': str(self.state), 'executable': str(executable), + 'display_argv': display_argv, + 'fragment': str(self.unit_path), 'dropin': str(self.dropin), + 'backend_host': '127.0.0.1', 'backend_port': backend_port, + 'allowed_source': '127.0.0.2', 'denied_source': '127.0.0.3', + 'interface': 'lo', 'uid': 976, 'gid': 964, + 'tls_url': f'https://www.aienos.com:{host_tls}', + 'browser_url': f'https://www.aienos.com:{host_tls}/aienet/', + 'plain_url': f'http://127.0.0.1:{host_plain}', + 'browser_host': 'www.aienos.com', 'browser_address': '127.0.0.1', + 'curl_resolve': f'www.aienos.com:{host_tls}:127.0.0.1', + 'namespace_prefix': self.command([]), + 'host_tls_port': host_tls, 'host_plain_port': host_plain, + 'frontend_host': '127.0.0.1', 'frontend_port': frontend_port, + 'proxy_tls_port': tls_port, 'plain_port': plain_port, + 'normal_tls_port': normal_port, + 'normal_site_host': 'normal.aienet.invalid', + 'normal_site_path': '/normal-site-control.txt', + 'nginx_config': str(nginx_config), 'nginx_args': nginx_args, + 'nginx_pid_file': str(self.runtime / 'nginx.pid'), + 'certificate': str(self.runtime / 'cert.pem'), + 'logs': [str(self.runtime / 'access.log'), + str(self.runtime / 'error.log')], + 'temp_dirs': [str(self.runtime / name) for name in + ('body', 'proxy', 'fastcgi', 'uwsgi', 'scgi')], + 'runtime': str(self.runtime), 'routing_units': [], + 'copied_artifacts': [ + (str(executable), str(self.backend), 0o755), + (str(self.runtime / 'public/aienet/index.html'), str(self.page), 0o644), + (str(self.runtime / 'public/js/aienet.js'), str(self.client), 0o644)], + } + self._call(['systemctl', 'daemon-reload']) + self.start_backend() + self.start_routing() + self._setup = True + return self.config + except BaseException: + self.cleanup() + raise + + def _provision_site(self): + public = self.runtime / 'public' + public.mkdir(mode=0o755) + for name in ('assets', 'js', 'vendor', 'wasm'): + source = REPOSITORY / 'public' / name + if source.is_dir(): + shutil.copytree(source, public / name) + for source in (REPOSITORY / 'public').iterdir(): + if source.is_file() and source.suffix in ('.svg', '.ico', '.png'): + shutil.copyfile(source, public / source.name) + (public / 'aienet').mkdir() + shutil.copyfile(self.page, public / 'aienet/index.html') + shutil.copyfile(self.client, public / 'js/aienet.js') + self._write(public / 'normal-site-control.txt', 'activation fixture normal site\n') + self._write(public / 'index.html', + 'Fixture normal site' + '

activation fixture normal site

\n') + # Readable assets are separate from root-only scratch and private state. + for directory, subdirs, files in os.walk(public): + Path(directory).chmod(0o755) + for name in files: + (Path(directory) / name).chmod(0o644) + self._call(['openssl', 'req', '-x509', '-newkey', 'rsa:2048', '-nodes', + '-keyout', self.runtime / 'key.pem', + '-out', self.runtime / 'cert.pem', '-days', '1', + '-subj', '/CN=www.aienos.com', '-addext', + 'subjectAltName=DNS:www.aienos.com,DNS:normal.aienet.invalid']) + (self.runtime / 'key.pem').chmod(0o600) + + def _provision_nginx(self, backend, frontend, tls, plain, normal): + deploy = REPOSITORY / 'om/agora/deploy' + upstream = self.runtime / 'upstream.conf' + self._write(upstream, f'server 127.0.0.1:{backend};\n') + http = (deploy / 'nginx-agora-http.conf').read_text().replace( + '/etc/nginx/snippets/agora-upstream.conf', str(upstream)) + routes = (deploy / 'nginx-agora.conf').read_text() + # Preserve the reviewed route template; outgoing socket identity is a + # server-level directive inherited by every nested registration route. + for name in ('body', 'proxy', 'fastcgi', 'uwsgi', 'scgi'): + path = self.runtime / name + path.mkdir(mode=0o700) + os.chown(path, 976, 964) + for name in ('access.log', 'error.log'): + self._write(self.runtime / name, '', 0o600) + path = self.runtime / 'nginx.conf' + self._write(path, f'''load_module {self.runtime}/ngx_stream_module.so; +user aien-agora aien-agora; +pid {self.runtime}/nginx.pid; +lock_file {self.runtime}/nginx.lock; +error_log {self.runtime}/error.log notice; +worker_processes 1; +events {{ worker_connections 256; }} +stream {{ + map $ssl_preread_server_name $fixture_sni {{ + www.aienos.com 127.0.0.1:{tls}; + default 127.0.0.1:{normal}; + }} + server {{ + listen 127.0.0.1:{frontend}; + ssl_preread on; + proxy_protocol on; + proxy_pass $fixture_sni; + }} +}} +http {{ + default_type application/octet-stream; + types {{ text/html html; text/css css; application/javascript js; + image/svg+xml svg; application/wasm wasm; }} + log_format fixture '$remote_addr $request_method $uri $status'; + access_log {self.runtime}/access.log fixture; + client_body_temp_path {self.runtime}/body; + proxy_temp_path {self.runtime}/proxy; + fastcgi_temp_path {self.runtime}/fastcgi; + uwsgi_temp_path {self.runtime}/uwsgi; + scgi_temp_path {self.runtime}/scgi; + ssl_certificate {self.runtime}/cert.pem; + ssl_certificate_key {self.runtime}/key.pem; + ssl_protocols TLSv1.2 TLSv1.3; + {http} + server {{ + listen 127.0.0.1:{tls} ssl proxy_protocol; + listen 127.0.0.1:{plain}; + server_name www.aienos.com; + root {self.runtime}/public; + index index.html; + proxy_bind 127.0.0.2; + {routes} + location / {{ try_files $uri $uri/ =404; }} + }} + server {{ + listen 127.0.0.1:{normal} ssl proxy_protocol; + server_name normal.aienet.invalid; + root {self.runtime}/public; + location / {{ try_files $uri =404; }} + }} +}} +''') + baseline = path.read_text().replace(routes, ''' + location ^~ /agora/api/ { + access_log off; + error_log /dev/null crit; + add_header Cache-Control "no-store" always; + return 404; + } + location = /agora/api { + access_log off; + error_log /dev/null crit; + return 404; + } +''').replace(http, '') + self._write(self.runtime / 'nginx-baseline.conf', baseline) + return path + + def _write_policy(self, allow): + allowed = [] + permitted = {'127.0.0.1/32', '127.0.0.2/32', '127.0.0.3/32'} + for address in allow: + address = str(ipaddress.IPv4Network(address, strict=True)) + if address not in permitted or address in allowed: + raise ValueError('Only distinct fixture source host prefixes are allowed') + allowed.append(address) + self._write(self.dropin, '[Service]\nIPAddressAllow=\n' + + ''.join('IPAddressAllow=' + address + '\n' for address in allowed) + + 'IPAddressDeny=\nIPAddressDeny=any\n') + + def set_policy(self, allow): + """Real dedicated-unit policy change; callers label control phases.""" + self._require_open() + self._write_policy(allow) + self._call(['systemctl', 'daemon-reload']) + self.restart_backend() + + def _require_open(self): + if not self._unit_created or self._closed: + raise RuntimeError('Fixture unit is not provisioned') + + def start_backend(self): + self._require_open() + self.config['journal_since'] = time.strftime('%Y-%m-%d %H:%M:%S UTC', time.gmtime()) + self._call(['systemctl', 'start', self.unit]) + self._refresh_backend_identity() + + def restart_backend(self): + self._require_open() + self.config['journal_since'] = time.strftime('%Y-%m-%d %H:%M:%S UTC', time.gmtime()) + self._call(['systemctl', 'restart', self.unit]) + self._refresh_backend_identity() + + def _refresh_backend_identity(self): + result = self._call(['systemctl', 'show', self.unit, '-p', 'MainPID', + '-p', 'ControlGroup']) + fields = dict(line.split('=', 1) for line in result.stdout.decode().splitlines() + if '=' in line) + pid = int(fields.get('MainPID', '0')) + if pid <= 0: + raise RuntimeError('Fixture backend has no MainPID; readiness is not proven') + self.config['backend_pid'] = pid + self.config['backend_cgroup'] = fields['ControlGroup'] + + def _start_routing_unit(self, suffix, argv, namespace=False): + unit = self.name + '-' + suffix + '.service' + self._routing_units.append(unit) + args = ['systemd-run', '--quiet', '--unit=' + unit, '--collect', + '--service-type=exec', '--property=Restart=no', + '--property=StandardOutput=null', '--property=StandardError=null'] + if namespace: + args.append('--property=NetworkNamespacePath=/run/netns/' + self.namespace) + self._call(args + ['--', *map(str, argv)]) + return unit + + def start_routing(self): + if self._routing_units or self._closed: + raise RuntimeError('Routing already started or fixture closed') + nginx_unit = self._start_routing_unit( + 'nginx', self.config['nginx_args'] + ['-g', 'daemon off;'], namespace=True) + # Wait only for our nginx pidfile, not a backend readiness verdict. + pidfile = Path(self.config['nginx_pid_file']) + deadline = time.monotonic() + 10 + while not pidfile.exists(): + if time.monotonic() >= deadline: + raise RuntimeError('Fixture nginx did not create its pidfile') + time.sleep(0.05) + self.config['nginx_pid'] = int(pidfile.read_text().strip()) + actual = self._call(['systemctl', 'show', nginx_unit, '-p', 'MainPID', + '--value']).stdout.strip() + if int(actual) != self.config['nginx_pid']: + raise RuntimeError('Fixture nginx pidfile does not match its unit MainPID') + self.config['tunnel_pids'] = {} + for suffix, host_key, destination in ( + ('tls', 'host_tls_port', self.config['frontend_port']), + ('plain', 'host_plain_port', self.config['plain_port'])): + port = self.config[host_key] + self._release_port(port) + tunnel_unit = self._start_routing_unit( + suffix, [sys.executable, self.runtime / 'tunnel.py', + '--tunnel', '--namespace', self.namespace, + '--listen-port', str(port), '--destination-port', str(destination)]) + # A readiness file is written only after bind. Match its PID to the + # dedicated unit rather than accepting any other host port listener. + ready = self.runtime / f'tunnel-{port}.ready' + deadline = time.monotonic() + 10 + while not ready.exists(): + if time.monotonic() >= deadline: + raise RuntimeError('Fixture host tunnel did not bind') + time.sleep(0.05) + pid = int(ready.read_text()) + actual = self._call(['systemctl', 'show', tunnel_unit, '-p', 'MainPID', + '--value']).stdout.strip() + if pid <= 0 or int(actual) != pid: + raise RuntimeError('Fixture tunnel readiness does not match its MainPID') + self.config['tunnel_pids'][suffix] = pid + self.config['routing_units'] = self._routing_units.copy() + + def enable_backend(self): + """Exercise enable-last without leaving a persistent boot target.""" + self._require_open() + self._runtime_enabled = True + self._call(['systemctl', 'enable', '--runtime', self.unit]) + + def _disable_backend(self): + if self._runtime_enabled: + self._call(['systemctl', 'disable', '--runtime', self.unit]) + self._runtime_enabled = False + + def rollback(self): + """Remove registration, keep ordinary site/tunnels and preserve profiles.""" + self._require_open() + active = Path(self.config['nginx_config']) + baseline = self.runtime / 'nginx-baseline.conf' + # Both candidates were constructed from the same reviewed input. + active.write_bytes(baseline.read_bytes()) + master = self.config['nginx_pid'] + children = Path(f'/proc/{master}/task/{master}/children') + old_workers = children.read_text().split() + self._call(self.command(self.config['nginx_args'] + ['-s', 'reload'])) + deadline = time.monotonic() + 15 + while any(Path('/proc', pid).exists() for pid in old_workers): + if time.monotonic() >= deadline: + raise RuntimeError('Fixture rollback workers did not drain') + time.sleep(0.05) + self._call(['systemctl', 'stop', self.unit]) + self._disable_backend() + + def _stop_owned_units(self): + errors = [] + for unit in reversed(self._routing_units): + result = self._call(['systemctl', 'stop', unit], check=False) + if result.returncode: + # --collect may already have unloaded a failed transient unit. + state = self._call(['systemctl', 'show', unit, '-p', 'LoadState', + '--value'], check=False) + if state.stdout.strip() != b'not-found': + errors.append(unit) + if self._unit_created: + result = self._call(['systemctl', 'stop', self.unit], check=False) + if result.returncode: + errors.append(self.unit) + if errors: + raise RuntimeError('Could not stop owned fixture units: ' + ', '.join(errors)) + + def cleanup(self): + if self._closed: + return + # Never unlink files or namespace while an owned service may still run. + self._stop_owned_units() + self._disable_backend() + for sock in self._ports: + sock.close() + self._ports.clear() + if self._namespace_created: + self._call(['ip', 'netns', 'delete', self.namespace]) + self._namespace_created = False + if self._unit_created: + if self.dropin_dir.exists(): + shutil.rmtree(self.dropin_dir) + self.unit_path.unlink() + self._unit_created = False + self._call(['systemctl', 'daemon-reload']) + self._call(['systemctl', 'reset-failed', self.unit], check=False) + if self._state_created: + if not self._state_retained: + retained = self.root / 'retained-state' + shutil.copytree(self.state, retained) + for directory, _, files in os.walk(retained): + Path(directory).chmod(0o700) + for name in files: + (Path(directory) / name).chmod(0o600) + self._state_retained = True + shutil.rmtree(self.state) + self._state_created = False + if self._runtime_created: + shutil.rmtree(self.runtime) + self._runtime_created = False + self._closed = True + + +def _relay(client, namespace_fd, destination_port): + """A byte relay to one compile-time-selected loopback fixture destination.""" + remote = None + try: + # setns affects this worker's OS thread, not the host acceptor thread. + # Use libc because supported Python versions do not all expose os.setns. + libc = ctypes.CDLL(None, use_errno=True) + if libc.setns(namespace_fd, 0) != 0: + raise OSError(ctypes.get_errno(), 'Could not enter fixture namespace') + remote = socket.create_connection(('127.0.0.1', destination_port), timeout=10) + client.settimeout(30) + remote.settimeout(30) + with selectors.DefaultSelector() as ready: + ready.register(client, selectors.EVENT_READ, remote) + ready.register(remote, selectors.EVENT_READ, client) + while ready.get_map(): + events = ready.select(timeout=30) + if not events: + return + for key, _ in events: + data = key.fileobj.recv(65536) + if not data: + ready.unregister(key.fileobj) + key.data.shutdown(socket.SHUT_WR) + else: + key.data.sendall(data) + except OSError: + # Neither payloads nor connection exceptions are logged. + pass + finally: + client.close() + if remote is not None: + remote.close() + + +def _tunnel_main(): + parser = argparse.ArgumentParser() + parser.add_argument('--tunnel', action='store_true', required=True) + parser.add_argument('--namespace', required=True) + parser.add_argument('--listen-port', required=True, type=int) + parser.add_argument('--destination-port', required=True, type=int) + args = parser.parse_args() + if not args.namespace.startswith('aien-agora-oracle-') or not all( + char in '0123456789abcdef' for char in args.namespace.removeprefix( + 'aien-agora-oracle-')): + parser.error('Not a fixture namespace') + if args.destination_port not in (28443, 28080): + parser.error('Destination is not an allowed fixture frontend') + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as listener: + listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + listener.bind(('127.0.0.1', args.listen_port)) + listener.listen(32) + namespace_fd = os.open('/run/netns/' + args.namespace, os.O_RDONLY) + ready = Path(__file__).resolve().parent / f'tunnel-{args.listen_port}.ready' + with ready.open('x') as stream: + stream.write(str(os.getpid())) + try: + while True: + client, _ = listener.accept() + threading.Thread(target=_relay, args=(client, namespace_fd, + args.destination_port), daemon=True).start() + finally: + os.close(namespace_fd) + + +if __name__ == '__main__': + _tunnel_main() diff --git a/scripts/agora_activation_observers.py b/scripts/agora_activation_observers.py new file mode 100755 index 0000000..d6622ee --- /dev/null +++ b/scripts/agora_activation_observers.py @@ -0,0 +1,392 @@ +#!/usr/bin/env python3 +"""Read-only activation observers shared by isolated rehearsal and live gates. + +These host tools are verification oracles, not the Omega registration backend. +No payload capture, response-body logging or implicit mutation retries. +""" +from contextlib import contextmanager +from datetime import datetime, timezone +import json +import hashlib +import os +from pathlib import Path +import re +import select +import subprocess +import stat +import time + + +class Refused(RuntimeError): + pass + + +class Commands: + def __init__(self): + self.records = [] + + def __call__(self, argv, input=None, timeout=30, check=True, private=False, + read_only=False): + attempts = 3 if read_only and argv[0] == 'ssh' else 1 + for attempt in range(1, attempts + 1): + record = {'command': [str(arg) for arg in argv], 'attempt': attempt, + 'utc': datetime.now(timezone.utc).isoformat()} + self.records.append(record) + try: + result = subprocess.run(argv, input=input, capture_output=True, + timeout=timeout) + except subprocess.TimeoutExpired: + record['result'] = 'TIMEOUT' + if attempt == attempts: + raise + continue + record['exit'] = result.returncode + if not private: + record['stdout'] = result.stdout.decode(errors='replace') + record['stderr'] = result.stderr.decode(errors='replace') + else: + record['output'] = 'PRIVATE_NOT_RECORDED' + if check and result.returncode: + if attempt != attempts: + continue + raise Refused('Command failed: ' + str(argv[:3]) + + ' exit=' + str(result.returncode)) + return result + raise Refused('Read-only SSH attempts exhausted') + + +def properties(raw): + result = {} + for line in raw.splitlines(): + if not line: + continue + key, separator, value = line.partition('=') + if not separator or key in result: + raise Refused('Malformed or duplicate property: ' + key) + result[key] = value + return result + + +class Observers: + def __init__(self, run, native, startup, prefix=(), sudo=('sudo', '-n')): + self.run = run + self.native = str(native) + self.startup_native = str(startup) + self.prefix = list(prefix) + self.sudo = list(sudo) + self.observations = [] + + def command(self, argv): + return self.prefix + list(argv) + + def text(self, argv, **kwargs): + return self.run(argv, **kwargs).stdout.decode() + + def show(self, unit, *fields): + argv = ['systemctl', 'show', unit] + for field in fields: + argv += ['-p', field] + return self.text(argv) + + def native_check(self, mode, *args, statuses=(0,)): + result = self.run([self.native, mode, *map(str, args)], check=False) + if result.returncode not in statuses: + raise Refused('Native ' + mode + ' refused: ' + str(result.returncode)) + return result.returncode + + def startup(self, unit, executable, endpoint): + deadline = time.monotonic_ns() + 10000000000 + pid = int(properties(self.show(unit, 'MainPID'))['MainPID']) + if pid <= 0: + raise Refused('No positive initial MainPID') + while time.monotonic_ns() < deadline: + before = properties(self.show(unit, 'MainPID'))['MainPID'] + exe_before = self.text(self.sudo + ['readlink', '-f', f'/proc/{pid}/exe']) + ps_before = self.text(['ps', '-p', str(pid), '-o', 'euid=,egid=']) + ss = self.text(self.command(self.sudo + + ['ss', '-H', '-ltnp', '( sport = :' + endpoint.rsplit(':', 1)[1] + ' )'])) + exe_after = self.text(self.sudo + ['readlink', '-f', f'/proc/{pid}/exe']) + ps_after = self.text(['ps', '-p', str(pid), '-o', 'euid=,egid=']) + after = properties(self.show(unit, 'MainPID'))['MainPID'] + elapsed = 10000000000 - (deadline - time.monotonic_ns()) + row = {'pid': pid, 'before': before, 'exe_before': exe_before, + 'ps_before': ps_before, 'listener': ss, 'exe_after': exe_after, + 'ps_after': ps_after, 'after': after, 'elapsed_ns': elapsed} + self.observations.append(row) + status = self.native_check('snapshot', pid, before, exe_before, + ps_before, ss, exe_after, ps_after, after, + executable, 976, 964, endpoint, elapsed, + 10000000000, statuses=(0, 2)) + if time.monotonic_ns() >= deadline: + raise Refused('Late startup observation') + if status == 0: + result = self.run([self.startup_native, str(deadline), + '1', '976', '964', '1'], check=False) + if result.returncode != 1 or time.monotonic_ns() >= deadline: + raise Refused('Startup policy did not return READY in time') + if int(properties(self.show(unit, 'MainPID'))['MainPID']) != pid: + raise Refused('MainPID changed after readiness') + return pid + time.sleep(0.01) + raise Refused('Startup deadline expired') + + def effective(self, config, pid, allowed_source=None): + proxy = allowed_source or config['allowed_source'] + raw = self.show(config['unit'], 'MainPID', 'User', 'Group', 'FragmentPath', + 'DropInPaths', 'IPAddressAllow', 'IPAddressDeny') + actual = properties(raw) + self.native_check('unit', raw, pid, 'aien-agora', 'aien-agora', + proxy + '/32', '127.0.0.1/32', + config.get('fragment', actual['FragmentPath']), + config.get('dropin', actual['DropInPaths'])) + state = self.show(config['unit'], 'ActiveState', 'SubState', + 'IPAccounting', 'ControlGroup') + group = '/system.slice/' + config['unit'] + self.native_check('state', state, group) + for ancestor in ('-.slice', 'system.slice'): + ancestors = self.text(['systemctl', 'show', '-p', 'IPAddressAllow', + '-p', 'IPAddressDeny', '--', ancestor]) + self.native_check('ancestors', ancestors, 1) + execution = self.show(config['unit'], 'ExecStart') + self.native_check('exec', execution, config['executable'], + config['display_argv'], pid) + actual_group = self.text(self.sudo + ['cat', f'/proc/{pid}/cgroup']) + state_info = Path(config['state']).stat() + if (not stat.S_ISDIR(state_info.st_mode) or state_info.st_uid != 976 + or state_info.st_gid != 964 or stat.S_IMODE(state_info.st_mode) != 0o750): + raise Refused('State directory identity or permissions differ from the approved policy') + activation = properties(self.show(config['unit'], 'TriggeredBy')) + if activation.get('TriggeredBy') != '': + raise Refused('Unexpected socket or other activation trigger') + sockets = self.text(self.command(self.sudo + ['ss', '-H', '-ltnp'])) + owned_rows = [line for line in sockets.splitlines() + if re.search(r'\bpid=' + str(pid) + r',', line)] + expected_endpoint = config['backend_host'] + ':' + str(config['backend_port']) + if len(owned_rows) != 1 or owned_rows[0].split()[3] != expected_endpoint: + raise Refused('Alternate or unexpected backend listener') + self.observations.append({'state_directory_mode': '750', + 'state_uid': state_info.st_uid, + 'state_gid': state_info.st_gid, + 'owned_listener_count': len(owned_rows), + 'activation_triggers': ''}) + if '0::' + group not in actual_group.splitlines(): + raise Refused('Process does not belong to observed cgroup') + if config.get('namespace'): + actual_ns = self.text(self.sudo + ['stat', '-Lc', '%i', + f'/proc/{pid}/ns/net']).strip() + expected_ns = self.text(self.sudo + ['stat', '-Lc', '%i', + '/run/netns/' + config['namespace']]).strip() + if int(actual_ns) != int(expected_ns): + raise Refused('Backend not inside fixture network namespace') + bpf = json.loads(self.text(self.sudo + ['bpftool', '-j', 'cgroup', 'show', + '/sys/fs/cgroup' + group, 'effective'])) + if ({item['attach_type'] for item in bpf} != + {'cgroup_inet_ingress', 'cgroup_inet_egress'} or + any(int(item['id']) <= 0 for item in bpf)): + raise Refused('Effective ingress/egress BPF not proved') + self.observations.append({'gate': 'effective', 'unit': raw, 'state': state, + 'exec': execution, 'bpf': bpf}) + journal = self.text(self.sudo + ['journalctl', '--unit', config['unit'], + '--since', config['journal_since'], '--no-pager', '-o', 'cat'], + private=True) + if re.search(r'(?i)(not supported|unsupported|failed to attach|failed to apply).*(BPF|IP firewall)|' + r'(BPF|IP firewall).*(not supported|unsupported|failed to attach|failed to apply)', journal): + raise Refused('Current invocation reports unsupported or failed IP filtering') + self.observations.append({'current_invocation_filter_warning': 'NONE', + 'since': config['journal_since']}) + return bpf + + def copied_artifacts(self, entries): + observed = [] + for destination, source, mode in entries: + target = Path(destination) + info = target.lstat() + digest = hashlib.sha256(target.read_bytes()).hexdigest() + expected = hashlib.sha256(Path(source).read_bytes()).hexdigest() + if (not stat.S_ISREG(info.st_mode) or info.st_uid != 0 or info.st_gid != 0 + or stat.S_IMODE(info.st_mode) != mode or digest != expected): + raise Refused('Copied artifact bytes, identity or mode do not match the approved input') + observed.append({'path': str(target), 'source': str(source), + 'sha256': digest, 'uid': info.st_uid, + 'gid': info.st_gid, 'mode': oct(mode)}) + self.observations.append({'copied_artifacts': observed}) + + @contextmanager + def capture(self, interface, expression): + argv = self.command(self.sudo + ['timeout', '10', 'tcpdump', '-ni', + interface, '-nn', '-tt', '-S', '-l', expression]) + record = {'command': argv, 'kind': 'passive_packet_metadata'} + self.run.records.append(record) + proc = subprocess.Popen(argv, stdout=subprocess.PIPE, + stderr=subprocess.PIPE, bufsize=0) + error = b'' + deadline = time.monotonic_ns() + 10000000000 + try: + while b'listening on ' + interface.encode() not in error: + if proc.poll() is not None or time.monotonic_ns() >= deadline: + raise Refused('Capture not ready') + ready, _, _ = select.select([proc.stderr], [], [], 0.1) + if ready: + error += os.read(proc.stderr.fileno(), 8192) + observation = {} + yield observation + out, rest = proc.communicate(timeout=12) + error += rest + record.update(exit=proc.returncode, stdout=out.decode(), + stderr=error.decode()) + if proc.returncode not in (0, 124): + raise Refused('Passive capture failed') + observation['packets'] = out.decode() + finally: + if proc.poll() is None: + proc.terminate() + out, rest = proc.communicate(timeout=5) + record.update(exit=proc.returncode, stdout=out.decode(), + stderr=(error + rest).decode(), interrupted=True) + + def syn_probe(self, config, source, request, accept): + target, port = config['backend_host'], config['backend_port'] + expression = (f'tcp port {port} and host {source} and ' + '(tcp[tcpflags] & tcp-syn != 0)') + with self.capture(config['interface'], expression) as observation: + response = request() + packets = [] + for match in re.finditer(r'IP (\d+\.\d+\.\d+\.\d+)\.(\d+) > ' + r'(\d+\.\d+\.\d+\.\d+)\.(\d+): ' + r'Flags \[([^\]]+)\]', observation['packets']): + packets.append(match.groups()) + syn = [row for row in packets if row[0] == source and row[2] == target + and int(row[3]) == port and 'S' in row[4] and '.' not in row[4]] + ack = [row for row in packets if row[0] == target and int(row[1]) == port + and row[2] == source and 'S' in row[4] and '.' in row[4]] + if not syn or bool(ack) != accept: + raise Refused('Source SYN/SYNACK proof disagrees with expected policy') + if response.returncode != (0 if accept else 28): + raise Refused('Source HTTP outcome disagrees with expected policy') + if response.stdout.strip() != (b'200' if accept else b'000'): + raise Refused('Unexpected challenge status') + result = {'source': source, 'syn': len(syn), 'synack': len(ack), + 'accept': accept} + self.observations.append(result) + return result + + def counted_get(self, config, request, expected=1): + expression = (f'tcp dst port {config["backend_port"]} and src host ' + f'{config["allowed_source"]} and ' + 'tcp[((tcp[12] & 0xf0)>>2):4] = 0x47455420') + with self.capture(config['interface'], expression) as observation: + result = request() + identities = set() + for match in re.finditer(r'IP (\S+) > (\S+): .*seq (\d+):\d+', + observation['packets']): + identities.add(match.groups()) + if callable(expected): + expected = expected(result) + if len(identities) != expected: + raise Refused('Independent backend GET count: ' + str(len(identities))) + self.observations.append({'backend_gets': len(identities)}) + return result + + def reload(self, config): + args = config['nginx_args'] + self.run(self.command(self.sudo + args + ['-t'])) + master = int(config['nginx_pid']) + def workers(): + rows = self.text(self.sudo + ['ps', '--ppid', str(master), '-o', + 'pid=,args='], check=False) + result = {} + for row in rows.splitlines(): + pid, title = row.strip().split(maxsplit=1) + if 'nginx: worker process' in title: + result[int(pid)] = 'shutting down' in title + return result + def listeners(): + raw = self.text(self.command(self.sudo + ['ss', '-H', '-ltnp'])) + return {int(pid) for pid in re.findall(r'\bpid=(\d+),', raw)} + before = workers() + old_active = {pid for pid, draining in before.items() if not draining} + if not old_active or any(pid in listeners() for pid, draining in + before.items() if draining): + raise Refused('Initial nginx worker/listener state invalid') + self.run(self.command(self.sudo + args + ['-s', 'reload'])) + deadline = time.monotonic_ns() + 30000000000 + while time.monotonic_ns() < deadline: + current = workers() + listening = listeners() + new = {pid for pid, draining in current.items() + if not draining and pid not in before} + ready = new and all(pid not in current or + (current[pid] and pid not in listening) + for pid in old_active) + if ready and time.monotonic_ns() < deadline: + self.observations.append({'reload_before': before, + 'reload_after': current, 'new_active': sorted(new), + 'listening_pids': sorted(listening)}) + return + time.sleep(0.01) + raise Refused('Nginx worker adoption deadline expired') + + def effective_logging(self, config): + raw = self.text(self.command(self.sudo + config['nginx_args'] + ['-T']), + private=True) + sinks = set() + access = set() + temps = set() + for kind, arguments in re.findall( + r'(?m)^\s*(access_log|error_log|[a-z_]+_temp_path)\s+([^;\n]+);', raw): + path = arguments.split()[0] + if kind.endswith('_temp_path'): + temps.add(path) + elif path not in ('off', '/dev/null'): + if not path.startswith('/') or '$' in path: + raise Refused('Effective log sink cannot be directly inspected') + sinks.add(path) + if kind == 'access_log': + access.add(path) + if sinks != set(config['logs']) or temps != set(config['temp_dirs']): + raise Refused('Declared log/temp paths differ from effective nginx configuration') + config['access_logs'] = sorted(access) + self.observations.append({'effective_log_sinks': sorted(sinks), + 'effective_temp_dirs': sorted(temps)}) + + def journal_privacy(self, config, markers): + units = [config['unit'], *config.get('routing_units', [])] + argv = self.sudo + ['journalctl'] + for unit in units: + argv += ['--unit', unit] + result = self.run(argv + ['--since', config['journal_since'], + '--no-pager', '-o', 'cat'], private=True) + if any(marker in result.stdout for marker in markers): + raise Refused('Privacy marker found in fixture service journal') + self.observations.append({'journal_privacy': 'PASS', 'units': units, + 'since': config['journal_since'], + 'markers': len(markers)}) + + def privacy(self, logs, temp_dirs, markers): + paths = list(logs) + for directory in temp_dirs: + result = self.run(self.sudo + ['find', str(directory), '-type', 'f', + '-print0']) + paths += [name.decode() for name in result.stdout.split(b'\0') if name] + if not paths: + raise Refused('No effective log sinks observed') + result = self.run(self.sudo + ['grep', '-F', '-l', '-f', '-', '--', *paths], + input=b'\n'.join(markers) + b'\n', check=False, + private=True) + if result.returncode != 1: + raise Refused('Privacy marker found or effective sink unreadable') + self.observations.append({'privacy': 'PASS', 'log_sinks': list(logs), + 'temp_dirs': list(map(str, temp_dirs)), + 'markers': len(markers)}) + + +def save_private(path, value): + target = Path(path) + descriptor = os.open(target, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + try: + os.write(descriptor, value.encode()) + os.fsync(descriptor) + finally: + os.close(descriptor) + if target.stat().st_mode & 0o077: + raise Refused('Recovery material permissions not private') diff --git a/scripts/allen/science/.crumb b/scripts/allen/science/.crumb index ff09904..9e26727 100644 --- a/scripts/allen/science/.crumb +++ b/scripts/allen/science/.crumb @@ -10,14 +10,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-26T17:20:08Z", + "compiled_at": "2026-10-30T02:44:24Z", "compiler": "crumb-compile/1", - "digest": "sha256:d19bb51f24d3c0b551f4664adba478bf03fed9ac1585a80f23f7fe8f34466813", + "digest": "sha256:b77336127516b827d0e7a19a214d6bd15665865f7fd2f2d4eb323c6eca9c3893", "evidence_files": 5, "evidence_root": "sha256:654dedeb42c301ff83a0fe00d66a40f27a6fa376e3eb537f00d1b369fe1aa476", - "files": 24, - "generated_at_commit": "7b36df545ed14c085c0509be39c1a76865a3fb28", - "source_tree": "sha256:d04dec59525df01aa3426fd02b8d20c4cdb53040cfa66d460806cd545ba26659" + "files": 26, + "generated_at_commit": "6dc2ff3c49dd486b51fd71da0d8a2cb6a7603307", + "source_tree": "sha256:490150aa44dea3df79e395be99bbcaa706d191e3649bc1a36c295a489bd62728" } }, "invariants": [ diff --git a/scripts/test-agora-activation.py b/scripts/test-agora-activation.py new file mode 100755 index 0000000..387060f --- /dev/null +++ b/scripts/test-agora-activation.py @@ -0,0 +1,404 @@ +#!/usr/bin/env python3 +"""Root-only isolated activation rehearsal and private browser control. + +Only the Fixture adapter performs mutations. All observations use the same +file-backed code intended for live activation; no production paths are accepted. +""" +import argparse +from concurrent.futures import ThreadPoolExecutor +import hashlib +import json +import os +from pathlib import Path +import signal +import socket +import sys + +from agora_activation_namespace import Fixture +from agora_activation_observers import Commands, Observers, Refused, properties, save_private + + +class Rehearsal: + def __init__(self, args): + self.root = Path(args.root) + self.root.mkdir(mode=0o700, parents=True, exist_ok=False) + self.run = Commands() + self.fixture = Fixture(self.root, Path(args.backend), Path(args.nginx), self.run, + Path(args.page), Path(args.client)) + self.native, self.startup = args.native, args.startup + self.gates = [] + self.keys = [] + self.pre_browser_passed = False + self.browser_passed = False + self.markers = [b'ACTIVATION_PUBLIC_BODY_SENTINEL', + b'ACTIVATION_SYNTHETIC_KEY_SENTINEL'] + self.config = {} + prefix = self.fixture.command([]) + self.observer = Observers(self.run, self.native, self.startup, prefix=prefix) + self.pid = None + + def setup(self): + self.config = self.fixture.setup() + + def gate(self, name, value=None): + self.gates.append({'gate': name, 'status': 'PASS', 'observation': value}) + + def startup_check(self, narrow=False): + self.pid = self.observer.startup(self.config['unit'], + self.config['executable'], + self.config['backend_host'] + ':' + str(self.config['backend_port'])) + self.observer.effective(self.config, self.pid, + '127.0.0.1' if narrow else None) + return self.pid + + def direct(self, source): + return self.run(self.fixture.command(['curl', '--silent', '--show-error', + '--max-time', '5', '--interface', source, '--output', '/dev/null', + '--write-out', '%{http_code}', + 'http://' + self.config['backend_host'] + ':' + + str(self.config['backend_port']) + '/agora/api/challenge']), check=False) + + def request(self, path, method='GET', body=None, plain=False, headers=()): + base = self.config['plain_url'] if plain else self.config['tls_url'] + argv = ['curl', '--silent', '--show-error', '--max-time', '10', + '--insecure', '--noproxy', '*', '--include'] + if not plain and self.config.get('curl_resolve'): + argv += ['--resolve', self.config['curl_resolve']] + argv += ['--head'] if method == 'HEAD' else ['--request', method] + for header in headers: + argv += ['--header', header] + if body is not None: + argv += ['--data-binary', '@-'] + argv.append(base.rstrip('/') + path) + result = self.run(argv, input=body, private=True) + head, separator, content = result.stdout.partition(b'\r\n\r\n') + if not separator: + raise Refused('Incomplete actual TLS HTTP response') + status = int(head.splitlines()[0].split()[1]) + fields = {} + for line in head.splitlines()[1:]: + key, sep, value = line.partition(b':') + if not sep: + raise Refused('Malformed HTTP header') + fields.setdefault(key.lower(), []).append(value.strip().lower()) + return status, fields, content + + @staticmethod + def expected(response, code): + status, headers, _ = response + if status != code: + raise Refused('HTTP expected ' + str(code) + ', observed ' + str(status)) + if headers.get(b'cache-control') != [b'no-store']: + raise Refused('No-store absent or ambiguous') + if headers.get(b'x-content-type-options') != [b'nosniff']: + raise Refused('Nosniff absent or ambiguous') + + def no_upstream(self, request): + expression = 'tcp dst port ' + str(self.config['backend_port']) + with self.observer.capture(self.config['interface'], expression) as observed: + response = request() + import re + if any(int(size) > 0 for size in re.findall(r'\blength (\d+)\b', observed['packets'])): + raise Refused('Blocked route generated upstream payload') + return response + + def pre_browser(self): + self.observer.copied_artifacts(self.config['copied_artifacts']) + self.gate('copied backend/page/client exact source bytes, root ownership and regular-file modes') + self.startup_check() + self.gate('bounded startup/effective native guards/current namespace/cgroup BPF') + # Independently establish .3 reachability to this exact endpoint in a + # separate declared control phase, then restore the exact acceptance set. + self.fixture.set_policy(['127.0.0.1/32', '127.0.0.2/32', '127.0.0.3/32']) + self.observer.startup(self.config['unit'], self.config['executable'], + self.config['backend_host'] + ':' + str(self.config['backend_port'])) + reachable = self.observer.syn_probe(self.config, '127.0.0.3', + lambda: self.direct('127.0.0.3'), True) + self.gate('independent same-endpoint second-source reachability control', reachable) + self.fixture.set_policy(['127.0.0.1/32', '127.0.0.2/32']) + self.startup_check() + for source, accept in [('127.0.0.2', True), ('127.0.0.3', False)]: + observation = self.observer.syn_probe(self.config, source, + lambda source=source: self.direct(source), accept) + self.gate('actual source-bound packet allow/deny', observation) + self.fixture.set_policy(['127.0.0.1/32']) + self.startup_check(narrow=True) + self.observer.syn_probe(self.config, '127.0.0.2', + lambda: self.direct('127.0.0.2'), False) + self.gate('independent real BPF denial with no firewall mutation') + self.fixture.set_policy(['127.0.0.1/32', '127.0.0.2/32']) + self.startup_check() + self.observer.syn_probe(self.config, '127.0.0.2', + lambda: self.direct('127.0.0.2'), True) + self.gate('exact service policy restored and allowed source recovers') + self.observer.reload(self.config) + self.expected(self.observer.counted_get(self.config, + lambda: self.request('/agora/api/challenge')), 200) + self.gate('nginx active-worker adoption plus independently counted TLS GET') + refused = [('/agora/api/challenge', 'POST', 405), + ('/agora/api/hello', 'GET', 405), + ('/agora/api/agent/0123456789abcdef', 'POST', 405), + ('/agora/api/agent/ABCDEF0123456789', 'GET', 404), + ('/agora/api/agent/0123', 'GET', 404), + ('/agora/api/challenge/extra', 'GET', 404), + ('/agora/api/import', 'POST', 404), + ('/agora/api/hello/', 'POST', 404)] + refused += [(path, 'HEAD', 405) for path in ( + '/agora/api/challenge', '/agora/api/hello', + '/agora/api/agent/0123456789abcdef')] + refused += [(path, 'POST', 404) for path in ( + '/agora/api/post', '/agora/api/note', '/agora/api/peer', + '/agora/api/stream', '/agora/api/other')] + refused += [(path, 'GET', 404) for path in ( + '/agora/api', '/agora/api/agent/0123456789abcdef/extra')] + for path, method, code in refused: + response = self.no_upstream(lambda path=path, method=method: + self.request(path, method)) + self.expected(response, code) + for path, method in (('/agora/api/challenge', 'GET'), + ('/agora/api/hello', 'POST'), + ('/agora/api/agent/0123456789abcdef', 'GET')): + self.expected(self.no_upstream( + lambda path=path, method=method: self.request(path, method, plain=True)), 503) + oversized = self.markers[0] * 1024 + self.expected(self.no_upstream(lambda: self.request('/agora/api/hello', + 'POST', oversized)), 413) + self.gate('actual TLS method/id/trailing/disabled/oversize and non-PROXY refusals, zero upstream payload') + synthetic = b'ACTIVATION_PUBLIC_BODY_SENTINEL\nkey ACTIVATION_SYNTHETIC_KEY_SENTINEL\n' + self.observer.effective_logging(self.config) + self.expected(self.request('/agora/api/hello', 'POST', synthetic), 400) + self.gate('synthetic body/key real backend failure path') + # Browser gates run before quota exhaustion; these requests preserve the + # real client bucket rather than relying on arbitrary forged headers. + self.observer.privacy(self.config['logs'], self.config['temp_dirs'], self.markers) + self.observer.journal_privacy(self.config, self.markers) + self.gate('effective actual fixture access/error/temp sinks have no synthetic body/key markers') + # Challenge the real sink scanner, not a canned privacy verdict. + control = Path(self.config['temp_dirs'][0]) / ('privacy-control-' + self.fixture.ident) + try: + with control.open('xb') as stream: + stream.write(self.markers[0]) + try: + self.observer.privacy(self.config['logs'], self.config['temp_dirs'], self.markers) + except Refused: + self.gate('privacy scanner rejects an actual marker in an effective temporary-body sink') + else: + raise Refused('Privacy scanner accepted its marker control') + finally: + control.unlink(missing_ok=True) + self.pre_browser_passed = True + return {'gates': self.gates, 'config': self.config} + + def save_key(self, key): + if not isinstance(key, str) or not key or '\n' in key: + raise Refused('Invalid private recovery material') + path = self.root / ('recovery-' + str(len(self.keys)) + '.key') + save_private(path, key) + if path.stat().st_uid != 0: + raise Refused('Recovery file is not root-owned') + self.keys.append(path) + return {'path': str(path), 'mode': '600', 'owner': 'root'} + + def restart(self): + self.fixture.restart_backend() + self.startup_check() + return {'status': 'READY'} + + def read_profile(self, identity): + if len(identity) != 16 or any(ch not in '0123456789abcdef' for ch in identity): + raise Refused('Malformed public profile id') + response = self.request('/agora/api/agent/' + identity) + self.expected(response, 200) + return response[2].decode() + + def after_browser(self, browser_result): + if not self.pre_browser_passed or browser_result.get('status') != 'PASS': + raise Refused('Full pre-browser and browser sequence must pass') + if not self.keys: + raise Refused('Browser did not preserve actual recovery material') + self.gate('real browser consent/ack/readback/uncertainty/durability', browser_result) + def burst(): + def forged(index): + response = self.request('/agora/api/challenge', headers=( + 'X-Real-IP: 203.0.113.' + str(index), + 'X-Forwarded-For: 198.51.100.' + str(index))) + if response[0] not in (200, 429): + raise Refused('Unexpected actual TLS quota response') + self.expected(response, response[0]) + return response[0] + with ThreadPoolExecutor(max_workers=32) as workers: + return list(workers.map(forged, range(1, 33))) + statuses = self.observer.counted_get( + self.config, burst, expected=lambda rows: rows.count(200)) + if not statuses.count(200) or not statuses.count(429): + raise Refused('Forged headers did not exercise the shared real-client bucket') + self.gate('actual TLS forged identity headers share quota; refusals produce zero upstream requests', + {'accepted': statuses.count(200), 'limited': statuses.count(429)}) + markers = self.markers + [path.read_bytes() for path in self.keys] + self.observer.privacy(self.config['logs'], self.config['temp_dirs'], markers) + self.observer.privacy(self.config['access_logs'], [], [b'/agora/api']) + self.observer.journal_privacy(self.config, markers) + self.gate('actual response recovery keys absent from every effective log/temp-body sink') + self.fixture.enable_backend() + enabled = self.run(['systemctl', 'is-enabled', self.config['unit']]) + if enabled.stdout.strip() != b'enabled-runtime': + raise Refused('Throwaway unit did not become enabled-runtime') + self.gate('enable only after every acceptance gate passes, isolated runtime target only') + self.browser_passed = True + return {'status': 'PASS', 'private_recovery_paths': list(map(str, self.keys))} + + def state_hashes(self): + root = Path(self.config['state']) + return {str(path.relative_to(root)): hashlib.sha256(path.read_bytes()).hexdigest() + for path in root.rglob('*') if path.is_file()} + + def rollback_proof(self): + if not self.browser_passed: + raise Refused('Entire browser, privacy and enable sequence has not passed') + before = self.state_hashes() + try: + raise Refused('Intentional dry-run acceptance-failure control') + except Refused: + self.fixture.rollback() + disabled = self.run(['systemctl', 'is-enabled', self.config['unit']], check=False) + if disabled.stdout.strip() != b'disabled': + raise Refused('Rollback did not disable the isolated unit') + unit = properties(self.observer.show(self.config['unit'], 'MainPID', 'ActiveState')) + if int(unit['MainPID']) != 0 or unit['ActiveState'] != 'inactive': + raise Refused('Rollback backend not stopped') + if self.state_hashes() != before: + raise Refused('Rollback changed accepted fixture profiles/state') + if self.request('/')[0] != 200 or self.request('/agora/api/challenge')[0] != 404: + raise Refused('Rollback did not preserve ordinary site and close API') + self.gate('injected first-failure rollback closes API/stops backend/preserves profiles/site200') + return {'status': 'PASS', 'state_files_retained': len(before)} + + def receipt(self, status): + result = {'status': status, 'scope': 'ISOLATED_NAMESPACE_ONLY_NOT_DEPLOYED', + 'gates': self.gates, 'commands': self.run.records, + 'observations': self.observer.observations, + 'private_state_path': str(self.root / 'retained-state'), + 'private_recovery_paths': list(map(str, self.keys))} + (self.root / 'result.json').write_text(json.dumps(result, indent=2) + '\n') + os.chmod(self.root / 'result.json', 0o600) + return result + + +def control(path, action): + payload = {'action': action} + if action in ('save-key', 'read-profile', 'after-browser'): + payload['value'] = json.loads(sys.stdin.read()) + with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as connection: + connection.connect(path) + connection.sendall(json.dumps(payload).encode() + b'\n') + connection.shutdown(socket.SHUT_WR) + answer = b'' + while True: + part = connection.recv(65536) + if not part: + break + answer += part + if not answer: + raise Refused('Fixture control closed without an acceptance verdict') + response = json.loads(answer) + if not response['ok']: + raise Refused(response['error']) + print(json.dumps(response['result'])) + + +def serve(args): + fixture = None + listener = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + def interrupted(number, _frame): + raise Refused('Fixture interrupted by ' + signal.Signals(number).name) + + previous = {number: signal.signal(number, interrupted) + for number in (signal.SIGHUP, signal.SIGINT, signal.SIGTERM)} + try: + fixture = Rehearsal(args) + fixture.setup() + listener.bind(str(fixture.root / 'control.sock')) + os.chmod(fixture.root / 'control.sock', 0o600) + listener.listen(1) + print('ACTIVATION_FIXTURE_READY ' + str(fixture.root / 'control.sock'), flush=True) + done = False + while not done: + connection, _ = listener.accept() + with connection: + raw = b'' + while True: + part = connection.recv(65536) + if not part: + break + raw += part + if len(raw) > 1048576: + raise Refused('Oversized private control request') + request = json.loads(raw) + action = request['action'] + if action == 'ready': + result = fixture.config + elif action == 'pre-browser': + result = fixture.pre_browser() + elif action == 'save-key': + result = fixture.save_key(request['value']) + elif action == 'restart-backend': + result = fixture.restart() + elif action == 'read-profile': + result = fixture.read_profile(request['value']) + elif action == 'after-browser': + result = fixture.after_browser(request['value']) + elif action == 'finish': + result = fixture.rollback_proof() + fixture.receipt('PASS') + done = True + else: + raise Refused('Unknown private fixture action') + connection.sendall(json.dumps({'ok': True, 'result': result}).encode()) + except Exception as error: + if fixture is not None: + try: + fixture.fixture.rollback() + except Exception as rollback_error: + fixture.gates.append({'gate': 'fixture rollback unavailable', + 'status': 'FAIL', + 'error': type(rollback_error).__name__ + ': ' + str(rollback_error)}) + finally: + fixture.gates.append({'gate': 'unexpected fixture failure', + 'status': 'FAIL', 'error': type(error).__name__ + ': ' + str(error)}) + fixture.receipt('FAIL') + raise + finally: + try: + listener.close() + if fixture is not None: + fixture.fixture.cleanup() + finally: + for number, handler in previous.items(): + signal.signal(number, handler) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--root') + parser.add_argument('--backend') + parser.add_argument('--nginx') + parser.add_argument('--native') + parser.add_argument('--startup') + parser.add_argument('--page') + parser.add_argument('--client') + parser.add_argument('--control') + parser.add_argument('--action') + args = parser.parse_args() + if os.geteuid() != 0: + raise Refused('Private fixture requires root') + if args.control: + control(args.control, args.action) + else: + if not all((args.root, args.backend, args.nginx, args.native, args.startup, + args.page, args.client)): + parser.error('serve requires explicit fixture root, published page/client and pinned binaries') + serve(args) + + +if __name__ == '__main__': + main()