diff --git a/.agents/tasks/phase1-design/decision.md b/.agents/tasks/phase1-design/decision.md index 7544514..2e77ea7 100644 --- a/.agents/tasks/phase1-design/decision.md +++ b/.agents/tasks/phase1-design/decision.md @@ -81,3 +81,43 @@ Rationale: same reasoning on single-file cross-checks, Q3-B drift, Q3-C operator ``` Merged rationale: one TOML policy file per identity, validated as a whole, swapped atomically, failing closed with `policy_unavailable`, stored in a proxy-only ConfigMap (Kubernetes) or Secrets Manager with S2 rules (ECS). Non-credential egress uses Q3-E2: a separate CONNECT-only `ap-egress` in its own container and UID, no Secret mount, no ap-broker dependency (CI-checked with cargo tree), resolving DNS itself and connecting to the exact validated address, refusing IP literals and private/loopback/link-local targets; agent UID keeps DNS blocked. GitHub goes through octobroker as an auth-proxy route behind TLS; git push via ap-egress to github.com:443; openab-pty#47's allowlist becomes the `[egress]` section. Follow-ups from both members: set `NO_PROXY=127.0.0.1,localhost`, confirm kiro-cli sends `X-Amz-Target` before any grant uses `aws_targets`, and measure the combined iptables rule set in one pod before release. + +## Over-design council (2026-11-16) and the owner's decision on Q1 + +After the Phase 1 verification (`.agents/tasks/phase1-verify/`), two council members (sol and +opus5) reviewed the built system for over-design. Both set escalate on one question: whether the +first end-to-end Kubernetes deployment may run on the Q1-A fallback (one session registered for +the pod's lifetime, no per-session revocation) while Q1-B stays built, and whether `ap-egress` may +ever be folded into the credential-holding proxy. + +### Owner decision (pahud, binding) + +Option 1 of the escalation: + +- **Q1-B stays the formal accepted design. New work on it is frozen.** +- Build **only** the minimal Q1-A static configuration (one session registered for the pod's + lifetime) as a **clearly labelled interim path** for the first end-to-end Kubernetes deployment. +- **The owner accepts that the interim deployment has no per-session revocation.** The + documentation says so in plain words (`docs/interim-static-session.md`, `docs/design/phase1.md`). +- The real-pod `hello` race test remains a **release gate** (`docs/pre-release-checklist.md`, item 3). +- **`ap-egress` stays a separate container and UID. It is never folded into the credential-holding + proxy.** + +### Council verdicts applied (council-level, low risk, reversible) + +| Item | Verdict | What was done | +|---|---|---| +| `aws_targets` | Freeze: keep parser, validation and tests dormant; forbid it in shipped policies | Test `shipped_policies_parse_and_use_no_aws_targets` fails if any policy under `deploy/` uses it. kiro-cli 3.3.0 was measured to send exactly one `X-Amz-Target` per call (model call `AmazonCodeWhispererStreamingService.GenerateAssistantResponse`, `docs/verification/phase1-xamz-target.md`), so the assumption holds, but no grant uses it yet. | +| `egress.allow_route_hosts` | Remove (security fix; only sol flagged it) | The field existed in `ap-core` `EgressCfg` and switched off the rule "an egress host is never a credential route host". Removed with no replacement; a policy that sets it is an unknown-field error. Tests: such a policy is rejected, and an egress entry that is a credential route host is rejected. | +| `route.connect_to` | Remove from production syntax or restrict to test builds | Restricted to the `test-resolve` cargo feature. No shipped build has it, and a policy that sets it is rejected (unit test plus `scripts/check-no-test-resolve.sh` on the release binary). Tests and the matrix use a `test-resolve` build. | +| Admin socket, revoke-all, status | Councils split (sol: remove; opus5: keep); lean was simplify | **Kept**, because tests depend on it: `crates/ap-proxy/tests/session_plane.rs` reads the session count from `GET /admin/status` in many tests and has `admin_socket_status_and_revoke_all`; `policy.rs` and the shared fixture start the proxy with `--admin-socket`; the matrix harness waits for the admin socket. The pre-release checklist does not depend on it. It is never merged into the agent-mounted session socket. Revisit when those tests get another way to count sessions. | +| Broker trait, `ap-client` | Freeze at the UDS client only | No code change. No networked-broker work in Phase 1. | +| `upstream_reset` audit gap (verification item 2) | Owner chose option A | `AuditRec` has a `bytes_sent` field (response-body bytes already relayed; `null` on other lines), counted in `agent.rs`. `#[ignore]` removed from `the_upstream_reset_audit_line_records_the_bytes_sent`. The audit stays free of secrets and of the `/ap/` prefix; matrix X5 passes. | +| Combined iptables rule set | Measured in one pod (verification item 1, PASS) | Design doc tag changed from [I] to [M]; evidence `docs/verification/phase1-k8s-iptables.md`. | +| `kiro-cps` route host placeholder | Not resolvable from the item 4 capture | Listed as an open item with what is needed (`docs/pre-release-checklist.md`). | + +### Q1 summary row, as amended + +| Question | Final status | +|---|---| +| Q1 session/caller identity | Q1-B accepted and frozen. Q1-A static session built as an **interim** path, with no per-session revocation, accepted by the owner. | diff --git a/.agents/tasks/phase1-verify/item6-cleanup.md b/.agents/tasks/phase1-verify/item6-cleanup.md new file mode 100644 index 0000000..2a29a11 --- /dev/null +++ b/.agents/tasks/phase1-verify/item6-cleanup.md @@ -0,0 +1,32 @@ +RESULT: PASS (mini left as found) + +# Item 6d: cleanup check on `mini` + +Start state recorded BEFORE any change in `item6-evidence/before.txt` (`snap.sh`: namespaces, pods, `ctr -n k8s.io` +images, listening sockets, tailscale status, `~` and `/tmp` listings, `~/.cargo/bin`, `~/.local/bin`, crictl container +count, host `iptables -S OUTPUT` md5, `iptables-save | grep ap-item6`, disk). After: `item6-evidence/after.txt`. + +Created and removed (one prefix, `ap-item6`): +- namespace `ap-item6` (pods, Services, Secrets, ConfigMaps): `kubectl delete ns ap-item6 --wait=true` -> deleted; +- images `docker.io/ap-item6/{proxy,egress,agent,hr,netinit}:dev` and the 5 index `sha256:` names the import added + (`ctr -n k8s.io images rm --sync`); +- `/tmp/ap-item6-build` (sources, build target, throwaway cargo home, keys, PKI, tar), `/tmp/ap-item6-snap.sh`; +- macmini: docker images `ap-item6/*` (6), `/tmp/ap-item6-ctx`; laptop: `/tmp/ap-item6-ctx`, `/tmp/ap-item6-tool`. +No cargo or rustc ran on the laptop or macmini. kiro-cli binaries were only copied (read) from `mini`'s install. + +Comparison after cleanup ([M]): +``` +namespaces : default kube-node-lease kube-public kube-system openab (same as before) +ctr images (sorted) md5 : 1b52afe0a10081120714dbf0a88a6778 before and after (identical) +ctr images matching ap-item6: 0 +ls /tmp | grep -c ap-item6: 0 +ps auth-proxy|ap-egress|hr-authority: 0 +host iptables OUTPUT md5 : 6aa9113fa8015deb4c7a93b5c2f03524 before and after +crictl containers : 13 before, 13 after +ls -A ~ md5 : 573255538318e555fbedd46e38caa2ce (same as the item 1 / item 5 baseline; ~ untouched) +df free on / : 31G before, 31G after +tailscale : state never touched; status header identical +``` +`diff before.txt after.txt` has only two lines, both artefacts of the snapshot itself: `ap-item6-after.txt` (the output +file existing in /tmp while the snapshot ran) and the `ps` counter 1 -> 2 (the snapshot's own shell command line +contains "ap-item6"). Both were re-checked without the artefact (counts above are 0). p1 was not touched. diff --git a/.agents/tasks/phase1-verify/item6-cps-host.md b/.agents/tasks/phase1-verify/item6-cps-host.md new file mode 100644 index 0000000..acaf105 --- /dev/null +++ b/.agents/tasks/phase1-verify/item6-cps-host.md @@ -0,0 +1,27 @@ +RESULT: SUPERSEDED by item7-cps-host.md (host measured) + +# Item 6c: `kiro-cps` route host + +`item4-xamz-target.md` pointed every endpoint at a local listener (`api.cps.service` included), so it records the +`X-Amz-Target` values but never the real control-plane host. It cannot fill `deploy/k8s/policy.example.toml`. +The placeholder `control-plane.placeholder.example` stays, and the pod stays "cannot be deployed until replaced". + +Also tried here: `kiro-cli settings api.cps.service` on kiro-cli 2.37.0 -> "No value associated" (there is no readable +default), and a string search of the binary found no unambiguous cps host (the search for host-looking strings ended in +a timeout and noise). Nothing guessed. + +## Exactly what is needed +The host (and port, and the `Host` header, if not 443) that kiro-cli 3.3.0 (the verified version) uses for +`GetProfile` and `ListAvailableModels` by default, observed with NO real credential and with the request not completing. +Literal command for the owner, on a machine with kiro-cli 3.3.0 and no network egress to the service: + +``` +# dummy key, DNS observed only; the connection is expected to fail +sudo tcpdump -ni any -l 'udp port 53' > /tmp/dns.txt & TP=$! +KIRO_API_KEY=aps_$(openssl rand -hex 32) HOME=$(mktemp -d) kiro-cli chat --no-interactive --trust-tools= hi +sudo kill $TP; grep -Eo '[a-z0-9.-]*(kiro\.dev|amazonaws\.com)' /tmp/dns.txt | sort -u +``` +Run it without outbound access to the service (for example with the network cable/Wi-Fi to the internet down but +resolver reachable, or `unshare -n` plus a local DNS logger) if the owner does not want even a dummy-key request to +leave. Then set `host` in the `kiro-cps` route, and check `pass_headers` (`tokentype`) and `error_shape = "aws"` +against that host's first response. diff --git a/.agents/tasks/phase1-verify/item6-evidence/after.txt b/.agents/tasks/phase1-verify/item6-evidence/after.txt new file mode 100644 index 0000000..f3de4f3 --- /dev/null +++ b/.agents/tasks/phase1-verify/item6-evidence/after.txt @@ -0,0 +1,89 @@ +## namespaces +default Active +kube-node-lease Active +kube-public Active +kube-system Active +openab Active +## pods all +kube-system coredns-5f5694d56b-rtsfq Running +kube-system helm-install-traefik-crd-jjbhl Completed +kube-system local-path-provisioner-58d557dc48-b5pxn Running +kube-system metrics-server-786d997795-5c85v Running +kube-system svclb-traefik-17fe3e0c-4wkdf Running +kube-system traefik-78db6cfbb5-tj8ln Running +## images (ctr k8s.io) +docker.io/rancher/klipper-helm:v0.11.1-build20260615 +docker.io/rancher/klipper-helm:v0.9.14-build20260210 +docker.io/rancher/klipper-helm@sha256:2d6c98a07cae39f1bd3bc8405b1b26aff3291b934569cd8dc0c974ba0f356dba +docker.io/rancher/klipper-helm@sha256:939b8f2fbb793483a8716464f8c7de9726dfb50393ad02b99b652004b5503ee6 +docker.io/rancher/klipper-lb:v0.4.17 +docker.io/rancher/klipper-lb@sha256:910944bb0bd94f060a82a56ca1ea1c577d3e49b3473a093a47a985f32e92d94a +docker.io/rancher/local-path-provisioner:v0.0.34 +docker.io/rancher/local-path-provisioner:v0.0.36 +docker.io/rancher/local-path-provisioner@sha256:1eba82e9c386038b4af6d69cca7519fac738c28c42735ed48ce70c882ad0d80f +docker.io/rancher/local-path-provisioner@sha256:6ff68ebe98bc623b45ad22c28be84f8a08214982710f3247d5862e9bccce73ef +docker.io/rancher/mirrored-coredns-coredns:1.14.1 +docker.io/rancher/mirrored-coredns-coredns:1.14.4 +docker.io/rancher/mirrored-coredns-coredns@sha256:3e98f280fd601b37411c5fb7075fd9f337833c480f1644970b727ae0af067782 +docker.io/rancher/mirrored-coredns-coredns@sha256:82b57287b29beb757c740dbbe68f2d4723da94715b563fffad5c13438b71b14a +docker.io/rancher/mirrored-library-busybox:1.37.0 +docker.io/rancher/mirrored-library-busybox@sha256:101b4afd76732482eff9b95cae5f94bcf295e521fbec4e01b69c5421f3f3f3e5 +docker.io/rancher/mirrored-library-traefik:3.6.7 +docker.io/rancher/mirrored-library-traefik@sha256:2c5e029ee3638d3788b4ca7c8ef454baa8f924b91b190b3fd2742bee721ebeea +docker.io/rancher/mirrored-metrics-server:v0.8.1 +docker.io/rancher/mirrored-metrics-server@sha256:b2d2efaf5ac3b366ed0f839d2412a2c4279d4fc2a2a733f12c52133faed36c41 +docker.io/rancher/mirrored-pause:3.6 +docker.io/rancher/mirrored-pause@sha256:74c4244427b7312c5b901fe0f67cbc53683d06f4f24c6faee65d4182bf0fa893 +ghcr.io/actions/actions-runner:latest +ghcr.io/actions/actions-runner@sha256:b6614fce332517f74d0a76e7c762fb08e4f2ff13dcf333183397c8a5725b6e8e +ghcr.io/actions/gha-runner-scale-set-controller:0.14.1 +ghcr.io/actions/gha-runner-scale-set-controller@sha256:4f589b93e55a0e20c12ff51c35249877c15429bbfe6a2c531072af18dfce7d00 +ghcr.io/openabdev/openab:0.9.0-beta.9-kiro +ghcr.io/openabdev/openab@sha256:73d540a413b8c88912b8f02c60db6b06cef8477cb65ba4ff272e8bf6859f732d +sha256:04e981eac7497e8fa8a528b1aaf3692624c823d343c95a388f3d7ba5adb46fc5 +sha256:171247bbf2d7096d7f4ef2d64b3d65275886540d8fbf919b27f559d202c1960d +sha256:2d7e26c3f9329b4c215a021319dd53cb58addd2302295b4efa5f6e10b163d090 +sha256:2e2c8cbfb79b88dca88ac4c0ac2b30f1c359d878739a2e5767622ac18bd78e88 +sha256:2ec68f0e51bbf583fbb40ef80cd9e38cb86b2d02266ed12763bdbdc8091cd908 +sha256:6270bb605e12e581514ada5fd5b3216f727db55dc87d5889c790e4c760683fee +sha256:63e7900ff35e22dd52d9061c75090689639287e4db230ad9900898b8e9e7774b +sha256:68650012ac8cba32ae61415d95424dbae1a4f6f069fb67ea08dec09fc2cd8777 +sha256:7a5975104f24bbd7e5adfa3c99561994bcad1cfe4c3a69dd76e732930cb51a3f +sha256:7c8de0ae9a92bf9ed1a8ca21bf40fc4e45a206bf74f5654f903a142119589534 +sha256:9254fb81aa65831cce153dfdf883805d40157b78ccec0c10fd82c499113fd1de +sha256:acccaf97bcb578daff51c6246e47babbca6e998e4225aa230544684cf147d6c1 +sha256:e0e34c2c9f8ab01e31b463de1d40cdd12d9dd1691900213adedf776deac7bce5 +sha256:e76b3f3568b7f440dfd477c1d6de638d7769ba34c93eef999dee418eb72bc0e3 +sha256:eaa1212a2b4569c811bfa0ad5708428703ad3120a6dbae3b4353ec3cb36f36d2 +sha256:ff7a7936e9306ce4a789cf5523922da5e585dc1216e400efb3b6872a5137ee6b +## cargo bin +cargo +cargo-clippy +cargo-fmt +cargo-miri +clippy-driver +rls +rust-analyzer +rust-gdb +rust-gdbgui +rust-lldb +rustc +rustdoc +rustfmt +rustup +## local bin +kcli +kiro-cli +kiro-cli-chat +kiro-cli-term +## crictl containers +13 +## host iptables OUTPUT md5 +6aa9113fa8015deb4c7a93b5c2f03524 - +## iptables ap-item6 refs +0 +## ps ap procs +2 +## df +98G 63G 31G +(sections listening, tailscale, home and /tmp listings omitted from this committed copy: tailnet and host details; compared locally, identical apart from the two artefacts in item6-cleanup.md) diff --git a/.agents/tasks/phase1-verify/item6-evidence/before.txt b/.agents/tasks/phase1-verify/item6-evidence/before.txt new file mode 100644 index 0000000..7a11e44 --- /dev/null +++ b/.agents/tasks/phase1-verify/item6-evidence/before.txt @@ -0,0 +1,89 @@ +## namespaces +default Active +kube-node-lease Active +kube-public Active +kube-system Active +openab Active +## pods all +kube-system coredns-5f5694d56b-rtsfq Running +kube-system helm-install-traefik-crd-jjbhl Completed +kube-system local-path-provisioner-58d557dc48-b5pxn Running +kube-system metrics-server-786d997795-5c85v Running +kube-system svclb-traefik-17fe3e0c-4wkdf Running +kube-system traefik-78db6cfbb5-tj8ln Running +## images (ctr k8s.io) +docker.io/rancher/klipper-helm:v0.11.1-build20260615 +docker.io/rancher/klipper-helm:v0.9.14-build20260210 +docker.io/rancher/klipper-helm@sha256:2d6c98a07cae39f1bd3bc8405b1b26aff3291b934569cd8dc0c974ba0f356dba +docker.io/rancher/klipper-helm@sha256:939b8f2fbb793483a8716464f8c7de9726dfb50393ad02b99b652004b5503ee6 +docker.io/rancher/klipper-lb:v0.4.17 +docker.io/rancher/klipper-lb@sha256:910944bb0bd94f060a82a56ca1ea1c577d3e49b3473a093a47a985f32e92d94a +docker.io/rancher/local-path-provisioner:v0.0.34 +docker.io/rancher/local-path-provisioner:v0.0.36 +docker.io/rancher/local-path-provisioner@sha256:1eba82e9c386038b4af6d69cca7519fac738c28c42735ed48ce70c882ad0d80f +docker.io/rancher/local-path-provisioner@sha256:6ff68ebe98bc623b45ad22c28be84f8a08214982710f3247d5862e9bccce73ef +docker.io/rancher/mirrored-coredns-coredns:1.14.1 +docker.io/rancher/mirrored-coredns-coredns:1.14.4 +docker.io/rancher/mirrored-coredns-coredns@sha256:3e98f280fd601b37411c5fb7075fd9f337833c480f1644970b727ae0af067782 +docker.io/rancher/mirrored-coredns-coredns@sha256:82b57287b29beb757c740dbbe68f2d4723da94715b563fffad5c13438b71b14a +docker.io/rancher/mirrored-library-busybox:1.37.0 +docker.io/rancher/mirrored-library-busybox@sha256:101b4afd76732482eff9b95cae5f94bcf295e521fbec4e01b69c5421f3f3f3e5 +docker.io/rancher/mirrored-library-traefik:3.6.7 +docker.io/rancher/mirrored-library-traefik@sha256:2c5e029ee3638d3788b4ca7c8ef454baa8f924b91b190b3fd2742bee721ebeea +docker.io/rancher/mirrored-metrics-server:v0.8.1 +docker.io/rancher/mirrored-metrics-server@sha256:b2d2efaf5ac3b366ed0f839d2412a2c4279d4fc2a2a733f12c52133faed36c41 +docker.io/rancher/mirrored-pause:3.6 +docker.io/rancher/mirrored-pause@sha256:74c4244427b7312c5b901fe0f67cbc53683d06f4f24c6faee65d4182bf0fa893 +ghcr.io/actions/actions-runner:latest +ghcr.io/actions/actions-runner@sha256:b6614fce332517f74d0a76e7c762fb08e4f2ff13dcf333183397c8a5725b6e8e +ghcr.io/actions/gha-runner-scale-set-controller:0.14.1 +ghcr.io/actions/gha-runner-scale-set-controller@sha256:4f589b93e55a0e20c12ff51c35249877c15429bbfe6a2c531072af18dfce7d00 +ghcr.io/openabdev/openab:0.9.0-beta.9-kiro +ghcr.io/openabdev/openab@sha256:73d540a413b8c88912b8f02c60db6b06cef8477cb65ba4ff272e8bf6859f732d +sha256:04e981eac7497e8fa8a528b1aaf3692624c823d343c95a388f3d7ba5adb46fc5 +sha256:171247bbf2d7096d7f4ef2d64b3d65275886540d8fbf919b27f559d202c1960d +sha256:2d7e26c3f9329b4c215a021319dd53cb58addd2302295b4efa5f6e10b163d090 +sha256:2e2c8cbfb79b88dca88ac4c0ac2b30f1c359d878739a2e5767622ac18bd78e88 +sha256:2ec68f0e51bbf583fbb40ef80cd9e38cb86b2d02266ed12763bdbdc8091cd908 +sha256:6270bb605e12e581514ada5fd5b3216f727db55dc87d5889c790e4c760683fee +sha256:63e7900ff35e22dd52d9061c75090689639287e4db230ad9900898b8e9e7774b +sha256:68650012ac8cba32ae61415d95424dbae1a4f6f069fb67ea08dec09fc2cd8777 +sha256:7a5975104f24bbd7e5adfa3c99561994bcad1cfe4c3a69dd76e732930cb51a3f +sha256:7c8de0ae9a92bf9ed1a8ca21bf40fc4e45a206bf74f5654f903a142119589534 +sha256:9254fb81aa65831cce153dfdf883805d40157b78ccec0c10fd82c499113fd1de +sha256:acccaf97bcb578daff51c6246e47babbca6e998e4225aa230544684cf147d6c1 +sha256:e0e34c2c9f8ab01e31b463de1d40cdd12d9dd1691900213adedf776deac7bce5 +sha256:e76b3f3568b7f440dfd477c1d6de638d7769ba34c93eef999dee418eb72bc0e3 +sha256:eaa1212a2b4569c811bfa0ad5708428703ad3120a6dbae3b4353ec3cb36f36d2 +sha256:ff7a7936e9306ce4a789cf5523922da5e585dc1216e400efb3b6872a5137ee6b +## cargo bin +cargo +cargo-clippy +cargo-fmt +cargo-miri +clippy-driver +rls +rust-analyzer +rust-gdb +rust-gdbgui +rust-lldb +rustc +rustdoc +rustfmt +rustup +## local bin +kcli +kiro-cli +kiro-cli-chat +kiro-cli-term +## crictl containers +13 +## host iptables OUTPUT md5 +6aa9113fa8015deb4c7a93b5c2f03524 - +## iptables ap-item6 refs +0 +## ps ap procs +1 +## df +98G 63G 31G +(sections listening, tailscale, home and /tmp listings omitted from this committed copy: tailnet and host details; compared locally, identical apart from the two artefacts in item6-cleanup.md) diff --git a/.agents/tasks/phase1-verify/item6-evidence/hello-post.out b/.agents/tasks/phase1-verify/item6-evidence/hello-post.out new file mode 100644 index 0000000..af7fb22 --- /dev/null +++ b/.agents/tasks/phase1-verify/item6-evidence/hello-post.out @@ -0,0 +1,27 @@ +### timeline from the proxy's own audit (ms, proxy clock) +request audit: {'route': '-', 'decision': 'deny', 'code': 'host_rejected', 'session': '-', 'status': 400} +request audit: {'route': 'kiro-krs', 'decision': 'deny', 'code': 'surrogate_revoked', 'session': '-', 'status': 403} +request audit: {'route': 'kiro-krs', 'decision': 'deny', 'code': 'upstream_unavailable', 'session': 'sess-1794856959', 'status': 502} +hello 201 times: [1794856771671, 1794856959918] +renew times: [1794856801673, 1794856831675, 1794856861678] +last renew before the new winner: 1794856861678 +lease 90s lapses at: 1794856951678 +409s after last renew: 54, last 409 at 1794856985980 (= last+124.3s) +first 409 after last renew... early hellos won before lapse: [] +winner 201 at 1794856959918 = last renew + 98.2s +other plane event: register ok 201 1794856771671 +other plane event: register ok 201 1794856959919 +### old surrogate through the proxy after the lapse (as UID 1000 in agent) +HTTP/1.1 403 Forbidden +x-auth-proxy-error: surrogate_revoked +content-type: application/x-amz-json-1.0 +x-amzn-errortype: AccessDeniedException +content-length: 96 +date: Mon, 16 Nov 2026 19:23:06 GMT + +{"__type":"AccessDeniedException","message":"auth-proxy: surrogate revoked (surrogate_revoked)"}### new session's surrogate works? (live, goes to the stub: a 400 from the stub means admitted) +new surrogate status=502 +hello 409 between last renew and the winner: 27 ; first at +0.2s, last at +83.2s after last renew +hello 201 in that window: 0 +max gap between consecutive 409s (ms): 15002 +agent=1 ap-egress=0 proxy=0 \ No newline at end of file diff --git a/.agents/tasks/phase1-verify/item6-evidence/hello-run.out b/.agents/tasks/phase1-verify/item6-evidence/hello-run.out new file mode 100644 index 0000000..00a46e7 --- /dev/null +++ b/.agents/tasks/phase1-verify/item6-evidence/hello-run.out @@ -0,0 +1,207 @@ +[19:19:54.929Z driver] pod before: +ap-agent 3/3 Running 0 26s 10.42.0.31 mini +[19:19:55.041Z driver] no socket-mode override anywhere in the applied pod: +0 +(count above must be 0) +[19:19:55.156Z driver] proxy container env + args +["--policy","/etc/auth-proxy/policy.toml"] env= +[19:19:55.267Z driver] session socket as seen by the agent (numeric ids) +uid=1000(ubuntu) gid=2000 groups=2000,4(adm),20(dialout),24(cdrom),25(floppy),27(sudo),29(audio),30(dip),44(video),46(plugdev) +total 0 +srw-rw---- 1 1001 2000 0 Nov 16 19:19 session.sock +ls: cannot access '/run/auth-proxy-admin': No such file or directory +command terminated with exit code 2 +[19:19:55.429Z driver] ap-egress container: socket paths mounted? +1002 +ls: cannot access '/run/auth-proxy': No such file or directory +ls: cannot access '/run/auth-proxy-admin': No such file or directory +command terminated with exit code 2 +[19:19:55.593Z driver] container ps (before kill) +PID PPID UID CMDLINE +1 0 1000 /usr/local/bin/hr-authority authority +11 1 1000 /usr/local/bin/hr-authority orphan +25 0 1000 /usr/local/bin/hr-authority ps +[19:21:08.876Z driver] orphan.log tail before kill +19:21:06.876Z epoch=1794856866.876 pid=11 ORPHAN_HELLO status=Some(409) code=Some("authority_active") active=true err=session plane answered 409 authority_active: another authority's lease is live +19:21:07.878Z epoch=1794856867.878 pid=11 ORPHAN_HELLO status=Some(409) code=Some("authority_active") active=true err=session plane answered 409 authority_active: another authority's lease is live +19:21:08.882Z epoch=1794856868.882 pid=11 ORPHAN_HELLO status=Some(409) code=Some("authority_active") active=true err=session plane answered 409 authority_active: another authority's lease is live +[19:21:09.057Z driver] agent log before kill +19:19:31.670Z epoch=1794856771.670 pid=1 AUTH_START Uid: 1000 1000 1000 1000 ppid=0 +19:19:31.671Z epoch=1794856771.671 pid=1 HELLO_WON authority token obtained (hello_retry returned) +19:19:31.672Z epoch=1794856771.672 pid=1 REGISTERED session=sess-1794856771 gen=1 (surrogate in /tmp, test value) +19:20:01.674Z epoch=1794856801.674 pid=1 RENEW Renewed +19:20:31.676Z epoch=1794856831.676 pid=1 RENEW Renewed +19:21:01.678Z epoch=1794856861.678 pid=1 RENEW Renewed +[19:21:09.427Z driver] old surrogate file: /tmp/surrogate.sess-1794856771 container id: 467f2e8faa00 +[19:21:09.429Z driver] KILL agent container now (crictl stop --timeout 0 = SIGKILL to PID 1) +[19:21:09.583Z driver] KILLED (crictl returned) +[19:21:11.032Z driver] agent restartCount=1 state={"running":{"startedAt":"2026-11-16T19:21:09Z"}} +ap-agent 3/3 Running 1 (2s ago) 102s 10.42.0.31 mini +[19:21:11.141Z driver] container ps (after restart) +PID PPID UID CMDLINE +1 0 1000 /usr/local/bin/hr-authority authority +11 0 1000 /usr/local/bin/hr-authority ps +[19:21:11.313Z driver] orphan.log: lines after the kill? (tail) +19:21:07.878Z epoch=1794856867.878 pid=11 ORPHAN_HELLO status=Some(409) code=Some("authority_active") active=true err=session plane answered 409 authority_active: another authority's lease is live +19:21:08.882Z epoch=1794856868.882 pid=11 ORPHAN_HELLO status=Some(409) code=Some("authority_active") active=true err=session plane answered 409 authority_active: another authority's lease is live +[19:21:11.483Z driver] start rival probe (uid 1000, exec'd, 50 s, hello every 5 s) +[19:22:40.883Z driver] new PID 1 HELLO_WON observed by driver +[19:22:40.888Z driver] probe output +19:21:11.647Z epoch=1794856871.647 pid=27 PROBE_START Uid: 1000 1000 1000 1000 ppid=0 +19:21:11.647Z epoch=1794856871.647 pid=27 PROBE_HELLO status=Some(409) code=Some("authority_active") active=true err=session plane answered 409 authority_active: another authority's lease is live +19:21:16.650Z epoch=1794856876.650 pid=27 PROBE_HELLO status=Some(409) code=Some("authority_active") active=true err=session plane answered 409 authority_active: another authority's lease is live +19:21:21.651Z epoch=1794856881.651 pid=27 PROBE_HELLO status=Some(409) code=Some("authority_active") active=true err=session plane answered 409 authority_active: another authority's lease is live +19:21:26.653Z epoch=1794856886.653 pid=27 PROBE_HELLO status=Some(409) code=Some("authority_active") active=true err=session plane answered 409 authority_active: another authority's lease is live +19:21:31.656Z epoch=1794856891.656 pid=27 PROBE_HELLO status=Some(409) code=Some("authority_active") active=true err=session plane answered 409 authority_active: another authority's lease is live +19:21:36.658Z epoch=1794856896.658 pid=27 PROBE_HELLO status=Some(409) code=Some("authority_active") active=true err=session plane answered 409 authority_active: another authority's lease is live +19:21:41.661Z epoch=1794856901.661 pid=27 PROBE_HELLO status=Some(409) code=Some("authority_active") active=true err=session plane answered 409 authority_active: another authority's lease is live +19:21:46.663Z epoch=1794856906.663 pid=27 PROBE_HELLO status=Some(409) code=Some("authority_active") active=true err=session plane answered 409 authority_active: another authority's lease is live +19:21:51.666Z epoch=1794856911.666 pid=27 PROBE_HELLO status=Some(409) code=Some("authority_active") active=true err=session plane answered 409 authority_active: another authority's lease is live +19:21:56.668Z epoch=1794856916.668 pid=27 PROBE_HELLO status=Some(409) code=Some("authority_active") active=true err=session plane answered 409 authority_active: another authority's lease is live +19:22:01.670Z epoch=1794856921.670 pid=27 PROBE_END never won +[19:22:40.893Z driver] GET old surrogate through proxy listener (after lapse) +19:22:41.047Z epoch=1794856961.047 pid=42 GET file=/tmp/surrogate.sess-1794856771 HTTP/1.1 400 Bad Request | body={"__type":"AccessDeniedException","message":"auth-proxy: Host must be exactly one listener authority (host_rejected)"} +[19:22:41.055Z driver] agent log (new container) +19:21:09.898Z epoch=1794856869.898 pid=1 AUTH_START Uid: 1000 1000 1000 1000 ppid=0 +19:22:39.919Z epoch=1794856959.919 pid=1 HELLO_WON authority token obtained (hello_retry returned) +19:22:39.920Z epoch=1794856959.920 pid=1 REGISTERED session=sess-1794856959 gen=1 (surrogate in /tmp, test value) +19:22:39.921Z epoch=1794856959.921 pid=1 SPAWNED_ORPHAN child pid=37 +[19:22:41.166Z driver] agent log (previous container) +19:19:31.670Z epoch=1794856771.670 pid=1 AUTH_START Uid: 1000 1000 1000 1000 ppid=0 +19:19:31.671Z epoch=1794856771.671 pid=1 HELLO_WON authority token obtained (hello_retry returned) +19:19:31.672Z epoch=1794856771.672 pid=1 REGISTERED session=sess-1794856771 gen=1 (surrogate in /tmp, test value) +19:19:31.672Z epoch=1794856771.672 pid=1 SPAWNED_ORPHAN child pid=11 +19:20:01.674Z epoch=1794856801.674 pid=1 RENEW Renewed +19:20:31.676Z epoch=1794856831.676 pid=1 RENEW Renewed +19:21:01.678Z epoch=1794856861.678 pid=1 RENEW Renewed +[19:22:41.280Z driver] proxy log (full) +auth-proxy: ready, agent listener on 127.0.0.1:18080 +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"ok","session":"-","status":201,"t":1794856771671} +{"count":null,"generation":1,"hash8":"84103eb0","plane":"register","result":"ok","session":"sess-1794856771","status":201,"t":1794856771671} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856771673} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856772676} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856773678} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856774680} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856775682} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856776684} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856777687} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856778689} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856779692} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856780694} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856781696} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856782698} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856783701} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856784703} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856785706} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856786708} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856787710} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856788712} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856789714} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856790716} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856791718} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856792720} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856793723} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856794725} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856795727} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856796729} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856797731} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856798733} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856799735} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856800737} +{"count":1,"generation":null,"hash8":"-","plane":"renew","result":"ok","session":"-","status":200,"t":1794856801673} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856801739} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856802741} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856803744} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856804746} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856805748} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856806750} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856807753} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856808755} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856809757} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856810759} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856811761} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856812763} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856813765} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856814767} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856815769} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856816771} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856817773} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856818777} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856819779} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856820781} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856821782} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856822784} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856823786} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856824786} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856825788} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856826790} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856827792} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856828794} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856829796} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856830798} +{"count":1,"generation":null,"hash8":"-","plane":"renew","result":"ok","session":"-","status":200,"t":1794856831675} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856831800} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856832802} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856833804} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856834807} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856835809} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856836811} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856837813} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856838815} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856839817} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856840820} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856841822} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856842824} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856843827} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856844829} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856845831} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856846833} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856847835} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856848837} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856849839} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856850841} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856851843} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856852845} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856853848} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856854850} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856855852} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856856854} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856857856} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856858858} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856859861} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856860863} +{"count":1,"generation":null,"hash8":"-","plane":"renew","result":"ok","session":"-","status":200,"t":1794856861678} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856861865} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856862867} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856863869} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856864871} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856865873} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856866875} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856867877} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856868882} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856869898} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856870900} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856871647} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856872902} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856876649} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856876904} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856881651} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856884906} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856886653} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856891656} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856896658} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856899908} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856901660} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856906663} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856911665} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856914910} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856916668} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856929912} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856944914} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"ok","session":"-","status":201,"t":1794856959918} +{"count":null,"generation":1,"hash8":"3ca567c5","plane":"register","result":"ok","session":"sess-1794856959","status":201,"t":1794856959919} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856959924} +{"count":null,"generation":null,"hash8":"-","plane":"hello","result":"authority_active","session":"-","status":409,"t":1794856960927} +{"aws_target":"-","bytes_sent":null,"code":"host_rejected","decision":"deny","duration_ms":0,"generation":null,"identity":"-","method":"GET","path":"-","route":"-","session":"-","status":400,"t":1794856961047} +[19:22:41.399Z driver] restart counts +agent=1 ap-egress=0 proxy=0 diff --git a/.agents/tasks/phase1-verify/item6-evidence/interim-run.out b/.agents/tasks/phase1-verify/item6-evidence/interim-run.out new file mode 100644 index 0000000..743c453 --- /dev/null +++ b/.agents/tasks/phase1-verify/item6-evidence/interim-run.out @@ -0,0 +1,177 @@ + +### pod +ap-agent 3/3 Running 0 38s 10.42.0.29 mini +netinit exit=0 kiro-settings exit=0 + +### proxy start log +auth-proxy: INTERIM static session enabled (Q1-A): one surrogate for the life of this process, 1 credential(s), NO per-session revocation (ends only when this process ends); see docs/interim-static-session.md +auth-proxy: ready, agent listener on 127.0.0.1:18080 + +### netinit log +== iptables iptables v1.8.9 (nf_tables) +-P OUTPUT ACCEPT +-A OUTPUT -m owner --uid-owner 1000 -m conntrack --ctstate ESTABLISHED -j ACCEPT +-A OUTPUT -o lo -p tcp -m tcp --dport 18080 -m owner --uid-owner 1000 -j ACCEPT +-A OUTPUT -o lo -p tcp -m tcp --dport 3128 -m owner --uid-owner 1000 -j ACCEPT +-A OUTPUT ! -o lo -m owner --uid-owner 1000 -j REJECT --reject-with icmp-port-unreachable +== ip6tables +-P OUTPUT ACCEPT +-A OUTPUT -m owner --uid-owner 1000 -m conntrack --ctstate ESTABLISHED -j ACCEPT +-A OUTPUT -o lo -p tcp -m tcp --dport 18080 -m owner --uid-owner 1000 -j ACCEPT +-A OUTPUT -o lo -p tcp -m tcp --dport 3128 -m owner --uid-owner 1000 -j ACCEPT +-A OUTPUT ! -o lo -m owner --uid-owner 1000 -j REJECT --reject-with icmp6-port-unreachable + +### kiro-settings init log + +### settings file in agent HOME (caller key masked) +./.local/share/kiro-cli/run-receipts/.reaper.lock +./.local/share/kiro-cli/telemetry-export-drops.lock +./.local/share/kiro-cli/data.sqlite3 +./.kiro/settings/cli.json +./.kiro/settings/cli.json.lock +-- ./.kiro/settings +cat: ./.kiro/settings: Is a directory + +-- ./.kiro/settings/cli.json +{ + "api.krs.service": { + "endpoint": "http://127.0.0.1:18080/ap/apk_/kiro-krs", + "region": "us-east-1" + }, + "api.cps.service": { + "endpoint": "http://127.0.0.1:18080/ap/apk_/kiro-cps", + "region": "us-east-1" + } +} + +### agent identity and env (surrogate masked) +uid=1000(ubuntu) gid=1000(ubuntu) groups=1000(ubuntu),4(adm),20(dialout),24(cdrom),25(floppy),27(sudo),29(audio),30(dip),44(video),46(plugdev) +HTTPS_PROXY=http://127.0.0.1:3128 +KIRO_API_KEY=aps_ +NO_PROXY=127.0.0.1,localhost +KIRO_DISABLE_TELEMETRY=1 + +### agent mounts: session socket path present? +ls: cannot access '/run/auth-proxy': No such file or directory +ls: cannot access '/run/auth-proxy-admin': No such file or directory + +######## T1 surrogate-only agent reaches the stub through the proxy + +### POST krs with surrogate, caller key in path +status=400 + +### POST cps with surrogate +{"__type": "ValidationException", "message": "stub upstream"} status=400 + +### negative: wrong surrogate +{"__type":"AccessDeniedException","message":"auth-proxy: surrogate malformed (surrogate_malformed)"} status=403 + +### negative: no surrogate +{"__type":"AccessDeniedException","message":"auth-proxy: no surrogate presented (surrogate_missing)"} status=403 + +### negative: wrong caller key +{"__type":"AccessDeniedException","message":"auth-proxy: caller key not recognised (caller_rejected)"} status=403 + +### stub log (what the upstream saw, summarised) +1 x host=control-plane.placeholder.example:8443 POST / target=AmazonCodeWhispererService.GetProfile authorization_class=REAL +1 x host=runtime.us-east-1.kiro.dev:8443 POST / target=AmazonCodeWhispererStreamingService.GenerateAssistantResponse authorization_class=REAL +total requests at stub: 2 +last raw line header names: +{"t": 1794856710.902, "host": "control-plane.placeholder.example:8443", "method": "POST", "path": "/", "xamz_target": "AmazonCodeWhispererService.GetProfile", "authorization_class": "REAL", "header_names": ["accept", "authorization", "content-length", "content-type", "host", "user-agent", "x-amz-target"], "body_len": 2} + +######## T2 real credential never in the agent container +uid=1000 pid1-cmd=sleep infinity +proc environ+cmdline hits: 0 +procs scanned: 4 +filesystem files containing it (home tmp work etc run var opt usr/local root): 0 +secret volume mounted? ls: cannot access '/run/secrets': No such file or directory + +### mounts in agent container that mention secrets +0 + +### negative control: the same scan against the PROXY container's own secret file finds it? (proxy has no shell: skip) ; scan finds the value when planted in /tmp +control hits: 1 + +######## T3 direct egress and DNS refused for the agent UID + +$ curl -sS --noproxy '*' -m 8 -o /dev/null -w '%{http_code}' https://example.com +curl: (6) Could not resolve host: example.com +000command terminated with exit code 6 +exit=6 elapsed=0.16s + +$ curl -sS --noproxy '*' -m 8 --resolve example.com:443:93.184.216.34 -o /dev/null -w '%{http_code}' https://example.com +curl: (7) Failed to connect to example.com port 443 after 0 ms: Couldn't connect to server +000command terminated with exit code 7 +exit=7 elapsed=0.17s + +$ curl -sS --noproxy '*' -m 8 -k -o /dev/null -w '%{http_code}' https://10.43.51.98:8443/ +curl: (7) Failed to connect to 10.43.51.98 port 8443 after 0 ms: Couldn't connect to server +000command terminated with exit code 7 +exit=7 elapsed=0.17s + +$ getent hosts github.com +command terminated with exit code 2 +exit=2 elapsed=0.16s + +$ dig +time=2 +tries=1 @10.43.0.10 github.com +;; global options: +cmd +;; no servers could be reached +command terminated with exit code 9 +exit=9 elapsed=0.19s + +$ nc -zv -w 3 1.1.1.1 443 +nc: connect to 1.1.1.1 port 443 (tcp) failed: Connection refused +command terminated with exit code 1 +exit=1 elapsed=0.16s + +$ nc -zvu -w 3 10.43.0.10 53 +command terminated with exit code 1 +exit=1 elapsed=0.16s + +$ python3 -c "import socket;socket.create_connection(('8.8.8.8',53),3)" + sock.connect(sa) +ConnectionRefusedError: [Errno 111] Connection refused +command terminated with exit code 1 +exit=1 elapsed=0.24s + +### via ap-egress (allowlisted) vs not +github.com via egress: 200 +example.com via egress: 000 + +### agent UID cannot reach the proxy's other things: admin socket +ls: cannot access '/run/auth-proxy-admin': No such file or directory +command terminated with exit code 2 + +######## T4 Q1-A interim session via kiro-cli (settings written by the init container) + +### kiro-cli version +kiro-cli 2.37.0 + +### kiro-cli settings read back (keys masked) +{ + "endpoint": "http://127.0.0.1:18080/ap/apk_/kiro-krs", + "region": "us-east-1" +} (global) +{ + "endpoint": "http://127.0.0.1:18080/ap/apk_/kiro-cps", + "region": "us-east-1" +} (global) + +### kiro-cli chat --no-interactive (stub upstream, timeout 90s) +Error: Internal error (code -32603): Encountered an error in the response stream: stub upstream +exit=0 + +### stub log after kiro-cli (summarised) +42 x host=control-plane.placeholder.example:8443 POST / target=AmazonCodeWhispererService.GetProfile authorization_class=REAL +4 x host=control-plane.placeholder.example:8443 POST / target=KiroControlPlaneBearerService.ListAvailableModels authorization_class=REAL +2 x host=runtime.us-east-1.kiro.dev:8443 POST / target=AmazonCodeWhispererStreamingService.GenerateAssistantResponse authorization_class=REAL +total requests at stub: 48 + +### proxy audit lines (summarised) and a leak scan +1 x route=- target=- decision=deny code=caller_rejected session=- status=403 +42 x route=kiro-cps target=AmazonCodeWhispererService.GetProfile decision=allow code=ok session=interim-static status=400 +4 x route=kiro-cps target=KiroControlPlaneBearerService.ListAvailableModels decision=allow code=ok session=interim-static status=400 +1 x route=kiro-krs target=- decision=deny code=surrogate_malformed session=- status=403 +1 x route=kiro-krs target=- decision=deny code=surrogate_missing session=- status=403 +2 x route=kiro-krs target=AmazonCodeWhispererStreamingService.GenerateAssistantResponse decision=allow code=ok session=interim-static status=400 +audit lines containing apk_/aps_/real-dummy: 0 diff --git a/.agents/tasks/phase1-verify/item6-evidence/pod6.sh b/.agents/tasks/phase1-verify/item6-evidence/pod6.sh new file mode 100644 index 0000000..763067b --- /dev/null +++ b/.agents/tasks/phase1-verify/item6-evidence/pod6.sh @@ -0,0 +1,18 @@ +#!/bin/bash +# Run on mini: render and apply the interim pod (INTERIM=1) or pod.yaml (INTERIM=0). Test-only edits listed in the report. +set -eu +K="sudo -n k3s kubectl"; NS=ap-item6; B=/tmp/ap-item6-build +SIP=$(cat $B/keys/stub.ip); SH=$(cat $B/keys/surrogate.hash) +if [ "${INTERIM:-1}" = 1 ]; then SRC=$B/src/deploy/k8s/pod-interim-static.yaml; AG=agent; else SRC=$B/src/deploy/k8s/pod.yaml; AG=hr; fi +awk 'BEGIN{d=1} /^---$/{d++; next} d>=2' $SRC \ + | sed -e 's#REPLACE/auth-proxy-netinit:TAG#docker.io/ap-item6/netinit:dev#' \ + -e 's#REPLACE/auth-proxy:TAG#docker.io/ap-item6/proxy:dev#' \ + -e 's#REPLACE/ap-egress:TAG#docker.io/ap-item6/egress:dev#' \ + -e "s#REPLACE/agent-runtime:TAG#docker.io/ap-item6/$AG:dev#" \ + -e "s#REPLACE_WITH_SHA256_OF_THE_SURROGATE\"\]#$SH\", \"--ca-file\", \"/etc/ap-ca/ca.pem\"]#" \ + -e 's#^\( - {name: proxy-state, mountPath: /var/lib/auth-proxy}.*\)$#\1\n - {name: ap-ca, mountPath: /etc/ap-ca, readOnly: true}#' \ + -e 's#^ - {name: work, emptyDir: {}}$# - {name: work, emptyDir: {}}\n - {name: ap-ca, configMap: {name: ap-ca, defaultMode: 0444}}#' \ + -e "s#^ enableServiceLinks: false\$# enableServiceLinks: false\n hostAliases:\n - {ip: \"$SIP\", hostnames: [\"runtime.us-east-1.kiro.dev\", \"control-plane.placeholder.example\"]}#" \ + -e 's#image: \(docker.io/ap-item6/[a-z]*:dev\)#image: \1\n imagePullPolicy: Never#' > $B/pod-rendered.yaml +diff <(awk 'BEGIN{d=1} /^---$/{d++; next} d>=2' $SRC) $B/pod-rendered.yaml > $B/pod-rendered.diff || true +$K -n $NS apply -f $B/pod-rendered.yaml diff --git a/.agents/tasks/phase1-verify/item6-evidence/run6.sh b/.agents/tasks/phase1-verify/item6-evidence/run6.sh new file mode 100644 index 0000000..12a3973 --- /dev/null +++ b/.agents/tasks/phase1-verify/item6-evidence/run6.sh @@ -0,0 +1,50 @@ +#!/bin/bash +# Timed hello-race run on the live pod. Foreground, raw output to stdout. +K="sudo -n k3s kubectl -n ap-item6" +now() { date -u +%H:%M:%S.%N | cut -c1-12; } +ev() { echo "[$(now)Z driver] $*"; } +ev "pod before:"; $K get pod ap-agent -o wide --no-headers +ev "no socket-mode override anywhere in the applied pod:"; $K get pod ap-agent -o yaml | grep -ci "SESSION_SOCKET_MODE\|session-socket-mode" ; echo "(count above must be 0)" +ev "proxy container env + args"; $K get pod ap-agent -o jsonpath='{.spec.containers[?(@.name=="proxy")].args}{" env="}{.spec.containers[?(@.name=="proxy")].env}{"\n"}' +ev "session socket as seen by the agent (numeric ids)"; $K exec ap-agent -c agent -- sh -c 'id; ls -ln /run/auth-proxy; ls -ld /run/auth-proxy-admin 2>&1' +ev "ap-egress container: socket paths mounted?"; $K exec ap-agent -c ap-egress -- sh -c 'id -u; ls /run/auth-proxy /run/auth-proxy-admin 2>&1' +ev "container ps (before kill)"; $K exec ap-agent -c agent -- /usr/local/bin/hr-authority ps +# wait for 3 renews, then 7 s more +while [ "$($K logs ap-agent -c agent | grep -c ' RENEW ')" -lt 3 ]; do sleep 2; done +sleep 7 +ev "orphan.log tail before kill"; $K exec ap-agent -c agent -- tail -n 3 /tmp/orphan.log +ev "agent log before kill"; $K logs ap-agent -c agent | grep -v ORPHAN +CID=$($K get pod ap-agent -o jsonpath='{.status.containerStatuses[?(@.name=="agent")].containerID}' | sed 's#containerd://##') +OLDSUR=$($K exec ap-agent -c agent -- sh -c 'ls /tmp/surrogate.sess-*' 2>/dev/null | head -1) +ev "old surrogate file: $OLDSUR container id: ${CID:0:12}" +ev "KILL agent container now (crictl stop --timeout 0 = SIGKILL to PID 1)" +sudo -n k3s crictl stop --timeout 0 "$CID" >/dev/null +ev "KILLED (crictl returned)" +# wait for restart +for i in $(seq 1 60); do + RC=$($K get pod ap-agent -o jsonpath='{.status.containerStatuses[?(@.name=="agent")].restartCount}') + ST=$($K get pod ap-agent -o jsonpath='{.status.containerStatuses[?(@.name=="agent")].state}') + case "$ST" in *running*) [ "$RC" = 1 ] && break;; esac + sleep 1 +done +ev "agent restartCount=$RC state=$ST" +$K get pod ap-agent -o wide --no-headers +ev "container ps (after restart)"; $K exec ap-agent -c agent -- /usr/local/bin/hr-authority ps +ev "orphan.log: lines after the kill? (tail)"; $K exec ap-agent -c agent -- tail -n 2 /tmp/orphan.log +ev "start rival probe (uid 1000, exec'd, 50 s, hello every 5 s)" +$K exec ap-agent -c agent -- /usr/local/bin/hr-authority probe 50 > /tmp/ap-item6-build/probe.out 2>&1 & +PP=$! +# poll for the new PID1 to win +for i in $(seq 1 120); do + if $K logs ap-agent -c agent 2>/dev/null | grep -q HELLO_WON; then break; fi + sleep 2 +done +ev "new PID 1 HELLO_WON observed by driver" +wait $PP +ev "probe output"; cat /tmp/ap-item6-build/probe.out +ev "GET old surrogate through proxy listener (after lapse)" +$K exec ap-agent -c agent -- /usr/local/bin/hr-authority get "$OLDSUR" +ev "agent log (new container)"; $K logs ap-agent -c agent +ev "agent log (previous container)"; $K logs ap-agent -c agent --previous +ev "proxy log (full)"; $K logs ap-agent -c proxy +ev "restart counts"; $K get pod ap-agent -o jsonpath='{range .status.containerStatuses[*]}{.name}={.restartCount} {end}{"\n"}' diff --git a/.agents/tasks/phase1-verify/item6-evidence/setup6.sh b/.agents/tasks/phase1-verify/item6-evidence/setup6.sh new file mode 100644 index 0000000..36d6d51 --- /dev/null +++ b/.agents/tasks/phase1-verify/item6-evidence/setup6.sh @@ -0,0 +1,56 @@ +#!/bin/sh +# Run on mini. Creates ns ap-item6 with the stub, secrets and configmaps. No value is printed. +set -eu +K="sudo -n k3s kubectl"; NS=ap-item6; B=/tmp/ap-item6-build +mkdir -p $B/pki $B/keys; cd $B +# PKI for the stub (test only) +openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes -days 2 -subj "/CN=ap-item6-test-ca" -keyout pki/ca.key -out pki/ca.pem 2>/dev/null +openssl req -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes -subj "/CN=stub" -keyout pki/key.pem -out pki/csr.pem 2>/dev/null +printf 'subjectAltName=DNS:runtime.us-east-1.kiro.dev,DNS:control-plane.placeholder.example\n' > pki/ext +openssl x509 -req -in pki/csr.pem -CA pki/ca.pem -CAkey pki/ca.key -CAcreateserial -days 2 -extfile pki/ext -out pki/cert.pem 2>/dev/null +# keys: caller key + surrogate via the shipped script; dummy "real" credential +sh src/deploy/k8s/interim-keygen.sh $B/keys/k > keys/keygen.out +CH=$(sed -n 's/.*caller_key_sha256 = "\([0-9a-f]*\)".*/\1/p' keys/keygen.out) +SH=$(sed -n 's/.*--interim-static-surrogate-sha256=\([0-9a-f]*\)$/\1/p' keys/keygen.out) +printf 'real-dummy-%s' "$(openssl rand -hex 24)" > keys/real +echo "$CH" > keys/caller.hash; echo "$SH" > keys/surrogate.hash +# policy: example + caller hash + test-only port 8443 on both routes +sed -e "s/^caller_key_sha256 = \"[0-9a-f]*\".*/caller_key_sha256 = \"$CH\"/" \ + -e 's/^host = \(.*\)$/host = \1\nport = 8443/' src/deploy/k8s/policy.example.toml > policy.toml +$K create ns $NS +$K label ns $NS pod-security.kubernetes.io/enforce=privileged +$K -n $NS create configmap auth-proxy-policy --from-file=policy.toml=policy.toml +$K -n $NS create configmap ap-ca --from-file=ca.pem=pki/ca.pem +$K -n $NS create configmap stub-pki --from-file=cert.pem=pki/cert.pem --from-file=key.pem=pki/key.pem +$K -n $NS create configmap stub-code --from-file=stub.py=/tmp/ap-item6-build/stub.py +$K -n $NS create secret generic auth-proxy-kiro --from-file=api_key=keys/real +$K -n $NS create secret generic auth-proxy-interim-agent --from-file=caller-key=keys/k/caller-key --from-file=surrogate=keys/k/surrogate +cat > stub.yaml < keys/stub.ip +echo "setup done; stub ip $(cat keys/stub.ip)" diff --git a/.agents/tasks/phase1-verify/item6-evidence/snap.sh b/.agents/tasks/phase1-verify/item6-evidence/snap.sh new file mode 100644 index 0000000..95ec374 --- /dev/null +++ b/.agents/tasks/phase1-verify/item6-evidence/snap.sh @@ -0,0 +1,16 @@ +#!/bin/sh +# state snapshot of mini; run on mini +echo "## namespaces"; sudo -n k3s kubectl get ns --no-headers | awk '{print $1,$2}' +echo "## pods all"; sudo -n k3s kubectl get pods -A --no-headers | awk '{print $1,$2,$4}' +echo "## images (ctr k8s.io)"; sudo -n k3s ctr -n k8s.io images ls -q | sort +echo "## listening"; ss -tulnH | awk '{print $1,$5}' | sort +echo "## tailscale"; tailscale status 2>&1 | awk '{print $1,$2,$5,$6,$7}' +echo "## ~ files"; ls -A ~ | sort +echo "## /tmp files (ssh-* excluded)"; ls -A /tmp | grep -v '^ssh-' | sort +echo "## cargo bin"; ls ~/.cargo/bin | sort +echo "## local bin"; ls -A ~/.local/bin | sort +echo "## crictl containers"; sudo -n k3s crictl ps -a -q | wc -l +echo "## host iptables OUTPUT md5"; sudo -n iptables -S OUTPUT | md5sum +echo "## iptables ap-item6 refs"; sudo -n iptables-save | grep -c ap-item6 +echo "## ps ap procs"; ps -eo args | grep -E "auth-proxy|ap-egress|hr-authority|ap-item6" | grep -v grep | wc -l +echo "## df"; df -h / | tail -1 | awk '{print $2,$3,$4}' diff --git a/.agents/tasks/phase1-verify/item6-evidence/stub.py b/.agents/tasks/phase1-verify/item6-evidence/stub.py new file mode 100644 index 0000000..d5832fd --- /dev/null +++ b/.agents/tasks/phase1-verify/item6-evidence/stub.py @@ -0,0 +1,31 @@ +# Test stub upstream (HTTPS). Logs one JSON line per request. Never prints header VALUES: +# the Authorization header is classified against the (dummy) real credential and the +# surrogate prefix only. +import http.server, ssl, json, sys, time +REAL = open("/run/secrets/real/api_key").read().strip() +class H(http.server.BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + def _do(self): + n = int(self.headers.get("content-length") or 0) + body = self.rfile.read(n) if n else b"" + a = self.headers.get("authorization") + cls = "none" if a is None else ("REAL" if a.strip() == REAL or a.strip() == "Bearer " + REAL else ("SURROGATE-prefix" if "aps_" in a else "other")) + rec = {"t": round(time.time(), 3), "host": self.headers.get("host"), "method": self.command, + "path": self.path, "xamz_target": self.headers.get("x-amz-target"), + "authorization_class": cls, "header_names": sorted(k.lower() for k in self.headers.keys()), + "body_len": len(body)} + print(json.dumps(rec), flush=True) + out = json.dumps({"__type": "ValidationException", "message": "stub upstream"}).encode() + self.send_response(400) + self.send_header("content-type", "application/x-amz-json-1.0") + self.send_header("content-length", str(len(out))) + self.end_headers() + self.wfile.write(out) + do_GET = do_POST = do_PUT = _do + def log_message(self, *a): pass +ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) +ctx.load_cert_chain("/etc/stub-pki/cert.pem", "/etc/stub-pki/key.pem") +s = http.server.ThreadingHTTPServer(("0.0.0.0", 8443), H) +s.socket = ctx.wrap_socket(s.socket, server_side=True) +print("stub up", flush=True) +s.serve_forever() diff --git a/.agents/tasks/phase1-verify/item6-evidence/t-hello-post.sh b/.agents/tasks/phase1-verify/item6-evidence/t-hello-post.sh new file mode 100644 index 0000000..1732dfc --- /dev/null +++ b/.agents/tasks/phase1-verify/item6-evidence/t-hello-post.sh @@ -0,0 +1,28 @@ +#!/bin/bash +K="sudo -n k3s kubectl -n ap-item6" +echo "### timeline from the proxy's own audit (ms, proxy clock)" +$K logs ap-agent -c proxy | python3 -c ' +import sys,json +ev=[json.loads(l) for l in sys.stdin if l.startswith("{")] +req=[e for e in ev if "plane" not in e] +ev=[e for e in ev if "plane" in e] +for r in req: print("request audit:",{k:r[k] for k in ("route","decision","code","session","status")}) +ren=[e["t"] for e in ev if e["plane"]=="renew"] +h201=[e["t"] for e in ev if e["plane"]=="hello" and e["status"]==201] +h409=[e["t"] for e in ev if e["plane"]=="hello" and e["status"]==409] +print("hello 201 times:",h201) +print("renew times:",ren) +last=max(t for t in ren if tlast] +print("409s after last renew: %d, last 409 at %d (= last+%.1fs)"%(len(b),b[-1],(b[-1]-last)/1000)) +print("first 409 after last renew... early hellos won before lapse: ",[t for t in h201 if th201[0]]) +print("winner 201 at %d = last renew + %.1fs"%(h201[-1],(h201[-1]-last)/1000)) +for e in ev: + if e["plane"] not in ("hello","renew") : print("other plane event:",e["plane"],e["result"],e["status"],e["t"]) +' +echo "### old surrogate through the proxy after the lapse (as UID 1000 in agent)" +cat /tmp/ap-item6-build/keys/k/caller-key | $K exec -i ap-agent -c agent -- sh -c 'read CK; S=$(cat /tmp/surrogate.sess-1794856771); curl -s -i -X POST http://127.0.0.1:18080/ap/$CK/kiro-krs/ -H "authorization: Bearer $S" -d "{}" | head -8' | sed -E 's/(apk|aps)_[0-9a-f]{64}/\1_/g' +echo "### new session's surrogate works? (live, goes to the stub: a 400 from the stub means admitted)" +cat /tmp/ap-item6-build/keys/k/caller-key | $K exec -i ap-agent -c agent -- sh -c 'read CK; S=$(cat $(ls -t /tmp/surrogate.sess-* | head -1)); curl -s -o /dev/null -w "new surrogate status=%{http_code}\n" -X POST http://127.0.0.1:18080/ap/$CK/kiro-krs/ -H "authorization: Bearer $S" -d "{}"' diff --git a/.agents/tasks/phase1-verify/item6-evidence/t-interim.sh b/.agents/tasks/phase1-verify/item6-evidence/t-interim.sh new file mode 100644 index 0000000..96f816c --- /dev/null +++ b/.agents/tasks/phase1-verify/item6-evidence/t-interim.sh @@ -0,0 +1,80 @@ +#!/bin/bash +# Run on mini. All output is masked for apk_/aps_ values. Stub logs never contain header values. +K="sudo -n k3s kubectl -n ap-item6"; A="$K exec ap-agent -c agent --" +mask() { sed -E 's/(apk|aps)_[0-9a-f]{64}/\1_/g; s/real-dummy-[0-9a-f]+//g'; } +h() { echo; echo "### $*"; } +slog() { $K logs stub | python3 -c ' +import sys,json,collections +c=collections.Counter() +for l in sys.stdin: + if l.startswith("{"): + r=json.loads(l); c[(r["host"],r["method"],r["path"].split("?")[0],r["xamz_target"],r["authorization_class"])]+=1 +for k,v in sorted(c.items()): print(v,"x host=%s %s %s target=%s authorization_class=%s"%k) +print("total requests at stub:",sum(c.values()))'; } +$K delete pod stub --wait=true >/dev/null; $K apply -f /tmp/ap-item6-build/stub.yaml >/dev/null; $K wait --for=condition=Ready pod/stub --timeout=90s >/dev/null +{ +h "pod"; $K get pod ap-agent -o wide --no-headers; $K get pod ap-agent -o jsonpath='{range .status.initContainerStatuses[*]}{.name} exit={.state.terminated.exitCode} {end}{"\n"}' +h "proxy start log"; $K logs ap-agent -c proxy | head -8 +h "netinit log"; $K logs ap-agent -c netinit | head -14 +h "kiro-settings init log"; $K logs ap-agent -c kiro-settings +h "settings file in agent HOME (caller key masked)"; $A sh -c 'cd /home/agent; find . -type f | head; for f in $(find . -name "*.json" -o -name settings* | head -3); do echo "-- $f"; cat $f; echo; done' +h "agent identity and env (surrogate masked)"; $A sh -c 'id; env | grep -E "^(HTTPS_PROXY|NO_PROXY|KIRO_)" ' +h "agent mounts: session socket path present?"; $A sh -c 'ls -la /run/auth-proxy /run/auth-proxy-admin 2>&1 | head -4' +echo; echo "######## T1 surrogate-only agent reaches the stub through the proxy" +CK=$($A sh -c "grep -o 'ap/apk_[0-9a-f]*' -r /home/agent | head -1 | sed 's#.*ap/##'") +h "POST krs with surrogate, caller key in path" +$A sh -c "curl -s -o /dev/null -w 'status=%{http_code}\n' -X POST http://127.0.0.1:18080/ap/$CK/kiro-krs/ -H \"authorization: Bearer \$KIRO_API_KEY\" -H 'tokentype: API_KEY' -H 'content-type: application/x-amz-json-1.0' -H 'x-amz-target: AmazonCodeWhispererStreamingService.GenerateAssistantResponse' -d '{}'" | mask +h "POST cps with surrogate" +$A sh -c "curl -s -w ' status=%{http_code}\n' -X POST http://127.0.0.1:18080/ap/$CK/kiro-cps/ -H \"authorization: Bearer \$KIRO_API_KEY\" -H 'x-amz-target: AmazonCodeWhispererService.GetProfile' -d '{}'" | mask +h "negative: wrong surrogate" +$A sh -c "curl -s -w ' status=%{http_code}\n' -X POST http://127.0.0.1:18080/ap/$CK/kiro-krs/ -H 'authorization: aps_0000000000000000000000000000000000000000000000000000000000000000' -d '{}'" | mask +h "negative: no surrogate" +$A sh -c "curl -s -w ' status=%{http_code}\n' -X POST http://127.0.0.1:18080/ap/$CK/kiro-krs/ -d '{}'" | mask +h "negative: wrong caller key" +$A sh -c "curl -s -w ' status=%{http_code}\n' -X POST http://127.0.0.1:18080/ap/apk_0000000000000000000000000000000000000000000000000000000000000000/kiro-krs/ -H \"authorization: Bearer \$KIRO_API_KEY\" -d '{}'" | mask +h "stub log (what the upstream saw, summarised)"; slog; echo "last raw line header names:"; $K logs stub | tail -1 | cut -c1-400 +echo; echo "######## T2 real credential never in the agent container" +REAL=$(cat /tmp/ap-item6-build/keys/real) +printf '%s\n' "$REAL" | $K exec -i ap-agent -c agent -- sh -c ' +read R +echo "uid=$(id -u) pid1-cmd=$(tr "\0" " " /dev/null; then n=$((n+1)); echo "HIT $p/$f"; fi; done; done +echo "proc environ+cmdline hits: $n" +echo "procs scanned: $(ls -d /proc/[0-9]* | wc -l)" +m=$(grep -rlF -- "$R" /home /tmp /work /etc /run /var /opt /usr/local /root 2>/dev/null | wc -l); echo "filesystem files containing it (home tmp work etc run var opt usr/local root): $m" +echo "secret volume mounted? $(ls /run/secrets 2>&1 | head -1)" +' | mask +h "mounts in agent container that mention secrets"; $A sh -c 'grep -E "secrets|auth-proxy-kiro" /proc/self/mountinfo | wc -l' +h "negative control: the same scan against the PROXY container's own secret file finds it? (proxy has no shell: skip) ; scan finds the value when planted in /tmp" +printf '%s\n' "$REAL" | $K exec -i ap-agent -c agent -- sh -c 'read R; printf %s "$R" > /tmp/plant; echo "control hits: $(grep -rlF -- "$R" /tmp 2>/dev/null | wc -l)"; rm /tmp/plant' +echo; echo "######## T3 direct egress and DNS refused for the agent UID" +STUB=$(cat /tmp/ap-item6-build/keys/stub.ip) +for cmd in \ + "curl -sS --noproxy '*' -m 8 -o /dev/null -w '%{http_code}' https://example.com" \ + "curl -sS --noproxy '*' -m 8 --resolve example.com:443:93.184.216.34 -o /dev/null -w '%{http_code}' https://example.com" \ + "curl -sS --noproxy '*' -m 8 -k -o /dev/null -w '%{http_code}' https://$STUB:8443/" \ + "getent hosts github.com" \ + "dig +time=2 +tries=1 @10.43.0.10 github.com" \ + "nc -zv -w 3 1.1.1.1 443" \ + "nc -zvu -w 3 10.43.0.10 53" \ + "python3 -c \"import socket;socket.create_connection(('8.8.8.8',53),3)\"" ; do + echo; echo "\$ $cmd"; t0=$(date +%s.%N); out=$($K exec ap-agent -c agent -- sh -c "$cmd" 2>&1); rc=$?; echo "$out" | tail -3; echo "exit=$rc elapsed=$(awk -v a=$t0 -v b=$(date +%s.%N) 'BEGIN{printf "%.2f",b-a}')s" +done +h "via ap-egress (allowlisted) vs not" +$A sh -c "curl -sS -m 15 -o /dev/null -w 'github.com via egress: %{http_code}\n' https://github.com/; curl -sS -m 10 -o /dev/null -w 'example.com via egress: %{http_code}\n' https://example.com/ 2>&1 | tail -1" +h "agent UID cannot reach the proxy's other things: admin socket"; $A sh -c 'ls /run/auth-proxy-admin 2>&1' +echo; echo "######## T4 Q1-A interim session via kiro-cli (settings written by the init container)" +h "kiro-cli version"; $A kiro-cli --version +h "kiro-cli settings read back (keys masked)"; $A sh -c 'kiro-cli settings api.krs.service; kiro-cli settings api.cps.service' | mask +h "kiro-cli chat --no-interactive (stub upstream, timeout 90s)" +$A sh -c 'cd /work && timeout 90 kiro-cli chat --no-interactive --trust-tools= "say hi" 2>&1 | tail -15; echo "exit=$?"' | mask +h "stub log after kiro-cli (summarised)"; slog +h "proxy audit lines (summarised) and a leak scan"; $K logs ap-agent -c proxy | python3 -c ' +import sys,json,collections +c=collections.Counter() +for l in sys.stdin: + if l.startswith("{"): + r=json.loads(l); c[(r["route"],r["aws_target"],r["decision"],r["code"],r["session"],r["status"])]+=1 +for k,v in sorted(c.items(),key=str): print(v,"x route=%s target=%s decision=%s code=%s session=%s status=%s"%k)' +echo "audit lines containing apk_/aps_/real-dummy: $($K logs ap-agent -c proxy | grep -cE 'apk_|aps_|real-dummy')" +} 2>&1 | mask diff --git a/.agents/tasks/phase1-verify/item6-gates.md b/.agents/tasks/phase1-verify/item6-gates.md new file mode 100644 index 0000000..9456901 --- /dev/null +++ b/.agents/tasks/phase1-verify/item6-gates.md @@ -0,0 +1,20 @@ +RESULT: PASS + +# Item 6 gates + +Code under test: `4ca9bf8` (exported with `git archive` to `~/item6-build` on macmini, cargo at `~/.cargo/bin`). +Python used by the test mocks and the matrix: PATH without `/opt/homebrew/bin` (macOS system python3 3.9.6). +With Homebrew python3 3.14 first on PATH the mock upstream fails to start, so the ap-proxy +integration tests fail with "mock upstream did not come up". That is an environment issue, not a code failure. + +| Gate | Result | +|---|---| +| cargo fmt --check | PASS | +| cargo clippy --workspace --all-targets -- -D warnings | PASS | +| cargo test --workspace | PASS (incl. hello_race 3/3) | +| cargo test -p ap-core | PASS (23) | +| scripts/check-session-socket.sh | PASS | +| cargo build --release | PASS | +| tests/matrix/matrix.py (test-resolve build) | PASS 31/31 (25/25 phase 0 + 6/6 added) | +| scripts/check-egress-deps.sh | PASS | +| scripts/check-no-test-resolve.sh target/release/auth-proxy | PASS | diff --git a/.agents/tasks/phase1-verify/item6-hello-race-fixed-mode.md b/.agents/tasks/phase1-verify/item6-hello-race-fixed-mode.md new file mode 100644 index 0000000..e61aaf6 --- /dev/null +++ b/.agents/tasks/phase1-verify/item6-hello-race-fixed-mode.md @@ -0,0 +1,25 @@ +RESULT: PASS (hello race holds with the fixed socket mode, no override) + +# Item 6b: hello race on `deploy/k8s/pod.yaml` with group 2000 and mode 0660 + +Same method as item 5 (`item5-hello-race.md`): `hr-authority` stand-in runtime (production `ap-client` `Authority`, +default 90 s lease, 30 s renew), PID 1 of the agent container, one same-UID child "orphan" hello-ing every 1 s. +Code `4bf8ae3`. Pod = `deploy/k8s/pod.yaml` with only image and `hostAliases`/CA test edits (`pod6.sh`, `INTERIM=0`). +**`AP_SESSION_SOCKET_MODE` is not set**: `kubectl get pod -o yaml | grep -ci "SESSION_SOCKET_MODE\|session-socket-mode"` -> `0`; +proxy args are `["--policy","/etc/auth-proxy/policy.toml"]`, env empty. Raw: `item6-evidence/hello-run.out`, `hello-post.out`. + +| Claim | Result | Evidence ([M]) | +|---|---|---| +| UID 1000 reaches the session socket without a 666 override | PASS | agent: `uid=1000 gid=2000`; `srw-rw---- 1 1001 2000 session.sock`; the first `hello` won (201) at the container's first attempt, 1 ms after start (proxy audit `hello ok 201`, then `register ok 201`). Item 5 saw `PermissionDenied` here. | +| Admin socket not reachable from the agent | PASS | `ls /run/auth-proxy-admin` in agent: No such file or directory (volume mounted only into `proxy`) | +| ap-egress (1002) has neither socket | PASS | in `ap-egress` (`id -u`=1002): `/run/auth-proxy` and `/run/auth-proxy-admin` do not exist (not mounted) | +| Same-UID orphan blocked while the lease is live | PASS | orphan (pid 11) `hello` every 1 s, all 409 `authority_active` (proxy audit shows each) | +| After SIGKILL of the agent container no orphan survives | PASS | kill 19:21:09.43 (`crictl stop --timeout 0`), new PID 1 `AUTH_START` 19:21:09.90 (0.5 s); `ps` after: only pid 1 and the exec'd `ps`; last orphan line 19:21:07.878, none after the kill | +| The 90 s lock holds; only the fresh PID 1 wins | PASS | proxy clock: last renew t0 = ...861678 ms. Between t0 and the winner: 27 hellos, all 409, last at +83.2 s; **0** 201s. Exec'd rival probe (UID 1000, 10 hellos every 5 s, +10 s to +60 s) all 409, "never won". Winner `201` at +98.2 s = lapse (+90 s) + the fresh PID 1's own backoff (attempts at +83.2 and +98.2 s); `HELLO_WON pid=1` 19:22:39.919 matches proxy `...959918` | +| Old session revoked at the lapse | PASS | as UID 1000: POST with the old surrogate -> `403 x-auth-proxy-error: surrogate_revoked`; audit `kiro-krs deny surrogate_revoked 403` | +| New session admitted | PASS | the new PID 1's surrogate gets past admission (audit `session=sess-1794856959`); the pod has no `--ca-file`, so the stub TLS fails and the call ends `502 upstream_unavailable`, which is after admission (a revoked/unknown surrogate would give 403) | +| Restarts | PASS | agent=1, proxy=0, ap-egress=0 | + +Limits: as in item 5, the attempts did not fall inside the 83 to 98 s window, so the 90.000 s boundary is pinned by the +unit test `hello_race.rs`, not here. The `hr-authority get` helper from item 5 now gets `400 host_rejected` (it sends a +Host the proxy refuses); the revocation check above used curl with the correct Host instead. The helper was a test tool. diff --git a/.agents/tasks/phase1-verify/item6-interim-k3s.md b/.agents/tasks/phase1-verify/item6-interim-k3s.md new file mode 100644 index 0000000..fd995e0 --- /dev/null +++ b/.agents/tasks/phase1-verify/item6-interim-k3s.md @@ -0,0 +1,53 @@ +RESULT: PASS (all five claims). One note on version: kiro-cli on `mini` is 2.37.0, not the 3.3.0 of item 4. + +# Item 6a: INTERIM Q1-A pod on real k3s (stub upstream, no real credential) + +Code under test: `4bf8ae3` exported with `git archive` (not the moving worktree). Node: `mini` +(LAN alias, Ubuntu 24.04 x86_64, k3s v1.36.2, single node). Namespace `ap-item6` (PSA privileged). +Run date (node clock): 2026-11-16. Tags: [M] measured. Raw output: `item6-evidence/interim-run.out`. + +## Method +- Linux binaries built ON `mini` (`cargo build --release --locked -p ap-proxy -p ap-egress`, glibc, throwaway + `CARGO_HOME`/target under `/tmp/ap-item6-build`). No cargo on the laptop or macmini. +- Images built on macmini (OrbStack docker, linux/amd64, ubuntu:24.04), moved as a tar, imported with + `k3s ctr -n k8s.io images import`. Names `docker.io/ap-item6/{proxy,egress,agent,hr,netinit}:dev`. + The agent image carries the kiro-cli binaries copied from `mini`'s own install (binaries only; the agent HOME + is an emptyDir, so no login state and no `~/.kiro` content went into the pod). +- Keys: `deploy/k8s/interim-keygen.sh` (shipped, unmodified) generated the caller key and surrogate. The "real" + credential is a random dummy (`real-dummy-`) generated on `mini`; no value was printed or committed. +- Stub upstream: an HTTPS python server (pod `stub`, Service) with a throwaway CA. It logs method, path, + `X-Amz-Target`, header NAMES, body length, and classifies the Authorization header as REAL / SURROGATE-prefix / + other / none. It never prints a header value. +- Manifest: `deploy/k8s/pod-interim-static.yaml` applied via `item6-evidence/pod6.sh` with these TEST-ONLY edits + (all other lines untouched; the unmodified diff is in the script): + 1. image placeholders -> the imported images, `imagePullPolicy: Never`; + 2. `--interim-static-surrogate-sha256=` filled with the real hash; + 3. proxy gets `--ca-file /etc/ap-ca/ca.pem` + a ConfigMap volume (to trust the stub CA); + 4. `hostAliases` on the pod map `runtime.us-east-1.kiro.dev` and the cps placeholder host to the stub Service IP; + 5. policy: example policy + caller hash + `port = 8443` on both routes (stub listens on 8443). + No `AP_SESSION_SOCKET_MODE` anywhere. + +## Claims + +| # | Claim | Result | Evidence ([M]) | +|---|---|---|---| +| 1 | Pod starts: netinit, **`kiro-settings` init container** (`kiro-cli settings`), proxy, ap-egress, agent | PASS | pod 3/3 Running; `netinit exit=0 kiro-settings exit=0`; `~/.kiro/settings/cli.json` in the agent HOME holds `api.krs.service` and `api.cps.service` endpoints `http://127.0.0.1:18080/ap/apk_/kiro-krs` and `/kiro-cps`, region us-east-1; `kiro-cli settings api.krs.service` reads them back | +| 2 | Interim start line and no session socket in the agent | PASS | proxy log: `INTERIM static session enabled (Q1-A): ... NO per-session revocation ...`; agent: `ls /run/auth-proxy` and `/run/auth-proxy-admin` -> "No such file or directory" | +| 3 | Agent holding only the surrogate reaches the stub through the proxy; upstream sees the REAL credential | PASS | agent env has only `KIRO_API_KEY=aps_`. `curl` as UID 1000 to `127.0.0.1:18080/ap//kiro-krs/` with `authorization: Bearer ` -> `status=400` (the stub's answer); stub log: `host=runtime.us-east-1.kiro.dev:8443 POST / target=AmazonCodeWhispererStreamingService.GenerateAssistantResponse authorization_class=REAL`; same for `kiro-cps` / `GetProfile`. Negatives: wrong surrogate 403 `surrogate_malformed`, none 403 `surrogate_missing`, wrong caller key 403 `caller_rejected`; none reached the stub | +| 4 | Real credential never in the agent container | PASS | scan as UID 1000 with the dummy value passed on stdin: `/proc/*/environ` + `cmdline` hits 0 (4 procs); files containing it under home, tmp, work, etc, run, var, opt, usr/local, root: 0; no `/run/secrets`; 0 secret mounts in `mountinfo`. Positive control (value planted in /tmp) found 1. Proxy audit has 0 lines containing `apk_`, `aps_` or the dummy | +| 5 | Direct egress and DNS from the agent UID refused | PASS | all fail in 0.16 to 0.24 s (incl. `kubectl exec` overhead): `curl --noproxy` example.com -> "Could not resolve host" (exit 6); `--resolve` to a literal IP -> connect refused (7); direct `https://:8443` refused (7); `getent hosts github.com` exit 2; `dig @kube-dns` "no servers could be reached"; `nc 1.1.1.1:443` refused; python socket to 8.8.8.8:53 `ConnectionRefusedError`. Via the pod's `HTTPS_PROXY` (ap-egress): `github.com` 200, `example.com` 000 (403 from ap-egress) | +| 6 | Q1-A interim session works with kiro-cli | PASS | `kiro-cli chat --no-interactive --trust-tools= "say hi"` (HTTPS_PROXY/settings from the pod): stub saw 1 `GenerateAssistantResponse` on the krs host, 42 `GetProfile` + 4 `ListAvailableModels` on the cps host (kiro-cli retries on the stub's 400), all `authorization_class=REAL`; chat printed the stub's error text, so the response came back through the proxy. Proxy audit: all allowed lines `session=interim-static`, `decision=allow`, 0 leaks | + +## Notes (not failures) +- kiro-cli 2.37.0 honours `api.krs.service` / `api.cps.service` in `~/.kiro/settings/cli.json` and sends + `Authorization: Bearer ` with `tokentype`. A bare `authorization: ` without `Bearer` + gets `surrogate_malformed`; that is the proxy's format check, not a defect. +- The test image's `ubuntu` user (UID 1000) is in the distro groups `adm`, `sudo`, etc. from `/etc/group`. That is + an artefact of the test image, not of the manifest (no `sudo` binary, no capabilities). Real agent images + should not add UID 1000 to such groups. +- The kiro-cli retry storm (46 control-plane calls in one `chat`) is kiro-cli reacting to the stub's HTTP 400. +- Not exercised: a real model response, the real kiro hosts, kiro-cli 3.3.0. + +## Defects found +None in the manifests or scripts. Two stale sentences updated (see commit): "has not been applied to a cluster yet" +in `docs/interim-static-session.md` and the matching line in `pod-interim-static.yaml`. diff --git a/.agents/tasks/phase1-verify/item6-socket-mode.md b/.agents/tasks/phase1-verify/item6-socket-mode.md new file mode 100644 index 0000000..662db1e --- /dev/null +++ b/.agents/tasks/phase1-verify/item6-socket-mode.md @@ -0,0 +1,39 @@ +RESULT: PASS (manifest + script; in-cluster proof is partB) + +# Item 6: session socket reachable by the agent UID without a world-writable socket + +Problem (item 5 finding): proxy UID 1001 creates `session.sock` 0660 `1001:1001`; the agent (UID 1000) shares no group, so `hello` got PermissionDenied and the runtime retried forever. Item 5 worked around it with `AP_SESSION_SOCKET_MODE=666`. + +## Mechanism +`proxy` and `agent` containers both set `runAsGroup: 2000`. The proxy creates the socket with its primary group, so it is `srw-rw---- 1001:2000` (mode unchanged, default 660). The agent UID 1000 connects as a group member. ap-egress (1002:1002) cannot. No proxy code change. + +Why smallest: one `runAsGroup` value on two containers; no new capability, no code, no pod-wide setting. + +## Admin socket +`/run/auth-proxy-admin/admin.sock`, mode 0600, in emptyDir `admin-sock` mounted only into `proxy`. The agent has neither the path nor the group. + +## Rejected +- `fsGroup` / `supplementalGroups`: pod-level only, adds the group to ap-egress too; fsGroup also changes Secret mount ownership (the pod header records it was measured harmful). +- mode 666: any UID in the pod (incl. ap-egress). +- chown socket to 1000: needs CAP_CHOWN in the proxy. +- proxy as UID 1000: breaks the UID separation netinit and the credential mount rely on. + +## Same-UID caveat +Every process in the agent container is in group 2000 and can speak to the session socket. Nothing new beyond the documented best-effort attribution between same-UID sessions: `hello` is unauthenticated by design and refused (409) while the lease is live; all other calls need the authority token. + +## Values +- `/run/auth-proxy/session.sock`, 0660, owner 1001, group 2000 (proxy UID 1001, GID 2000; agent UID 1000, GID 2000; ap-egress 1002:1002). +- `/run/auth-proxy-admin/admin.sock`, 0600, owner 1001, group 2000 (proxy only volume). +- `pod-interim-static.yaml`: unchanged config (agent does not mount the session socket; proxy stays 1001:1001), comment only. + +## Check +`scripts/check-session-socket.sh`: +- static (default, no cluster): both manifests; shared GID only where the agent mounts the session socket, ap-egress outside it, no fsGroup/supplementalGroups, no socket-mode override, agent has no admin-sock or credential Secret, ap-egress mounts no socket volume. Wired into `.github/workflows/ci.yml` and `scripts/sync-and-test.sh`. +- live: `LIVE=1 NS=.. POD=.. sh scripts/check-session-socket.sh` runs as UID 1000 in the agent container: connect to session.sock must succeed, admin.sock must be absent/denied, socket stat must be 0660 group 2000. NOT run yet (needs a cluster; partB). + +## Files +deploy/k8s/pod.yaml, deploy/k8s/pod-interim-static.yaml (comment), scripts/check-session-socket.sh (new), scripts/sync-and-test.sh, .github/workflows/ci.yml, docs/design/phase1.md (new section "Session socket access"), docs/interim-static-session.md. + +## Commands run +- `sh scripts/check-session-socket.sh`: 18 PASS, 0 FAIL on both manifests; a mutated pod.yaml (agent GID 1000) FAILs as expected. +- `sh scripts/sync-and-test.sh` (macmini: fmt --check, clippy --workspace --all-targets -D warnings, cargo test --workspace, ap-core test, release build, check-no-test-resolve, matrix, egress-deps): exit 0. diff --git a/.agents/tasks/phase1-verify/item7-cps-host.md b/.agents/tasks/phase1-verify/item7-cps-host.md new file mode 100644 index 0000000..dee4e6d --- /dev/null +++ b/.agents/tasks/phase1-verify/item7-cps-host.md @@ -0,0 +1,19 @@ +RESULT: host MEASURED = `management.us-east-1.kiro.dev:443`; `pass_headers` / `error_shape` UNCHECKED (need a real first response). + +# Item 7: `kiro-cps` route host + +- Real requests to the service: **0**. Dummy `KIRO_API_KEY=aps_`, throwaway HOME and working dir under `/tmp`. No real key read. +- Host: the laptop (macOS), kiro-cli 3.3.0 (the item 4 host). Homelab Linux hosts do not have 3.3.0 (`mini` 2.37.0, `bl` 2.1.1, rpi1/rpi2 none), so no `unshare -n` run; macOS has no netns. +- Containment instead: `HTTPS_PROXY`/`HTTP_PROXY` -> a local listener that logs the `CONNECT host:port` line and answers 403. kiro-cli honors the proxy, so there was no DNS lookup and no connection beyond localhost. +- Run 1 (60 s, one attempt): CONNECT counts: `management.us-east-1.kiro.dev:443` x30, `runtime.us-east-1.kiro.dev:443` x3 (model path, = `kiro-krs`), `q.us-east-1.amazonaws.com` x3, `telemetry.us-east-1.kiro.dev` x1, `cognito-identity.us-east-1.amazonaws.com` x7, `desktop-release.q.us-east-1.amazonaws.com` x3, and `management.*` in eu-central-1, us-gov-east-1, us-gov-west-1 and four us-iso* regions, x9 each. +- Run 2 (one attempt): same, plus `api.cps.service` overridden to the local listener (the item 4 knob). Every `management.*` CONNECT vanished; 29 POSTs to `/cps/` arrived. So `management.us-east-1.kiro.dev` is the default cps host; `runtime.us-east-1.kiro.dev` stays the model host. +- Not seen: the `Host` header inside TLS (assumed `management.us-east-1.kiro.dev`, port 443), which call goes to the other regions, `tokentype` and the error shape. +- Total diagnostic runs: 2 (plus one that failed to start because `timeout` is missing on macOS). + +## Cleanup check +- Listener killed (`pgrep -fl cap.py` empty); `/tmp/cpsprobe` (HOME, workdir, logs) deleted and `ls` reports it absent. +- Only a `/tmp/keep` copy of two CONNECT logs remains outside the repo and is removed at the end of this step. +- No tailscale or system state touched; kiro-cli not installed anywhere; no hosts, IPs or logins in this report. + +## Checks (macmini, this commit's tree) +fmt --check, clippy --workspace --all-targets -D warnings, cargo test --workspace: all pass; check-egress-deps.sh and check-no-test-resolve.sh (after `cargo build --release`): ok. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..4167e22 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,41 @@ +name: ci +on: + push: + branches: [main] + pull_request: +jobs: + gate: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@stable + with: + components: rustfmt, clippy + - uses: Swatinem/rust-cache@v2 + # Same commands as scripts/sync-and-test.sh runs on macmini. + - run: cargo fmt --check + - run: cargo clippy --workspace --all-targets -- -D warnings + - run: cargo test --workspace + # The workspace test run turns the ap-core `test-resolve` feature on for every + # crate; this run checks the shipped feature set rejects route.connect_to. + - run: cargo test -p ap-core + - run: sh scripts/check-session-socket.sh + - run: cargo build --release + - run: sh scripts/check-no-test-resolve.sh target/release/auth-proxy + # The matrix routes to local mock upstreams with connect_to, so it runs a + # test-resolve build of auth-proxy in its own target directory. + - run: cargo build --release -p ap-proxy --features test-resolve --target-dir target/matrix-bin + - name: Fail-closed matrix + run: | + mkdir -p matrix-out + rc=0 + python3 tests/matrix/matrix.py --bin target/matrix-bin/release --json matrix-out/matrix.json > matrix-out/matrix.txt || rc=$? + cat matrix-out/matrix.txt + exit $rc + - run: sh scripts/check-egress-deps.sh + - uses: actions/upload-artifact@v4 + if: always() + with: + name: matrix-output + path: matrix-out/ + # Static musl release job: documented in docs/operations.md, not run here yet. diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..2f7896d --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +target/ diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..9059a3f --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,1660 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "ap-broker" +version = "0.1.0" +dependencies = [ + "ap-core", + "getrandom 0.2.17", + "hex", + "serde", + "serde_json", + "sha2", + "subtle", + "zeroize", +] + +[[package]] +name = "ap-client" +version = "0.1.0" +dependencies = [ + "ap-core", + "getrandom 0.2.17", + "hex", + "serde", + "serde_json", + "sha2", + "tokio", +] + +[[package]] +name = "ap-core" +version = "0.1.0" +dependencies = [ + "hex", + "http", + "serde", + "serde_json", + "sha2", + "subtle", + "toml", +] + +[[package]] +name = "ap-egress" +version = "0.1.0" +dependencies = [ + "ap-core", + "tokio", +] + +[[package]] +name = "ap-proxy" +version = "0.1.0" +dependencies = [ + "ap-broker", + "ap-client", + "ap-core", + "axum", + "bytes", + "futures-util", + "h2", + "hex", + "http", + "reqwest", + "rustls", + "rustls-pki-types", + "serde", + "serde_json", + "sha2", + "tokio", + "tokio-rustls", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "axum" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" +dependencies = [ + "axum-core", + "bytes", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "itoa", + "matchit", + "memchr", + "mime", + "percent-encoding", + "pin-project-lite", + "serde_core", + "sync_wrapper", + "tokio", + "tower", + "tower-layer", + "tower-service", +] + +[[package]] +name = "axum-core" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "mime", + "pin-project-lite", + "sync_wrapper", + "tower-layer", + "tower-service", +] + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "bumpalo" +version = "3.20.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "cc" +version = "1.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33ef9e3e8154a45c7a95cff4c1299702106ad94062d7bb85fdc5d3a5afd91d45" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "rand_core", +] + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "errno" +version = "0.3.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "wasi", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi", + "rand_core", + "wasm-bindgen", +] + +[[package]] +name = "h2" +version = "0.4.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d29020232d6aa3fb1daca64c1127cf662cf97f254ae16c18c05b8ab635fc118" +dependencies = [ + "atomic-waker", + "bytes", + "fnv", + "futures-core", + "futures-sink", + "http", + "indexmap", + "slab", + "tokio", + "tokio-util", + "tracing", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + +[[package]] +name = "hyper" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c" +dependencies = [ + "atomic-waker", + "bytes", + "futures-channel", + "futures-core", + "h2", + "http", + "http-body", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "tokio", + "tokio-rustls", + "tower-service", + "webpki-roots", +] + +[[package]] +name = "hyper-util" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" +dependencies = [ + "base64 0.23.1", + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "httparse", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2", + "tokio", + "tower-service", + "tracing", +] + +[[package]] +name = "icu_collections" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" + +[[package]] +name = "icu_properties" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" + +[[package]] +name = "icu_provider" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", +] + +[[package]] +name = "ipnet" +version = "2.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "js-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "lru-slab" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f" + +[[package]] +name = "matchit" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "mime" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5848f5a9e8117cf94f2f90faac24a87ff81600ff8628c1e3deaab572e76bfa1" + +[[package]] +name = "mio" +version = "1.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20521a903f02b0a573cd6840e9d0a5a0cc043d361fe924092cd70f8556cc9c4a" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quinn" +version = "0.11.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4051e23e9185c255a7e33ef59cdbca87a22d359052eecd22fc6b901fb37d9d11" +dependencies = [ + "bytes", + "cfg_aliases", + "pin-project-lite", + "quinn-proto", + "quinn-udp", + "rustc-hash", + "rustls", + "socket2", + "thiserror", + "tokio", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-proto" +version = "0.11.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe" +dependencies = [ + "bytes", + "getrandom 0.4.3", + "lru-slab", + "rand", + "rand_pcg", + "ring", + "rustc-hash", + "rustls", + "rustls-pki-types", + "slab", + "thiserror", + "tinyvec", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-udp" +version = "0.5.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016" +dependencies = [ + "cfg_aliases", + "libc", + "once_cell", + "socket2", + "tracing", + "windows-sys 0.61.2", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f6fa277c67e6ea590466f04c3fe82cb509f0864fe470643e5570de9514a9b11" +dependencies = [ + "chacha20", + "getrandom 0.4.3", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "rand_pcg" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a" +dependencies = [ + "rand_core", +] + +[[package]] +name = "reqwest" +version = "0.12.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" +dependencies = [ + "base64 0.22.1", + "bytes", + "futures-core", + "futures-util", + "h2", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "js-sys", + "log", + "percent-encoding", + "pin-project-lite", + "quinn", + "rustls", + "rustls-pki-types", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tokio-util", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "wasm-streams", + "web-sys", + "webpki-roots", +] + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb" +dependencies = [ + "web-time", + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_spanned" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3" +dependencies = [ + "serde", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46" + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tinystr" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + +[[package]] +name = "tokio" +version = "1.54.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" +dependencies = [ + "bytes", + "libc", + "mio", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" +dependencies = [ + "rustls", + "tokio", +] + +[[package]] +name = "tokio-util" +version = "0.7.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e464cf451ba96ebfc6f9b6542f17ee8b8956e33f1e40d9690624e59d7a7f8a4b" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "libc", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "toml" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362" +dependencies = [ + "serde", + "serde_spanned", + "toml_datetime", + "toml_edit", +] + +[[package]] +name = "toml_datetime" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22cddaf88f4fbc13c51aebbf5f8eceb5c7c5a9da2ac40a13519eb5b0a0e8f11c" +dependencies = [ + "serde", +] + +[[package]] +name = "toml_edit" +version = "0.22.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a" +dependencies = [ + "indexmap", + "serde", + "serde_spanned", + "toml_datetime", + "toml_write", + "winnow", +] + +[[package]] +name = "toml_write" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801" + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", +] + +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "bitflags", + "bytes", + "futures-util", + "http", + "http-body", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", + "url", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-core", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0" +dependencies = [ + "utf_types", +] + +[[package]] +name = "utf_types" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "want" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasm-bindgen" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" +dependencies = [ + "cfg-if", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.80" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e14e0327cb5368ad60ccb22d04a9827a693c95a926d8d125e9fa39e0baec501" +dependencies = [ + "js-sys", + "tokio", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "wasm-streams" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15053d8d85c7eccdbefef60f06769760a563c7f0a9d6902a13d35c7800b0ad65" +dependencies = [ + "futures-util", + "js-sys", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "web-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webpki-roots" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7265c9301c16a8711c992c2d8da90ee77ef54b1ed51482d6dfeb00dc756b1297" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "winnow" +version = "0.7.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945" +dependencies = [ + "memchr", +] + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "yoke" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "synstructure", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..217f45b --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,34 @@ +[workspace] +resolver = "2" +members = ["crates/*"] +# The Phase 0 spike packages stay outside the workspace as reference code. +exclude = ["spike/exp2"] + +[workspace.package] +version = "0.1.0" +edition = "2021" +license = "MIT" +publish = false + +[workspace.dependencies] +ap-core = { path = "crates/ap-core" } +ap-broker = { path = "crates/ap-broker" } +ap-client = { path = "crates/ap-client" } +axum = { version = "0.8", default-features = false, features = ["http1", "tokio"] } +futures-util = "0.3" +reqwest = { version = "0.12", default-features = false, features = ["rustls-tls", "stream", "http2"] } +tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "sync", "time", "signal", "io-util"] } +getrandom = "0.2" +hex = "0.4" +http = "1" +serde = { version = "1", features = ["derive"] } +serde_json = "1" +sha2 = "0.10" +subtle = "2" +toml = "0.8" +zeroize = "1" + +[profile.release] +lto = "thin" +codegen-units = 1 +strip = true diff --git a/crates/ap-broker/Cargo.toml b/crates/ap-broker/Cargo.toml new file mode 100644 index 0000000..451fd06 --- /dev/null +++ b/crates/ap-broker/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "ap-broker" +description = "auth-proxy broker: session registry with leases, authority lock, credential store (file), Broker trait. The only crate that holds a credential value." +version.workspace = true +edition.workspace = true +license.workspace = true +publish.workspace = true + +[dependencies] +ap-core.workspace = true +getrandom.workspace = true +hex.workspace = true +serde.workspace = true +serde_json.workspace = true +sha2.workspace = true +subtle.workspace = true +zeroize.workspace = true diff --git a/crates/ap-broker/src/authority.rs b/crates/ap-broker/src/authority.rs new file mode 100644 index 0000000..e72a3be --- /dev/null +++ b/crates/ap-broker/src/authority.rs @@ -0,0 +1,172 @@ +//! The authority lock (Q1-B, Kubernetes). +//! +//! One session authority at a time. `hello` takes the lock and returns a +//! random token; only the token's sha256 is kept, in memory and in a +//! proxy-private state file. The authority renews every 30 s; the lock lapses +//! after 90 s without a renewal, and the caller then revokes every session. +//! +//! The runtime is the authority container's PID 1, so when it dies its shells +//! die with it, and the next `hello` can only come from the restarted runtime, +//! which sends it before any session exists. Until the lease lapses, a `hello` +//! from anyone gets 409. +//! +//! Proxy restart: the persisted hash stays valid, and the lock is treated as +//! live for one full authority lease from the restart (the proxy cannot know +//! how long ago the last renewal was). + +use crate::error::PlaneError; +use sha2::{Digest, Sha256}; +use std::path::PathBuf; +use std::time::Duration; +use subtle::ConstantTimeEq; + +pub const DEFAULT_AUTHORITY_LEASE_SECS: u64 = 90; +/// How often the authority renews. Documented to clients; the lock itself only +/// needs the lease length. +pub const AUTHORITY_RENEW_SECS: u64 = 30; +/// Shorter leases exist only so tests can run fast. +pub const MIN_AUTHORITY_LEASE_SECS: u64 = 3; + +struct Active { + token_hash: [u8; 32], + expires: Duration, +} + +pub struct AuthorityLock { + lease: Duration, + state_path: Option, + active: Option, +} + +impl AuthorityLock { + /// `now` is the clock reading at construction (proxy start). A persisted + /// token hash makes the lock live until `now + lease`. + pub fn new( + lease_secs: u64, + state_path: Option, + now: Duration, + ) -> Result { + if lease_secs < MIN_AUTHORITY_LEASE_SECS { + return Err(format!( + "authority lease must be at least {MIN_AUTHORITY_LEASE_SECS} s" + )); + } + let lease = Duration::from_secs(lease_secs); + let active = state_path + .as_deref() + .and_then(load_hash) + .map(|token_hash| Active { + token_hash, + expires: now + lease, + }); + Ok(AuthorityLock { + lease, + state_path, + active, + }) + } + + pub fn lease_secs(&self) -> u64 { + self.lease.as_secs() + } + + pub fn is_live(&self, now: Duration) -> bool { + self.active.as_ref().is_some_and(|a| now < a.expires) + } + + /// Free the lock if its lease has lapsed. Returns true when it just did, + /// so the caller can revoke the authority's sessions. + pub fn poll(&mut self, now: Duration) -> bool { + if self.active.is_some() && !self.is_live(now) { + self.active = None; + self.clear_state(); + true + } else { + false + } + } + + /// Take the lock. Call `poll` first. Returns the token (shown once) or + /// `AuthorityActive`. + pub fn hello(&mut self, now: Duration) -> Result { + if self.is_live(now) { + return Err(PlaneError::AuthorityActive); + } + let mut raw = [0u8; 32]; + getrandom::getrandom(&mut raw) + .map_err(|_| PlaneError::Internal("no randomness available".into()))?; + let token = format!("apt_{}", hex::encode(raw)); + let token_hash: [u8; 32] = Sha256::digest(token.as_bytes()).into(); + // Persist first: if the state cannot be written, the lock is not taken. + self.persist(&token_hash)?; + self.active = Some(Active { + token_hash, + expires: now + self.lease, + }); + Ok(token) + } + + /// Constant-time token check. A lapsed lock accepts no token. + pub fn verify(&self, token: &str, now: Duration) -> bool { + match &self.active { + Some(a) if now < a.expires && token.len() <= 256 => { + let h: [u8; 32] = Sha256::digest(token.as_bytes()).into(); + bool::from(h.ct_eq(&a.token_hash)) + } + _ => false, + } + } + + /// Extend the lease to `now + lease`. Only the explicit renew call does + /// this; no other request extends it. + pub fn renew(&mut self, now: Duration) { + if let Some(a) = self.active.as_mut() { + a.expires = now + self.lease; + } + } + + fn persist(&self, hash: &[u8; 32]) -> Result<(), PlaneError> { + let Some(path) = &self.state_path else { + return Ok(()); + }; + let body = serde_json::json!({"version": 1, "token_sha256": hex::encode(hash)}).to_string(); + write_private(path, body.as_bytes()) + .map_err(|e| PlaneError::Internal(format!("persist authority state: {}", e.kind()))) + } + + fn clear_state(&self) { + if let Some(path) = &self.state_path { + // Best effort: a stale file only makes the lock live for one lease + // after a later restart. + let _ = std::fs::remove_file(path); + } + } +} + +fn load_hash(path: &std::path::Path) -> Option<[u8; 32]> { + let raw = std::fs::read(path).ok()?; + let v: serde_json::Value = serde_json::from_slice(&raw).ok()?; + if v.get("version")?.as_u64()? != 1 { + return None; + } + let h = v.get("token_sha256")?.as_str()?; + let mut out = [0u8; 32]; + hex::decode_to_slice(h, &mut out).ok()?; + Some(out) +} + +fn write_private(path: &std::path::Path, bytes: &[u8]) -> std::io::Result<()> { + use std::io::Write; + let tmp = path.with_extension("tmp"); + let mut opts = std::fs::OpenOptions::new(); + opts.write(true).create(true).truncate(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + opts.mode(0o600); + } + let mut f = opts.open(&tmp)?; + f.write_all(bytes)?; + f.sync_all()?; + std::fs::rename(&tmp, path) +} diff --git a/crates/ap-broker/src/broker.rs b/crates/ap-broker/src/broker.rs new file mode 100644 index 0000000..b6e7775 --- /dev/null +++ b/crates/ap-broker/src/broker.rs @@ -0,0 +1,135 @@ +//! The `Broker` trait the proxy calls, and the in-process implementation +//! (Q2-A): session plane plus file store. No network, no resolve endpoint. + +use crate::plane::SessionPlane; +use crate::registry::SessionView; +use crate::store::{Secret, Store}; +use ap_core::{Code, Policy}; +use std::sync::Arc; + +/// What admission learned about a surrogate: which session it belongs to, and +/// which of the session's credentials can be used on the requested route. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Binding { + pub session: String, + pub generation: u64, + /// Credentials bound to the session whose route set contains the route. + pub credentials: Vec, +} + +/// The two questions the proxy asks per request, in pipeline order: is this +/// surrogate live for this route (step 5), and then what is the credential +/// value (step 7). `policy` is the snapshot the request is being judged +/// against, so one request sees one snapshot. +pub trait Broker: Send + Sync { + /// `surrogate_unknown | _revoked | _expired | _wrong_caller | _wrong_route`. + fn admit( + &self, + surrogate_sha256: &[u8; 32], + route: &str, + policy: &Policy, + ) -> Result; + + /// `broker_unavailable` when the store cannot produce the value now. + fn secret(&self, credential: &str, policy: &Policy) -> Result, Code>; +} + +/// Session id the interim static session reports to the audit log. +pub const INTERIM_SESSION: &str = "interim-static"; + +/// INTERIM Q1-A path: the one session of a pod, fixed at proxy start. It has no +/// lease, no absolute TTL and no authority; nothing on the session plane can +/// register, renew, resync or revoke it. It ends only when the proxy process +/// does (pod deletion or restart). The owner accepted that there is no +/// per-session revocation on this path (decision record, Q1). +struct InterimSession { + hash: [u8; 32], + identity: String, + credentials: Vec, +} + +pub struct LocalBroker { + plane: Arc, + store: Arc, + interim: Option, +} + +impl LocalBroker { + pub fn new(plane: Arc, store: Arc) -> LocalBroker { + LocalBroker { + plane, + store, + interim: None, + } + } + + /// INTERIM Q1-A: also admit one fixed surrogate (by `sha256`) as a session of + /// `identity` bound to `credentials`, for the life of this broker. The Q1-B + /// session machinery is untouched: this is a separate admission branch. + pub fn with_interim_static_session( + mut self, + surrogate_sha256: [u8; 32], + identity: &str, + credentials: Vec, + ) -> LocalBroker { + self.interim = Some(InterimSession { + hash: surrogate_sha256, + identity: identity.to_string(), + credentials, + }); + self + } + + pub fn plane(&self) -> &Arc { + &self.plane + } +} + +impl Broker for LocalBroker { + fn admit( + &self, + surrogate_sha256: &[u8; 32], + route: &str, + policy: &Policy, + ) -> Result { + let view = match &self.interim { + Some(i) if i.hash == *surrogate_sha256 => SessionView { + session: INTERIM_SESSION.to_string(), + generation: 0, + identity: i.identity.clone(), + credentials: i.credentials.clone(), + }, + _ => self.plane.lookup(surrogate_sha256)?, + }; + // A policy that now names another identity does not own this session. + if view.identity != policy.identity() { + return Err(Code::SurrogateWrongCaller); + } + let usable: Vec = view + .credentials + .into_iter() + .filter(|id| { + policy + .credential(id) + .is_some_and(|c| c.routes.iter().any(|r| r == route)) + }) + .collect(); + if usable.is_empty() { + return Err(Code::SurrogateWrongRoute); + } + Ok(Binding { + session: view.session, + generation: view.generation, + credentials: usable, + }) + } + + fn secret(&self, credential: &str, policy: &Policy) -> Result, Code> { + let c = policy + .credential(credential) + .ok_or(Code::BrokerUnavailable)?; + self.store + .resolve(&c.source) + .map_err(|_| Code::BrokerUnavailable) + } +} diff --git a/crates/ap-broker/src/clock.rs b/crates/ap-broker/src/clock.rs new file mode 100644 index 0000000..a2541c0 --- /dev/null +++ b/crates/ap-broker/src/clock.rs @@ -0,0 +1,59 @@ +//! Injectable monotonic clock, so lease tests do not sleep. + +use std::sync::atomic::{AtomicU64, Ordering}; +use std::time::{Duration, Instant}; + +/// Time since an arbitrary origin. Monotonic; never compared across processes. +pub trait Clock: Send + Sync { + fn now(&self) -> Duration; +} + +pub struct SystemClock { + origin: Instant, +} + +impl SystemClock { + pub fn new() -> SystemClock { + SystemClock { + origin: Instant::now(), + } + } +} + +impl Default for SystemClock { + fn default() -> Self { + SystemClock::new() + } +} + +impl Clock for SystemClock { + fn now(&self) -> Duration { + self.origin.elapsed() + } +} + +/// A clock that only moves when told to. +#[derive(Default)] +pub struct FakeClock { + ms: AtomicU64, +} + +impl FakeClock { + pub fn new() -> FakeClock { + FakeClock::default() + } + + pub fn advance(&self, d: Duration) { + self.ms.fetch_add(d.as_millis() as u64, Ordering::SeqCst); + } + + pub fn advance_secs(&self, s: u64) { + self.advance(Duration::from_secs(s)); + } +} + +impl Clock for FakeClock { + fn now(&self) -> Duration { + Duration::from_millis(self.ms.load(Ordering::SeqCst)) + } +} diff --git a/crates/ap-broker/src/error.rs b/crates/ap-broker/src/error.rs new file mode 100644 index 0000000..19745a7 --- /dev/null +++ b/crates/ap-broker/src/error.rs @@ -0,0 +1,75 @@ +//! Session-plane errors. Messages name fields and ids, never a token or a +//! surrogate. + +use std::fmt; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum PlaneError { + /// Missing, wrong or lapsed authority token (401). + Unauthorized, + /// `hello` while the current authority's lease is live (409). + AuthorityActive, + /// A field failed validation (400). Nothing was changed. + Invalid(String), + /// A credential id is not defined for this identity (403). + CredentialNotGranted(String), + /// Same session and generation registered with another binding, or the + /// surrogate hash is already bound elsewhere (409). + Conflict(String), + /// Over `max_sessions` (429). + TooManySessions, + /// The proxy could not persist its state (500). + Internal(String), +} + +impl PlaneError { + pub fn status(&self) -> u16 { + match self { + PlaneError::Invalid(_) => 400, + PlaneError::Unauthorized => 401, + PlaneError::CredentialNotGranted(_) => 403, + PlaneError::AuthorityActive | PlaneError::Conflict(_) => 409, + PlaneError::TooManySessions => 429, + PlaneError::Internal(_) => 500, + } + } + + pub fn code(&self) -> &'static str { + match self { + PlaneError::Unauthorized => "unauthorized", + PlaneError::AuthorityActive => "authority_active", + PlaneError::Invalid(_) => "invalid_request", + PlaneError::CredentialNotGranted(_) => "credential_not_granted", + PlaneError::Conflict(_) => "session_conflict", + PlaneError::TooManySessions => "too_many_sessions", + PlaneError::Internal(_) => "internal_error", + } + } + + /// Prefix the message with the failing list entry (resync). + pub fn at_entry(self, index: usize) -> PlaneError { + let p = |m: String| format!("entry {index}: {m}"); + match self { + PlaneError::Invalid(m) => PlaneError::Invalid(p(m)), + PlaneError::CredentialNotGranted(m) => PlaneError::CredentialNotGranted(p(m)), + PlaneError::Conflict(m) => PlaneError::Conflict(p(m)), + other => other, + } + } +} + +impl fmt::Display for PlaneError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + PlaneError::Unauthorized => f.write_str("authority token missing, wrong or lapsed"), + PlaneError::AuthorityActive => f.write_str("another authority's lease is live"), + PlaneError::Invalid(m) | PlaneError::Conflict(m) | PlaneError::Internal(m) => { + f.write_str(m) + } + PlaneError::CredentialNotGranted(m) => f.write_str(m), + PlaneError::TooManySessions => f.write_str("too many sessions"), + } + } +} + +impl std::error::Error for PlaneError {} diff --git a/crates/ap-broker/src/lib.rs b/crates/ap-broker/src/lib.rs new file mode 100644 index 0000000..51eabc5 --- /dev/null +++ b/crates/ap-broker/src/lib.rs @@ -0,0 +1,26 @@ +//! auth-proxy broker (Q1-B session plane, Q2-A in-process broker, S1 file +//! store). The only crate that ever holds a credential value. +//! +//! No network I/O, no `aws-sm` feature, no network store: those belong to the +//! deferred ECS phase. + +pub mod authority; +pub mod broker; +pub mod clock; +pub mod error; +pub mod plane; +pub mod registry; +pub mod store; + +pub use authority::{ + AuthorityLock, AUTHORITY_RENEW_SECS, DEFAULT_AUTHORITY_LEASE_SECS, MIN_AUTHORITY_LEASE_SECS, +}; +pub use broker::{Binding, Broker, LocalBroker, INTERIM_SESSION}; +pub use clock::{Clock, FakeClock, SystemClock}; +pub use error::PlaneError; +pub use plane::{HelloOk, LeaseOk, PlaneConfig, RenewOk, ResyncOk, SessionPlane}; +pub use registry::{ + validate_register, RegisterReq, RegistryConfig, SessionRef, SessionRegistry, SessionView, + ValidEntry, DEFAULT_ABSOLUTE_TTL_SECS, DEFAULT_MAX_SESSIONS, DEFAULT_SESSION_LEASE_SECS, +}; +pub use store::{FileStore, Secret, Store, StoreError}; diff --git a/crates/ap-broker/src/plane.rs b/crates/ap-broker/src/plane.rs new file mode 100644 index 0000000..cb6441e --- /dev/null +++ b/crates/ap-broker/src/plane.rs @@ -0,0 +1,219 @@ +//! The session plane's state machine: authority lock plus session registry, +//! behind one mutex so a lapse and the revoke-all that follows it cannot be +//! interleaved with another call. No I/O except the authority state file. +//! +//! The HTTP layer (ap-proxy) maps these methods to the five calls in the +//! design doc and the `PlaneError` to its status codes. + +use crate::authority::{AuthorityLock, DEFAULT_AUTHORITY_LEASE_SECS}; +use crate::clock::Clock; +use crate::error::PlaneError; +use crate::registry::{ + validate_register, RegisterReq, RegistryConfig, SessionRef, SessionRegistry, SessionView, +}; +use ap_core::{Code, Policy}; +use serde::Serialize; +use std::fmt; +use std::path::PathBuf; +use std::sync::{Arc, Mutex}; + +#[derive(Debug, Clone)] +pub struct PlaneConfig { + pub registry: RegistryConfig, + pub authority_lease_secs: u64, + /// Proxy-private file holding the authority token's hash (and nothing + /// secret). `None` keeps it in memory only. + pub authority_state: Option, +} + +impl Default for PlaneConfig { + fn default() -> Self { + PlaneConfig { + registry: RegistryConfig::default(), + authority_lease_secs: DEFAULT_AUTHORITY_LEASE_SECS, + authority_state: None, + } + } +} + +/// `201` body of `hello`. The token is shown once; `Debug` redacts it. +#[derive(Serialize, Clone, PartialEq, Eq)] +pub struct HelloOk { + pub authority_token: String, + pub lease_secs: u64, +} + +impl fmt::Debug for HelloOk { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("HelloOk") + .field("authority_token", &"") + .field("lease_secs", &self.lease_secs) + .finish() + } +} + +#[derive(Serialize, Debug, Clone, PartialEq, Eq)] +pub struct LeaseOk { + pub lease_secs: u64, +} + +#[derive(Serialize, Debug, Clone, PartialEq, Eq)] +pub struct RenewOk { + pub lease_secs: u64, + pub unknown: Vec, +} + +#[derive(Serialize, Debug, Clone, PartialEq, Eq)] +pub struct ResyncOk { + pub registered: usize, + pub dropped: usize, +} + +struct Inner { + authority: AuthorityLock, + registry: SessionRegistry, +} + +pub struct SessionPlane { + clock: Arc, + inner: Mutex, +} + +impl SessionPlane { + pub fn new(cfg: PlaneConfig, clock: Arc) -> Result { + let authority = + AuthorityLock::new(cfg.authority_lease_secs, cfg.authority_state, clock.now())?; + Ok(SessionPlane { + clock, + inner: Mutex::new(Inner { + authority, + registry: SessionRegistry::new(cfg.registry), + }), + }) + } + + /// Apply time: free a lapsed authority lock (revoking every session) and + /// drop lapsed sessions. Run at the start of every call, so nothing rides + /// on a lease that has ended. + fn tick(inner: &mut Inner, now: std::time::Duration) { + if inner.authority.poll(now) { + inner.registry.revoke_all(); + } + inner.registry.sweep(now); + } + + fn authed( + &self, + token: &str, + ) -> Result<(std::sync::MutexGuard<'_, Inner>, std::time::Duration), PlaneError> { + let now = self.clock.now(); + let mut g = self.inner.lock().unwrap(); + Self::tick(&mut g, now); + if g.authority.verify(token, now) { + Ok((g, now)) + } else { + Err(PlaneError::Unauthorized) + } + } + + /// `POST /v1/hello`. + pub fn hello(&self) -> Result { + let now = self.clock.now(); + let mut g = self.inner.lock().unwrap(); + Self::tick(&mut g, now); + let token = g.authority.hello(now)?; + Ok(HelloOk { + authority_token: token, + lease_secs: g.authority.lease_secs(), + }) + } + + /// `POST /v1/sessions`. + pub fn register( + &self, + token: &str, + policy: &Policy, + req: &RegisterReq, + ) -> Result { + let (mut g, now) = self.authed(token)?; + let v = validate_register(policy, req)?; + let lease = g.registry.register(now, policy.identity(), v)?; + Ok(LeaseOk { + lease_secs: lease.as_secs(), + }) + } + + /// `POST /v1/renew`: extends the authority's own lease and the listed + /// sessions' leases (never past their absolute TTL). + pub fn renew(&self, token: &str, sessions: &[SessionRef]) -> Result { + let (mut g, now) = self.authed(token)?; + g.authority.renew(now); + let unknown = g.registry.renew(now, sessions); + Ok(RenewOk { + lease_secs: g.registry.lease().as_secs(), + unknown, + }) + } + + /// `DELETE /v1/sessions/{session}/{generation}`. Idempotent. + pub fn revoke(&self, token: &str, session: &str, generation: u64) -> Result<(), PlaneError> { + let (mut g, now) = self.authed(token)?; + g.registry.revoke(now, session, generation); + Ok(()) + } + + /// `PUT /v1/sessions`: the whole list is validated before anything is + /// applied; sessions not in it are revoked. + pub fn resync( + &self, + token: &str, + policy: &Policy, + reqs: &[RegisterReq], + ) -> Result { + let (mut g, now) = self.authed(token)?; + let mut list = Vec::with_capacity(reqs.len()); + for (i, r) in reqs.iter().enumerate() { + list.push(validate_register(policy, r).map_err(|e| e.at_entry(i))?); + } + let (registered, dropped) = g.registry.resync(now, policy.identity(), list)?; + Ok(ResyncOk { + registered, + dropped, + }) + } + + /// Admission lookup by surrogate hash. + pub fn lookup(&self, hash: &[u8; 32]) -> Result { + let now = self.clock.now(); + let mut g = self.inner.lock().unwrap(); + Self::tick(&mut g, now); + g.registry.lookup(now, hash) + } + + /// Operator action (admin socket): revoke every registered session now and + /// return how many there were. The authority lock is left alone, so a live + /// authority that sees its sessions come back as `unknown` can still + /// re-register them; stopping the authority is what ends them for good. + pub fn revoke_all(&self) -> usize { + let now = self.clock.now(); + let mut g = self.inner.lock().unwrap(); + Self::tick(&mut g, now); + let n = g.registry.len(); + g.registry.revoke_all(); + n + } + + pub fn session_count(&self) -> usize { + let now = self.clock.now(); + let mut g = self.inner.lock().unwrap(); + Self::tick(&mut g, now); + g.registry.len() + } + + pub fn authority_live(&self) -> bool { + let now = self.clock.now(); + let mut g = self.inner.lock().unwrap(); + Self::tick(&mut g, now); + g.authority.is_live(now) + } +} diff --git a/crates/ap-broker/src/registry.rs b/crates/ap-broker/src/registry.rs new file mode 100644 index 0000000..2138285 --- /dev/null +++ b/crates/ap-broker/src/registry.rs @@ -0,0 +1,400 @@ +//! Session registry (Q1-B). Keyed by the sha256 of the surrogate: the proxy +//! never sees a surrogate until a request presents one, and never stores it. +//! +//! All methods take `now` explicitly (time since the clock's origin). The +//! registry has no lock of its own; `SessionPlane` serializes access. + +use crate::error::PlaneError; +use ap_core::{Code, Policy}; +use serde::Deserialize; +use std::collections::{HashMap, HashSet, VecDeque}; +use std::time::Duration; + +/// Per-session lease: 15 minutes from the last renewal. +pub const DEFAULT_SESSION_LEASE_SECS: u64 = 15 * 60; +/// Absolute session TTL: 12 hours from first registration. Renewal never +/// extends past it. +pub const DEFAULT_ABSOLUTE_TTL_SECS: u64 = 12 * 60 * 60; +pub const DEFAULT_MAX_SESSIONS: usize = 256; +const MAX_TOMBSTONES: usize = 1024; + +#[derive(Debug, Clone)] +pub struct RegistryConfig { + pub lease: Duration, + pub absolute_ttl: Duration, + pub max_sessions: usize, +} + +impl Default for RegistryConfig { + fn default() -> Self { + RegistryConfig { + lease: Duration::from_secs(DEFAULT_SESSION_LEASE_SECS), + absolute_ttl: Duration::from_secs(DEFAULT_ABSOLUTE_TTL_SECS), + max_sessions: DEFAULT_MAX_SESSIONS, + } + } +} + +/// `POST /v1/sessions` body, and one element of a `PUT /v1/sessions` list. +#[derive(Deserialize, Debug, Clone)] +#[serde(deny_unknown_fields)] +pub struct RegisterReq { + pub session: String, + pub generation: u64, + pub surrogate_sha256: String, + pub credentials: Vec, +} + +/// One live session, as named in `renew`. +#[derive(Deserialize, serde::Serialize, Debug, Clone, PartialEq, Eq, Hash)] +#[serde(deny_unknown_fields)] +pub struct SessionRef { + pub session: String, + pub generation: u64, +} + +/// A `RegisterReq` that passed field validation and the grant check. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ValidEntry { + pub session: String, + pub generation: u64, + pub hash: [u8; 32], + pub credentials: Vec, +} + +impl ValidEntry { + fn key(&self) -> (String, u64) { + (self.session.clone(), self.generation) + } +} + +fn session_ok(s: &str) -> bool { + !s.is_empty() + && s.len() <= 128 + && s.bytes() + .all(|b| b.is_ascii_alphanumeric() || b"._:-".contains(&b)) +} + +/// Validate one registration against the config. Field problems (400) are +/// reported before grant problems (403), and nothing is changed. +pub fn validate_register(policy: &Policy, req: &RegisterReq) -> Result { + if !session_ok(&req.session) { + return Err(PlaneError::Invalid( + "session must be 1-128 characters of [A-Za-z0-9._:-]".into(), + )); + } + let h = &req.surrogate_sha256; + let mut hash = [0u8; 32]; + let hex_ok = h.len() == 64 + && h.bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) + && hex::decode_to_slice(h, &mut hash).is_ok(); + if !hex_ok { + return Err(PlaneError::Invalid( + "surrogate_sha256 must be 64 lowercase hex characters".into(), + )); + } + if req.credentials.is_empty() || req.credentials.len() > 16 { + return Err(PlaneError::Invalid( + "credentials must list 1 to 16 ids".into(), + )); + } + let mut seen = HashSet::new(); + for c in &req.credentials { + if !seen.insert(c.as_str()) { + return Err(PlaneError::Invalid(format!( + "credential {c:?} listed twice" + ))); + } + } + for c in &req.credentials { + if policy.credential(c).is_none() { + return Err(PlaneError::CredentialNotGranted(format!( + "credential {c:?} is not defined for this identity" + ))); + } + } + Ok(ValidEntry { + session: req.session.clone(), + generation: req.generation, + hash, + credentials: req.credentials.clone(), + }) +} + +#[derive(Debug, Clone)] +struct Entry { + hash: [u8; 32], + credentials: Vec, + identity: String, + lease_expires: Duration, + hard_expires: Duration, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Gone { + Revoked, + Expired, +} + +/// Remembers why a recently dropped surrogate stopped working, so the CLI +/// sees `surrogate_revoked` or `surrogate_expired` instead of `unknown`. +/// Bounded; forgotten entries read as `surrogate_unknown`. +#[derive(Default)] +struct Tombstones { + why: HashMap<[u8; 32], Gone>, + order: VecDeque<[u8; 32]>, +} + +impl Tombstones { + fn add(&mut self, hash: [u8; 32], why: Gone) { + if self.why.insert(hash, why).is_none() { + self.order.push_back(hash); + while self.order.len() > MAX_TOMBSTONES { + if let Some(old) = self.order.pop_front() { + self.why.remove(&old); + } + } + } + } + + fn remove(&mut self, hash: &[u8; 32]) { + self.why.remove(hash); + // `order` keeps a stale slot until it is evicted; harmless. + } +} + +/// What admission needs to know about a live session. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SessionView { + pub session: String, + pub generation: u64, + pub identity: String, + pub credentials: Vec, +} + +pub struct SessionRegistry { + cfg: RegistryConfig, + by_key: HashMap<(String, u64), Entry>, + by_hash: HashMap<[u8; 32], (String, u64)>, + tombs: Tombstones, +} + +impl SessionRegistry { + pub fn new(cfg: RegistryConfig) -> SessionRegistry { + SessionRegistry { + cfg, + by_key: HashMap::new(), + by_hash: HashMap::new(), + tombs: Tombstones::default(), + } + } + + pub fn lease(&self) -> Duration { + self.cfg.lease + } + + pub fn len(&self) -> usize { + self.by_key.len() + } + + pub fn is_empty(&self) -> bool { + self.by_key.is_empty() + } + + fn drop_key(&mut self, key: &(String, u64), why: Gone) -> bool { + match self.by_key.remove(key) { + Some(e) => { + self.by_hash.remove(&e.hash); + self.tombs.add(e.hash, why); + true + } + None => false, + } + } + + fn lease_until(&self, now: Duration, hard: Duration) -> Duration { + (now + self.cfg.lease).min(hard) + } + + /// Remove sessions whose lease has lapsed or whose absolute TTL is reached. + pub fn sweep(&mut self, now: Duration) { + let dead: Vec<_> = self + .by_key + .iter() + .filter(|(_, e)| now >= e.lease_expires || now >= e.hard_expires) + .map(|(k, _)| k.clone()) + .collect(); + for k in dead { + self.drop_key(&k, Gone::Expired); + } + } + + /// Revoke everything (the authority's lease lapsed). + pub fn revoke_all(&mut self) { + let keys: Vec<_> = self.by_key.keys().cloned().collect(); + for k in keys { + self.drop_key(&k, Gone::Revoked); + } + } + + /// `POST /v1/sessions`. Returns the session lease. + pub fn register( + &mut self, + now: Duration, + identity: &str, + v: ValidEntry, + ) -> Result { + self.sweep(now); + let key = v.key(); + if let Some(e) = self.by_key.get(&key) { + if e.hash != v.hash || e.credentials != v.credentials { + return Err(PlaneError::Conflict( + "session and generation are already registered with another binding".into(), + )); + } + // Idempotent retry: an explicit re-registration renews the lease, + // capped by the original absolute TTL. + let until = self.lease_until(now, e.hard_expires); + self.by_key.get_mut(&key).unwrap().lease_expires = until; + return Ok(self.cfg.lease); + } + if self.by_hash.contains_key(&v.hash) { + return Err(PlaneError::Conflict( + "surrogate hash is already bound to another session".into(), + )); + } + if self.by_key.len() >= self.cfg.max_sessions { + return Err(PlaneError::TooManySessions); + } + let hard = now + self.cfg.absolute_ttl; + self.tombs.remove(&v.hash); + self.by_hash.insert(v.hash, key.clone()); + self.by_key.insert( + key, + Entry { + hash: v.hash, + credentials: v.credentials, + identity: identity.to_string(), + lease_expires: self.lease_until(now, hard), + hard_expires: hard, + }, + ); + Ok(self.cfg.lease) + } + + /// `POST /v1/renew` for sessions. Returns the refs that are not registered + /// (never registered, revoked, lapsed, or past their absolute TTL). + pub fn renew(&mut self, now: Duration, refs: &[SessionRef]) -> Vec { + self.sweep(now); + let mut unknown = Vec::new(); + for r in refs { + let key = (r.session.clone(), r.generation); + match self.by_key.get(&key) { + Some(e) => { + let until = self.lease_until(now, e.hard_expires); + self.by_key.get_mut(&key).unwrap().lease_expires = until; + } + None => unknown.push(r.clone()), + } + } + unknown + } + + /// `DELETE`. Idempotent: returns whether the session existed. + pub fn revoke(&mut self, now: Duration, session: &str, generation: u64) -> bool { + self.sweep(now); + self.drop_key(&(session.to_string(), generation), Gone::Revoked) + } + + /// `PUT /v1/sessions`: the list is the whole truth. Validates all of it + /// before applying anything; on error nothing changes. Returns + /// `(registered, dropped)`. + pub fn resync( + &mut self, + now: Duration, + identity: &str, + list: Vec, + ) -> Result<(usize, usize), PlaneError> { + self.sweep(now); + if list.len() > self.cfg.max_sessions { + return Err(PlaneError::TooManySessions); + } + let mut keys = HashSet::new(); + let mut hashes = HashSet::new(); + for (i, v) in list.iter().enumerate() { + if !keys.insert(v.key()) { + return Err( + PlaneError::Invalid("session and generation listed twice".into()).at_entry(i), + ); + } + if !hashes.insert(v.hash) { + return Err(PlaneError::Conflict("surrogate hash listed twice".into()).at_entry(i)); + } + if let Some(e) = self.by_key.get(&v.key()) { + if e.hash != v.hash || e.credentials != v.credentials { + return Err(PlaneError::Conflict( + "session and generation are already registered with another binding".into(), + ) + .at_entry(i)); + } + } + } + // Everything validated: apply. + let stale: Vec<_> = self + .by_key + .keys() + .filter(|k| !keys.contains(*k)) + .cloned() + .collect(); + let dropped = stale.len(); + for k in stale { + self.drop_key(&k, Gone::Revoked); + } + for v in &list { + let key = v.key(); + if let Some(e) = self.by_key.get(&key) { + let until = self.lease_until(now, e.hard_expires); + self.by_key.get_mut(&key).unwrap().lease_expires = until; + } else { + let hard = now + self.cfg.absolute_ttl; + self.tombs.remove(&v.hash); + self.by_hash.insert(v.hash, key.clone()); + self.by_key.insert( + key, + Entry { + hash: v.hash, + credentials: v.credentials.clone(), + identity: identity.to_string(), + lease_expires: self.lease_until(now, hard), + hard_expires: hard, + }, + ); + } + } + Ok((list.len(), dropped)) + } + + /// Admission lookup by surrogate hash. A lapsed or past-TTL session is + /// removed here too, so a request never rides on a stale lease. + pub fn lookup(&mut self, now: Duration, hash: &[u8; 32]) -> Result { + self.sweep(now); + match self + .by_hash + .get(hash) + .and_then(|k| self.by_key.get(k).map(|e| (k, e))) + { + Some((k, e)) => Ok(SessionView { + session: k.0.clone(), + generation: k.1, + identity: e.identity.clone(), + credentials: e.credentials.clone(), + }), + None => Err(match self.tombs.why.get(hash) { + Some(Gone::Revoked) => Code::SurrogateRevoked, + Some(Gone::Expired) => Code::SurrogateExpired, + None => Code::SurrogateUnknown, + }), + } + } +} diff --git a/crates/ap-broker/src/store.rs b/crates/ap-broker/src/store.rs new file mode 100644 index 0000000..87ec83a --- /dev/null +++ b/crates/ap-broker/src/store.rs @@ -0,0 +1,129 @@ +//! Credential values and the S1 file store. +//! +//! `Secret` is the only type in the workspace that holds a credential value. +//! It has no `Debug`, no `Display`, no `Clone` and no `Serialize`; it zeroizes +//! its bytes on drop. + +use ap_core::{CredentialSource, FileStamp}; +use std::collections::HashMap; +use std::io::Read; +use std::path::PathBuf; +use std::sync::{Arc, Mutex}; +use zeroize::Zeroizing; + +const MAX_SECRET_BYTES: u64 = 64 * 1024; + +pub struct Secret(Zeroizing>); + +impl Secret { + pub fn new(bytes: Vec) -> Secret { + Secret(Zeroizing::new(bytes)) + } + + /// The raw value. Callers put it in one header and nowhere else. + pub fn expose(&self) -> &[u8] { + &self.0 + } +} + +/// Why a credential could not be read. Carries no value and no path. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum StoreError { + /// Missing, unreadable, too large or empty. + Unavailable(&'static str), + /// The source kind is not resolved by this store (`env:` in Phase 1). + Unsupported, +} + +pub trait Store: Send + Sync { + fn resolve(&self, source: &CredentialSource) -> Result, StoreError>; +} + +/// S1: reads Secret files. `k8s::` maps to +/// `//` (each Secret mounted at +/// `/`, only into the proxy container); `file:` is +/// read as is. Every request stats the file and re-reads it when its mtime, +/// size or inode changed, so kubelet's atomic symlink swap is picked up with no +/// restart. A failed stat or read drops the cached value: nothing is served +/// from memory once the file is gone. +pub struct FileStore { + secrets_dir: PathBuf, + cache: Mutex)>>, +} + +impl FileStore { + pub fn new(secrets_dir: impl Into) -> FileStore { + FileStore { + secrets_dir: secrets_dir.into(), + cache: Mutex::new(HashMap::new()), + } + } + + /// Startup check: every source in the policy is one this store resolves. + pub fn supports(source: &CredentialSource) -> bool { + !matches!(source, CredentialSource::Env(_)) + } + + fn path_of(&self, source: &CredentialSource) -> Result { + match source { + CredentialSource::K8s { secret, key } => Ok(self.secrets_dir.join(secret).join(key)), + CredentialSource::File(p) => Ok(p.clone()), + CredentialSource::Env(_) => Err(StoreError::Unsupported), + } + } +} + +impl Store for FileStore { + fn resolve(&self, source: &CredentialSource) -> Result, StoreError> { + let path = self.path_of(source)?; + let mut cache = self.cache.lock().unwrap(); + let mut file = match std::fs::File::open(&path) { + Ok(f) => f, + Err(_) => { + cache.remove(&path); + return Err(StoreError::Unavailable( + "credential file missing or unreadable", + )); + } + }; + // Stat the open handle so the stamp describes the bytes we read. + let stamp = match file.metadata() { + Ok(md) => FileStamp::of(&md), + Err(_) => { + cache.remove(&path); + return Err(StoreError::Unavailable( + "credential file cannot be inspected", + )); + } + }; + if let Some((s, v)) = cache.get(&path) { + if *s == stamp { + return Ok(v.clone()); + } + } + let mut buf = Zeroizing::new(Vec::new()); + if (&mut file) + .take(MAX_SECRET_BYTES + 1) + .read_to_end(&mut buf) + .is_err() + { + cache.remove(&path); + return Err(StoreError::Unavailable("credential file unreadable")); + } + if buf.len() as u64 > MAX_SECRET_BYTES { + cache.remove(&path); + return Err(StoreError::Unavailable("credential file too large")); + } + // `echo value > file` leaves a newline; no credential ends in one. + while matches!(buf.last(), Some(b'\n' | b'\r')) { + buf.pop(); + } + if buf.is_empty() { + cache.remove(&path); + return Err(StoreError::Unavailable("credential file empty")); + } + let secret = Arc::new(Secret::new(std::mem::take(&mut *buf))); + cache.insert(path, (stamp, secret.clone())); + Ok(secret) + } +} diff --git a/crates/ap-broker/tests/plane.rs b/crates/ap-broker/tests/plane.rs new file mode 100644 index 0000000..16843fb --- /dev/null +++ b/crates/ap-broker/tests/plane.rs @@ -0,0 +1,807 @@ +//! Session registry and authority lock, driven by a fake clock. + +mod support; + +use ap_broker::{ + PlaneConfig, PlaneError, RegisterReq, RegistryConfig, AUTHORITY_RENEW_SECS, + DEFAULT_ABSOLUTE_TTL_SECS, DEFAULT_AUTHORITY_LEASE_SECS, DEFAULT_SESSION_LEASE_SECS, +}; +use ap_core::Code; +use std::time::Duration; +use support::*; + +#[test] +fn pinned_defaults() { + assert_eq!(DEFAULT_AUTHORITY_LEASE_SECS, 90); + assert_eq!(AUTHORITY_RENEW_SECS, 30); + assert_eq!(DEFAULT_SESSION_LEASE_SECS, 15 * 60); + assert_eq!(DEFAULT_ABSOLUTE_TTL_SECS, 12 * 60 * 60); + let c = PlaneConfig::default(); + assert_eq!(c.authority_lease_secs, 90); + assert_eq!(c.registry.lease, Duration::from_secs(900)); + assert_eq!(c.registry.absolute_ttl, Duration::from_secs(43_200)); + let (_, p) = plane(); + let h = p.hello().unwrap(); + assert_eq!(h.lease_secs, 90); + assert_eq!( + p.register(&h.authority_token, &policy(), &req("s", 1, 1, &["kiro"])) + .unwrap() + .lease_secs, + 900 + ); +} + +#[test] +fn authority_lease_below_minimum_is_refused() { + for secs in [0, 1, 2] { + let cfg = PlaneConfig { + authority_lease_secs: secs, + ..Default::default() + }; + assert!(ap_broker::SessionPlane::new( + cfg, + std::sync::Arc::new(ap_broker::FakeClock::new()) + ) + .is_err()); + } + let cfg = PlaneConfig { + authority_lease_secs: 3, + ..Default::default() + }; + assert!( + ap_broker::SessionPlane::new(cfg, std::sync::Arc::new(ap_broker::FakeClock::new())).is_ok() + ); +} + +// ---------------------------------------------------------------- leases + +#[test] +fn session_lease_is_15_minutes_from_registration() { + let (clock, p) = plane(); + let tok = p.hello().unwrap().authority_token; + p.register(&tok, &policy(), &req("s1", 1, 1, &["kiro"])) + .unwrap(); + advance_renewing_authority(&clock, &p, &tok, 899); + assert!(p.lookup(&hash(1)).is_ok(), "alive at 899 s"); + advance_renewing_authority(&clock, &p, &tok, 1); + assert_eq!( + p.lookup(&hash(1)), + Err(Code::SurrogateExpired), + "lapsed at 900 s" + ); + assert_eq!(p.session_count(), 0); +} + +#[test] +fn renew_restarts_the_15_minute_lease() { + let (clock, p) = plane(); + let tok = p.hello().unwrap().authority_token; + p.register(&tok, &policy(), &req("s1", 1, 1, &["kiro"])) + .unwrap(); + advance_renewing_authority(&clock, &p, &tok, 600); + let r = p.renew(&tok, &[sref("s1", 1)]).unwrap(); + assert_eq!(r.lease_secs, 900); + assert!(r.unknown.is_empty()); + advance_renewing_authority(&clock, &p, &tok, 899); + assert!( + p.lookup(&hash(1)).is_ok(), + "600 + 899 s: renewed lease still holds" + ); + advance_renewing_authority(&clock, &p, &tok, 1); + assert_eq!(p.lookup(&hash(1)), Err(Code::SurrogateExpired)); +} + +#[test] +fn use_does_not_extend_a_lease() { + let (clock, p) = plane(); + let tok = p.hello().unwrap().authority_token; + p.register(&tok, &policy(), &req("s1", 1, 1, &["kiro"])) + .unwrap(); + for _ in 0..29 { + advance_renewing_authority(&clock, &p, &tok, 30); + let _ = p.lookup(&hash(1)); + } + // 870 s of lookups so far; a lookup never renews + advance_renewing_authority(&clock, &p, &tok, 30); + assert_eq!(p.lookup(&hash(1)), Err(Code::SurrogateExpired)); +} + +#[test] +fn renew_cannot_extend_past_the_absolute_ttl() { + let (clock, p) = plane(); + let tok = p.hello().unwrap().authority_token; + p.register(&tok, &policy(), &req("s1", 1, 1, &["kiro"])) + .unwrap(); + let sessions = [sref("s1", 1)]; + // renew every 30 s for 12 h minus 30 s + let mut t = 0; + while t < DEFAULT_ABSOLUTE_TTL_SECS - 30 { + clock.advance_secs(30); + t += 30; + let r = p.renew(&tok, &sessions).unwrap(); + assert!(r.unknown.is_empty(), "t={t}"); + } + assert!(p.lookup(&hash(1)).is_ok()); + // this renew would reach 43170 + 900 s without the cap + clock.advance_secs(29); + let r = p.renew(&tok, &sessions).unwrap(); + assert!(r.unknown.is_empty()); + assert!( + p.lookup(&hash(1)).is_ok(), + "alive one second before the TTL" + ); + clock.advance_secs(1); + assert_eq!( + p.lookup(&hash(1)), + Err(Code::SurrogateExpired), + "dead at exactly 12 h" + ); + let r = p.renew(&tok, &sessions).unwrap(); + assert_eq!(r.unknown, vec![sref("s1", 1)], "renew reports it unknown"); +} + +#[test] +fn configurable_ttl_and_lease() { + let cfg = PlaneConfig { + registry: RegistryConfig { + lease: Duration::from_secs(60), + absolute_ttl: Duration::from_secs(100), + max_sessions: 8, + }, + authority_lease_secs: 90, + authority_state: None, + }; + let (clock, p) = plane_with(cfg); + let tok = p.hello().unwrap().authority_token; + assert_eq!( + p.register(&tok, &policy(), &req("s", 1, 1, &["kiro"])) + .unwrap() + .lease_secs, + 60 + ); + clock.advance_secs(50); + p.renew(&tok, &[sref("s", 1)]).unwrap(); // lease would end at 110, TTL caps at 100 + clock.advance_secs(49); + assert!(p.lookup(&hash(1)).is_ok()); + clock.advance_secs(1); + assert_eq!(p.lookup(&hash(1)), Err(Code::SurrogateExpired)); +} + +// ---------------------------------------------------------------- registration + +#[test] +fn register_validation_rejects_and_changes_nothing() { + let (_, p) = plane(); + let tok = p.hello().unwrap().authority_token; + let pol = policy(); + let good = req("s1", 1, 1, &["kiro"]); + let bad_hash = |h: &str| RegisterReq { + surrogate_sha256: h.into(), + ..good.clone() + }; + let upper = hex::encode(hash(1)).to_uppercase(); + let cases: Vec<(&str, RegisterReq, u16, &str)> = vec![ + ( + "empty session", + RegisterReq { + session: "".into(), + ..good.clone() + }, + 400, + "invalid_request", + ), + ( + "session too long", + RegisterReq { + session: "a".repeat(129), + ..good.clone() + }, + 400, + "invalid_request", + ), + ( + "session bad char", + RegisterReq { + session: "a b".into(), + ..good.clone() + }, + 400, + "invalid_request", + ), + ( + "session slash", + RegisterReq { + session: "a/b".into(), + ..good.clone() + }, + 400, + "invalid_request", + ), + ( + "hash short", + bad_hash(&"a".repeat(63)), + 400, + "invalid_request", + ), + ( + "hash long", + bad_hash(&"a".repeat(65)), + 400, + "invalid_request", + ), + ("hash upper", bad_hash(&upper), 400, "invalid_request"), + ( + "hash non-hex", + bad_hash(&"g".repeat(64)), + 400, + "invalid_request", + ), + ( + "no credentials", + RegisterReq { + credentials: vec![], + ..good.clone() + }, + 400, + "invalid_request", + ), + ( + "17 credentials", + RegisterReq { + credentials: (0..17).map(|i| format!("c{i}")).collect(), + ..good.clone() + }, + 400, + "invalid_request", + ), + ( + "duplicate credential", + RegisterReq { + credentials: vec!["kiro".into(), "kiro".into()], + ..good.clone() + }, + 400, + "invalid_request", + ), + ( + "credential not granted", + RegisterReq { + credentials: vec!["ghost".into()], + ..good.clone() + }, + 403, + "credential_not_granted", + ), + ( + "one granted one not", + RegisterReq { + credentials: vec!["kiro".into(), "ghost".into()], + ..good.clone() + }, + 403, + "credential_not_granted", + ), + ]; + for (label, r, status, code) in cases { + let e = p.register(&tok, &pol, &r).expect_err(label); + assert_eq!((e.status(), e.code()), (status, code), "{label}: {e}"); + } + assert_eq!(p.session_count(), 0); + // boundaries that are valid + p.register( + &tok, + &pol, + &RegisterReq { + session: "A.b_c:d-e".repeat(10), + generation: u64::MAX, + ..good.clone() + }, + ) + .unwrap(); + let both: Vec = ["kiro", "anthropic"] + .iter() + .map(|s| s.to_string()) + .collect(); + p.register( + &tok, + &pol, + &RegisterReq { + session: "two".into(), + generation: 0, + credentials: both, + ..req("x", 0, 2, &[]) + }, + ) + .unwrap(); +} + +#[test] +fn register_conflicts_and_idempotence() { + let (_, p) = plane(); + let tok = p.hello().unwrap().authority_token; + let pol = policy(); + p.register(&tok, &pol, &req("s1", 1, 1, &["kiro"])).unwrap(); + // identical retry is fine + assert!(p.register(&tok, &pol, &req("s1", 1, 1, &["kiro"])).is_ok()); + // same session+generation, other hash + let e = p + .register(&tok, &pol, &req("s1", 1, 2, &["kiro"])) + .unwrap_err(); + assert_eq!((e.status(), e.code()), (409, "session_conflict")); + // same session+generation, other credentials + let e = p + .register(&tok, &pol, &req("s1", 1, 1, &["anthropic"])) + .unwrap_err(); + assert_eq!(e.status(), 409); + // same hash under another session + let e = p + .register(&tok, &pol, &req("s2", 1, 1, &["kiro"])) + .unwrap_err(); + assert_eq!(e.status(), 409); + // new generation of the same session with its own hash coexists + p.register(&tok, &pol, &req("s1", 2, 3, &["kiro"])).unwrap(); + assert_eq!(p.session_count(), 2); +} + +#[test] +fn max_sessions_gives_429_and_frees_on_revoke() { + let cfg = PlaneConfig { + registry: RegistryConfig { + max_sessions: 2, + ..Default::default() + }, + ..Default::default() + }; + let (_, p) = plane_with(cfg); + let tok = p.hello().unwrap().authority_token; + let pol = policy(); + p.register(&tok, &pol, &req("a", 1, 1, &["kiro"])).unwrap(); + p.register(&tok, &pol, &req("b", 1, 2, &["kiro"])).unwrap(); + let e = p + .register(&tok, &pol, &req("c", 1, 3, &["kiro"])) + .unwrap_err(); + assert_eq!((e.status(), e.code()), (429, "too_many_sessions")); + // an idempotent retry of an existing one is not over the limit + p.register(&tok, &pol, &req("b", 1, 2, &["kiro"])).unwrap(); + p.revoke(&tok, "a", 1).unwrap(); + p.register(&tok, &pol, &req("c", 1, 3, &["kiro"])).unwrap(); +} + +#[test] +fn revoke_is_synchronous_and_idempotent() { + let (_, p) = plane(); + let tok = p.hello().unwrap().authority_token; + p.register(&tok, &policy(), &req("s1", 1, 1, &["kiro"])) + .unwrap(); + assert!(p.lookup(&hash(1)).is_ok()); + p.revoke(&tok, "s1", 1).unwrap(); + assert_eq!(p.lookup(&hash(1)), Err(Code::SurrogateRevoked)); + p.revoke(&tok, "s1", 1).unwrap(); + p.revoke(&tok, "never-existed", 9).unwrap(); + assert_eq!(p.lookup(&hash(77)), Err(Code::SurrogateUnknown)); + // re-registering the same hash clears the revoked memory + p.register(&tok, &policy(), &req("s1", 2, 1, &["kiro"])) + .unwrap(); + assert!(p.lookup(&hash(1)).is_ok()); +} + +#[test] +fn every_call_needs_the_token() { + let (_, p) = plane(); + let tok = p.hello().unwrap().authority_token; + let pol = policy(); + for bad in [ + "", + "apt_", + "garbage", + &format!("{tok}x"), + &tok[..tok.len() - 1], + ] { + assert_eq!( + p.register(bad, &pol, &req("s", 1, 1, &["kiro"])), + Err(PlaneError::Unauthorized) + ); + assert_eq!(p.renew(bad, &[]), Err(PlaneError::Unauthorized)); + assert_eq!(p.revoke(bad, "s", 1), Err(PlaneError::Unauthorized)); + assert_eq!(p.resync(bad, &pol, &[]), Err(PlaneError::Unauthorized)); + } + assert_eq!(p.session_count(), 0); +} + +// ---------------------------------------------------------------- resync + +#[test] +fn resync_validates_the_whole_list_before_applying() { + let (_, p) = plane(); + let tok = p.hello().unwrap().authority_token; + let pol = policy(); + p.register(&tok, &pol, &req("old", 1, 9, &["kiro"])) + .unwrap(); + let list = vec![ + req("new1", 1, 1, &["kiro"]), + req("new2", 1, 2, &["ghost"]), // not granted + ]; + let e = p.resync(&tok, &pol, &list).unwrap_err(); + assert_eq!(e.status(), 403); + assert!( + e.to_string().contains("entry 1"), + "says which entry failed: {e}" + ); + assert_eq!(p.session_count(), 1, "nothing applied"); + assert!(p.lookup(&hash(9)).is_ok(), "old session untouched"); + assert_eq!( + p.lookup(&hash(1)), + Err(Code::SurrogateUnknown), + "good entry not registered" + ); + + for (label, list, status) in [ + ( + "duplicate key", + vec![req("a", 1, 1, &["kiro"]), req("a", 1, 2, &["kiro"])], + 400, + ), + ( + "duplicate hash", + vec![req("a", 1, 1, &["kiro"]), req("b", 1, 1, &["kiro"])], + 409, + ), + ( + "bad hash", + vec![RegisterReq { + surrogate_sha256: "zz".into(), + ..req("a", 1, 1, &["kiro"]) + }], + 400, + ), + ( + "rebinds existing key", + vec![req("old", 1, 5, &["kiro"])], + 409, + ), + ] { + let e = p.resync(&tok, &pol, &list).expect_err(label); + assert_eq!(e.status(), status, "{label}: {e}"); + assert!(p.lookup(&hash(9)).is_ok(), "{label}: nothing applied"); + } +} + +#[test] +fn resync_registers_drops_and_reports() { + let (_, p) = plane(); + let tok = p.hello().unwrap().authority_token; + let pol = policy(); + p.register(&tok, &pol, &req("keep", 1, 1, &["kiro"])) + .unwrap(); + p.register(&tok, &pol, &req("drop", 1, 2, &["kiro"])) + .unwrap(); + let r = p + .resync( + &tok, + &pol, + &[ + req("keep", 1, 1, &["kiro"]), + req("fresh", 1, 3, &["anthropic"]), + ], + ) + .unwrap(); + assert_eq!((r.registered, r.dropped), (2, 1)); + assert!(p.lookup(&hash(1)).is_ok()); + assert!(p.lookup(&hash(3)).is_ok()); + assert_eq!( + p.lookup(&hash(2)), + Err(Code::SurrogateRevoked), + "dropped sessions stay dropped" + ); + let r = p.resync(&tok, &pol, &[]).unwrap(); + assert_eq!((r.registered, r.dropped), (0, 2)); + assert_eq!(p.session_count(), 0); +} + +#[test] +fn resync_keeps_the_original_absolute_ttl() { + let (clock, p) = plane(); + let tok = p.hello().unwrap().authority_token; + let pol = policy(); + p.register(&tok, &pol, &req("s", 1, 1, &["kiro"])).unwrap(); + advance_renewing(&clock, &p, &tok, 43_000, &[sref("s", 1)]); + p.resync(&tok, &pol, &[req("s", 1, 1, &["kiro"])]).unwrap(); + advance_renewing_authority(&clock, &p, &tok, 199); + assert!(p.lookup(&hash(1)).is_ok()); + advance_renewing_authority(&clock, &p, &tok, 1); + assert_eq!( + p.lookup(&hash(1)), + Err(Code::SurrogateExpired), + "resync does not restart the 12 h" + ); +} + +#[test] +fn proxy_restart_then_resync_restores_the_same_surrogates() { + let dir = tmpdir("restart"); + let state = dir.join("authority.json"); + let cfg = || PlaneConfig { + authority_state: Some(state.clone()), + ..Default::default() + }; + let pol = policy(); + let (clock1, p1) = plane_with(cfg()); + let tok = p1.hello().unwrap().authority_token; + p1.register(&tok, &pol, &req("a", 1, 1, &["kiro"])).unwrap(); + p1.register(&tok, &pol, &req("b", 1, 2, &["anthropic"])) + .unwrap(); + clock1.advance_secs(20); + drop(p1); // proxy restarts: registry is memory only + + let (_clock2, p2) = plane_with(cfg()); + assert_eq!( + p2.lookup(&hash(1)), + Err(Code::SurrogateUnknown), + "gap: refused" + ); + // the authority's next renew lists everything as unknown + let r = p2.renew(&tok, &[sref("a", 1), sref("b", 1)]).unwrap(); + assert_eq!(r.unknown.len(), 2); + // it re-sends the live sessions it still has (only "a") + let r = p2.resync(&tok, &pol, &[req("a", 1, 1, &["kiro"])]).unwrap(); + assert_eq!((r.registered, r.dropped), (1, 0)); + assert!(p2.lookup(&hash(1)).is_ok(), "same surrogate works again"); + assert_eq!( + p2.lookup(&hash(2)), + Err(Code::SurrogateUnknown), + "dropped session stays dropped" + ); + let _ = std::fs::remove_dir_all(&dir); +} + +// ---------------------------------------------------------------- hello lock + +#[test] +fn hello_409_while_live_then_lapse_revokes_everything_and_next_hello_wins() { + let (clock, p) = plane(); + let pol = policy(); + let a = p.hello().unwrap(); + assert_eq!(a.lease_secs, 90); + assert!(a.authority_token.starts_with("apt_") && a.authority_token.len() == 68); + p.register(&a.authority_token, &pol, &req("s1", 1, 1, &["kiro"])) + .unwrap(); + + // renewed every 30 s: the lock stays held for as long as it is renewed + for _ in 0..10 { + clock.advance_secs(30); + p.renew(&a.authority_token, &[sref("s1", 1)]).unwrap(); + assert_eq!(p.hello(), Err(PlaneError::AuthorityActive)); + } + // the authority dies: 89 s of silence + clock.advance_secs(89); + assert_eq!( + p.hello(), + Err(PlaneError::AuthorityActive), + "lock holds until the lease ends" + ); + assert!(p.lookup(&hash(1)).is_ok(), "sessions still work until then"); + assert!(p.authority_live()); + // 90 s + clock.advance_secs(1); + assert!(!p.authority_live()); + assert_eq!( + p.lookup(&hash(1)), + Err(Code::SurrogateRevoked), + "lapse revokes the authority's sessions" + ); + assert_eq!(p.session_count(), 0); + // the old token is dead + assert_eq!( + p.renew(&a.authority_token, &[]), + Err(PlaneError::Unauthorized) + ); + assert_eq!( + p.register(&a.authority_token, &pol, &req("s2", 1, 2, &["kiro"])), + Err(PlaneError::Unauthorized) + ); + // exactly one hello wins + let b = p.hello().unwrap(); + assert_ne!(a.authority_token, b.authority_token); + assert_eq!( + p.hello(), + Err(PlaneError::AuthorityActive), + "a concurrent second hello gets 409" + ); + // stale token after a new hello is 401, the new one works + assert_eq!( + p.renew(&a.authority_token, &[]), + Err(PlaneError::Unauthorized) + ); + p.register(&b.authority_token, &pol, &req("s3", 1, 3, &["kiro"])) + .unwrap(); +} + +#[test] +fn restarted_runtime_retries_with_backoff_and_wins_only_after_the_lease() { + let (clock, p) = plane(); + let a = p.hello().unwrap(); + p.renew(&a.authority_token, &[]).unwrap(); + // container dies at t=0 (last renew). The fresh PID 1 retries every 10 s. + let mut won_at = None; + for attempt in 1..=12u64 { + clock.advance_secs(10); + match p.hello() { + Ok(_) => { + won_at = Some(attempt * 10); + break; + } + Err(e) => assert_eq!(e, PlaneError::AuthorityActive, "t={}", attempt * 10), + } + } + assert_eq!( + won_at, + Some(90), + "first attempt at or after the 90 s lease wins" + ); +} + +#[test] +fn hello_wins_exactly_once_under_concurrency() { + use std::sync::Arc; + let (clock, p) = plane(); + let p = Arc::new(p); + let a = p.hello().unwrap(); + clock.advance_secs(90); + let _ = a; + let handles: Vec<_> = (0..16) + .map(|_| { + let p = p.clone(); + std::thread::spawn(move || p.hello().is_ok()) + }) + .collect(); + let wins = handles + .into_iter() + .map(|h| h.join().unwrap()) + .filter(|w| *w) + .count(); + assert_eq!(wins, 1); +} + +#[test] +fn authority_lock_survives_a_proxy_restart_for_one_lease() { + let dir = tmpdir("lock"); + let state = dir.join("authority.json"); + let cfg = || PlaneConfig { + authority_state: Some(state.clone()), + ..Default::default() + }; + let pol = policy(); + let (_c1, p1) = plane_with(cfg()); + let a = p1.hello().unwrap(); + drop(p1); + + // the file holds the hash and nothing secret + let text = std::fs::read_to_string(&state).unwrap(); + assert!(!text.contains(&a.authority_token), "token never written"); + assert!(!text.contains("apt_")); + assert!(text.contains("token_sha256")); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + assert_eq!( + std::fs::metadata(&state).unwrap().permissions().mode() & 0o777, + 0o600 + ); + } + + // restart: the lock is live for one full lease from now, the token still works + let (c2, p2) = plane_with(cfg()); + assert!(p2.authority_live()); + assert_eq!(p2.hello(), Err(PlaneError::AuthorityActive)); + p2.register(&a.authority_token, &pol, &req("s", 1, 1, &["kiro"])) + .unwrap(); + c2.advance_secs(89); + assert_eq!(p2.hello(), Err(PlaneError::AuthorityActive)); + // a renew after the restart extends it by a full lease again + p2.renew(&a.authority_token, &[sref("s", 1)]).unwrap(); + c2.advance_secs(89); + assert_eq!(p2.hello(), Err(PlaneError::AuthorityActive)); + // silence for the rest of a lease frees it + c2.advance_secs(1); + assert!(!p2.authority_live()); + assert_eq!(p2.lookup(&hash(1)), Err(Code::SurrogateRevoked)); + let b = p2.hello().unwrap(); + assert_eq!( + p2.renew(&a.authority_token, &[]), + Err(PlaneError::Unauthorized) + ); + assert!(p2.renew(&b.authority_token, &[]).is_ok()); + + // a restart after a lapse finds no lock: the state file was cleared on + // the lapse, then rewritten for b; drop b's lease and restart again + drop(p2); + let (c3, p3) = plane_with(cfg()); + c3.advance_secs(90); + assert!(!p3.authority_live()); + p3.hello().unwrap(); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn lapse_clears_the_state_file() { + let dir = tmpdir("clear"); + let state = dir.join("authority.json"); + let (clock, p) = plane_with(PlaneConfig { + authority_state: Some(state.clone()), + ..Default::default() + }); + p.hello().unwrap(); + assert!(state.exists()); + clock.advance_secs(90); + assert!(!p.authority_live()); + assert!(!state.exists(), "no stale hash left behind after a lapse"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn unwritable_state_means_no_lock_is_taken() { + let dir = tmpdir("nowrite"); + let (_, p) = plane_with(PlaneConfig { + authority_state: Some(dir.join("missing-dir").join("authority.json")), + ..Default::default() + }); + for _ in 0..2 { + let e = p.hello().unwrap_err(); + assert_eq!(e.status(), 500, "{e}"); + } + assert!(!p.authority_live()); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn corrupt_state_file_starts_with_no_lock() { + let dir = tmpdir("corrupt"); + let state = dir.join("authority.json"); + for junk in [ + "", + "not json", + "{\"version\":2,\"token_sha256\":\"00\"}", + "{\"version\":1,\"token_sha256\":\"zz\"}", + ] { + std::fs::write(&state, junk).unwrap(); + let (_, p) = plane_with(PlaneConfig { + authority_state: Some(state.clone()), + ..Default::default() + }); + assert!(!p.authority_live(), "{junk:?}"); + p.hello().unwrap(); + } + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn authority_lease_is_configurable_for_tests_only_down_to_3_s() { + let (clock, p) = plane_with(PlaneConfig { + authority_lease_secs: 3, + ..Default::default() + }); + let a = p.hello().unwrap(); + assert_eq!(a.lease_secs, 3); + clock.advance_secs(2); + assert_eq!(p.hello(), Err(PlaneError::AuthorityActive)); + clock.advance_secs(1); + assert!(p.hello().is_ok()); +} + +#[test] +fn revoke_all_drops_every_session_and_keeps_the_authority() { + let (_, p) = plane(); + let tok = p.hello().unwrap().authority_token; + p.register(&tok, &policy(), &req("a", 1, 1, &["kiro"])) + .unwrap(); + p.register(&tok, &policy(), &req("b", 1, 2, &["kiro"])) + .unwrap(); + assert_eq!(p.revoke_all(), 2); + assert_eq!(p.session_count(), 0); + assert_eq!(p.lookup(&hash(1)), Err(Code::SurrogateRevoked)); + assert!(p.authority_live(), "revoke_all must not free the lock"); + assert_eq!(p.revoke_all(), 0); + // The live authority can register again. + p.register(&tok, &policy(), &req("a", 1, 1, &["kiro"])) + .unwrap(); +} diff --git a/crates/ap-broker/tests/store.rs b/crates/ap-broker/tests/store.rs new file mode 100644 index 0000000..7ce2857 --- /dev/null +++ b/crates/ap-broker/tests/store.rs @@ -0,0 +1,364 @@ +//! S1 file store, the Broker admission rules, and the "no Debug for secrets" +//! guarantees. + +mod support; + +use ap_broker::{ + Binding, Broker, FileStore, HelloOk, LocalBroker, PlaneConfig, Secret, SessionPlane, Store, + StoreError, +}; +use ap_core::{Code, CredentialSource}; +use std::fmt::{Debug, Display}; +use std::fs; +use std::marker::PhantomData; +use std::path::Path; +use std::sync::Arc; +use std::time::{Duration, SystemTime}; +use support::*; + +fn k8s(secret: &str, key: &str) -> CredentialSource { + CredentialSource::K8s { + secret: secret.into(), + key: key.into(), + } +} + +fn write_at(path: &Path, content: &str, n: u64) { + fs::write(path, content).unwrap(); + fs::OpenOptions::new() + .write(true) + .open(path) + .unwrap() + .set_modified(SystemTime::UNIX_EPOCH + Duration::from_secs(1_700_000_000 + n)) + .unwrap(); +} + +fn value(s: &Arc) -> String { + String::from_utf8(s.expose().to_vec()).unwrap() +} + +#[test] +fn reads_and_trims_the_trailing_newline() { + let d = tmpdir("read"); + fs::create_dir_all(d.join("auth-proxy-kiro")).unwrap(); + write_at(&d.join("auth-proxy-kiro/api_key"), "sk-test-1\n", 1); + let st = FileStore::new(&d); + assert_eq!( + value(&st.resolve(&k8s("auth-proxy-kiro", "api_key")).unwrap()), + "sk-test-1" + ); + write_at(&d.join("auth-proxy-kiro/api_key"), "sk-test-2\r\n\n", 2); + assert_eq!( + value(&st.resolve(&k8s("auth-proxy-kiro", "api_key")).unwrap()), + "sk-test-2" + ); + // file: sources read the path as given + let abs = d.join("plain"); + write_at(&abs, "plain-value", 1); + assert_eq!( + value(&st.resolve(&CredentialSource::File(abs)).unwrap()), + "plain-value" + ); + let _ = fs::remove_dir_all(&d); +} + +#[test] +fn reread_on_change_and_unavailable_on_removal_empty_or_env() { + let d = tmpdir("change"); + let f = d.join("s/key"); + fs::create_dir_all(d.join("s")).unwrap(); + write_at(&f, "one", 1); + let st = FileStore::new(&d); + let src = k8s("s", "key"); + assert_eq!(value(&st.resolve(&src).unwrap()), "one"); + // same pointer while unchanged + let (a, b) = (st.resolve(&src).unwrap(), st.resolve(&src).unwrap()); + assert!(Arc::ptr_eq(&a, &b)); + // changed size + write_at(&f, "three", 2); + assert_eq!(value(&st.resolve(&src).unwrap()), "three"); + // changed mtime only (same size) + write_at(&f, "THREE", 3); + assert_eq!(value(&st.resolve(&src).unwrap()), "THREE"); + // removed: unavailable, never the cached value + fs::remove_file(&f).unwrap(); + assert!(matches!(st.resolve(&src), Err(StoreError::Unavailable(_)))); + // restored + write_at(&f, "back", 4); + assert_eq!(value(&st.resolve(&src).unwrap()), "back"); + // emptied (and whitespace-only): unavailable + write_at(&f, "", 5); + assert!(matches!(st.resolve(&src), Err(StoreError::Unavailable(_)))); + write_at(&f, "\n\n", 6); + assert!(matches!(st.resolve(&src), Err(StoreError::Unavailable(_)))); + // too large + write_at(&f, &"x".repeat(64 * 1024 + 1), 7); + assert!(matches!(st.resolve(&src), Err(StoreError::Unavailable(_)))); + write_at(&f, &"x".repeat(64 * 1024), 8); + assert!(st.resolve(&src).is_ok()); + // other missing secret / key + assert!(matches!( + st.resolve(&k8s("nope", "key")), + Err(StoreError::Unavailable(_)) + )); + assert!(matches!( + st.resolve(&k8s("s", "nope")), + Err(StoreError::Unavailable(_)) + )); + // a directory is not a credential + fs::create_dir_all(d.join("s/dir")).unwrap(); + assert!(matches!( + st.resolve(&k8s("s", "dir")), + Err(StoreError::Unavailable(_)) + )); + // env: parses in the policy but this store does not resolve it + assert_eq!( + st.resolve(&CredentialSource::Env("X".into())).err(), + Some(StoreError::Unsupported) + ); + assert!(!FileStore::supports(&CredentialSource::Env("X".into()))); + assert!(FileStore::supports(&src)); + let _ = fs::remove_dir_all(&d); +} + +/// Kubernetes Secret volume layout: `key -> ..data/key`, `..data -> ..`, +/// kubelet flips `..data` with a rename. +#[cfg(unix)] +#[test] +fn atomic_symlink_swap_is_picked_up_even_with_same_size_and_mtime() { + use std::os::unix::fs::symlink; + let d = tmpdir("swap"); + let sdir = d.join("auth-proxy-kiro"); + fs::create_dir_all(sdir.join("..v1")).unwrap(); + fs::create_dir_all(sdir.join("..v2")).unwrap(); + write_at(&sdir.join("..v1/api_key"), "key-AAAA", 1); + write_at(&sdir.join("..v2/api_key"), "key-BBBB", 1); + symlink("..v1", sdir.join("..data")).unwrap(); + symlink("..data/api_key", sdir.join("api_key")).unwrap(); + + let st = FileStore::new(&d); + let src = k8s("auth-proxy-kiro", "api_key"); + assert_eq!(value(&st.resolve(&src).unwrap()), "key-AAAA"); + symlink("..v2", sdir.join("..data_tmp")).unwrap(); + fs::rename(sdir.join("..data_tmp"), sdir.join("..data")).unwrap(); + assert_eq!(value(&st.resolve(&src).unwrap()), "key-BBBB"); + + // the volume is removed (pod mount torn down): nothing is served + fs::remove_file(sdir.join("..data")).unwrap(); + assert!(matches!(st.resolve(&src), Err(StoreError::Unavailable(_)))); + let _ = fs::remove_dir_all(&d); +} + +// ---------------------------------------------------------------- Broker + +struct Rig { + broker: LocalBroker, + plane: Arc, + token: String, + dir: std::path::PathBuf, +} + +fn rig(tag: &str) -> Rig { + let dir = tmpdir(tag); + for (secret, key, v) in [ + ("auth-proxy-kiro", "api_key", "kiro-secret"), + ("auth-proxy-anthropic", "api_key", "ant-secret"), + ] { + fs::create_dir_all(dir.join(secret)).unwrap(); + write_at(&dir.join(secret).join(key), v, 1); + } + let (_clock, plane) = plane_with(PlaneConfig::default()); + let plane = Arc::new(plane); + let token = plane.hello().unwrap().authority_token; + let broker = LocalBroker::new(plane.clone(), Arc::new(FileStore::new(&dir))); + Rig { + broker, + plane, + token, + dir, + } +} + +#[test] +fn admit_follows_the_pipeline_codes() { + let r = rig("admit"); + let pol = policy(); + r.plane + .register(&r.token, &pol, &req("s1", 7, 1, &["kiro"])) + .unwrap(); + r.plane + .register(&r.token, &pol, &req("s2", 1, 2, &["anthropic"])) + .unwrap(); + + let b = r.broker.admit(&hash(1), "kiro-krs", &pol).unwrap(); + assert_eq!( + b, + Binding { + session: "s1".into(), + generation: 7, + credentials: vec!["kiro".into()] + } + ); + assert_eq!( + r.broker + .admit(&hash(1), "kiro-q", &pol) + .unwrap() + .credentials, + ["kiro"] + ); + // a surrogate bound to credentials that do not reach this route + assert_eq!( + r.broker.admit(&hash(1), "anthropic", &pol), + Err(Code::SurrogateWrongRoute) + ); + assert_eq!( + r.broker.admit(&hash(2), "kiro-krs", &pol), + Err(Code::SurrogateWrongRoute) + ); + assert_eq!( + r.broker.admit(&hash(1), "no-such-route", &pol), + Err(Code::SurrogateWrongRoute) + ); + // unknown, revoked + assert_eq!( + r.broker.admit(&hash(99), "kiro-krs", &pol), + Err(Code::SurrogateUnknown) + ); + r.plane.revoke(&r.token, "s1", 7).unwrap(); + assert_eq!( + r.broker.admit(&hash(1), "kiro-krs", &pol), + Err(Code::SurrogateRevoked) + ); + // the policy now names another identity: not this session's owner + assert_eq!( + r.broker + .admit(&hash(2), "anthropic", &policy_for_identity("pty-team-b")), + Err(Code::SurrogateWrongCaller) + ); + let _ = fs::remove_dir_all(&r.dir); +} + +#[test] +fn admit_uses_the_credentials_of_the_current_policy() { + // a credential dropped from the policy after registration no longer + // counts for any route + let r = rig("admit-drop"); + let pol = policy(); + r.plane + .register(&r.token, &pol, &req("s1", 1, 1, &["kiro"])) + .unwrap(); + let slimmed = ap_core::Policy::parse( + ap_core::testing::sample_toml() + .replace( + "routes = [\"kiro-cps\", \"kiro-krs\", \"kiro-cw\", \"kiro-q\"]", + "routes = [\"kiro-krs\"]", + ) + .replace( + "route = \"kiro-cps\"\nmethods", + "route = \"kiro-krs\"\nmethods", + ) + .as_bytes(), + ) + .unwrap(); + assert!(r.broker.admit(&hash(1), "kiro-krs", &slimmed).is_ok()); + assert_eq!( + r.broker.admit(&hash(1), "kiro-q", &slimmed), + Err(Code::SurrogateWrongRoute) + ); + let _ = fs::remove_dir_all(&r.dir); +} + +#[test] +fn secret_comes_from_the_store_every_time_and_fails_closed() { + let r = rig("secret"); + let pol = policy(); + assert_eq!( + value(&r.broker.secret("kiro", &pol).unwrap()), + "kiro-secret" + ); + assert_eq!( + value(&r.broker.secret("anthropic", &pol).unwrap()), + "ant-secret" + ); + // rotation: the next request sees the new value + write_at(&r.dir.join("auth-proxy-kiro/api_key"), "rotated!!!!", 2); + assert_eq!( + value(&r.broker.secret("kiro", &pol).unwrap()), + "rotated!!!!" + ); + // the store goes away after a good request: broker_unavailable, no stale value + fs::remove_file(r.dir.join("auth-proxy-kiro/api_key")).unwrap(); + assert_eq!( + r.broker.secret("kiro", &pol).err(), + Some(Code::BrokerUnavailable) + ); + assert_eq!( + value(&r.broker.secret("anthropic", &pol).unwrap()), + "ant-secret" + ); + // unknown credential id + assert_eq!( + r.broker.secret("ghost", &pol).err(), + Some(Code::BrokerUnavailable) + ); + // env: source + let env_pol = ap_core::Policy::parse( + ap_core::testing::sample_toml() + .replace("k8s:auth-proxy-anthropic:api_key", "env:ANTHROPIC_API_KEY") + .as_bytes(), + ) + .unwrap(); + assert_eq!( + r.broker.secret("anthropic", &env_pol).err(), + Some(Code::BrokerUnavailable) + ); + let _ = fs::remove_dir_all(&r.dir); +} + +// ---------------------------------------------------------------- no Debug for secrets + +/// Inherent associated consts win when their bounds hold, so `IS` is true +/// exactly when `T` implements the trait. Compile-time proof, no runtime state. +struct Probe(PhantomData); +trait Fallback { + const DEBUG: bool = false; + const DISPLAY: bool = false; + const CLONE: bool = false; +} +impl Fallback for Probe {} +impl Probe { + const DEBUG: bool = true; +} +impl Probe { + const DISPLAY: bool = true; +} +impl Probe { + const CLONE: bool = true; +} + +#[test] +fn secret_values_have_no_debug_display_or_clone() { + const { assert!(!Probe::::DEBUG) }; + const { assert!(!Probe::::DISPLAY) }; + const { assert!(!Probe::::CLONE) }; + // holders of secrets do not leak them through Debug either + const { assert!(!Probe::::DEBUG) }; + const { assert!(!Probe::::DEBUG) }; + // the probe itself works + const { assert!(Probe::::DEBUG && Probe::::DISPLAY && Probe::::CLONE) }; +} + +#[test] +fn hello_debug_redacts_the_token() { + let (_, p) = plane(); + let h: HelloOk = p.hello().unwrap(); + let shown = format!("{h:?}"); + assert!(!shown.contains(&h.authority_token)); + assert!(!shown.contains("apt_")); + assert!(shown.contains("redacted")); + let e = format!( + "{:?}", + p.register(&h.authority_token, &policy(), &req("s", 1, 1, &["ghost"])) + ); + assert!(!e.contains("apt_")); +} diff --git a/crates/ap-broker/tests/support/mod.rs b/crates/ap-broker/tests/support/mod.rs new file mode 100644 index 0000000..7eae901 --- /dev/null +++ b/crates/ap-broker/tests/support/mod.rs @@ -0,0 +1,81 @@ +#![allow(dead_code)] + +use ap_broker::{FakeClock, PlaneConfig, RegisterReq, SessionPlane, SessionRef}; +use ap_core::surrogate::hash_surrogate; +use ap_core::testing::sample_toml; +use ap_core::Policy; +use std::path::PathBuf; +use std::sync::Arc; + +pub fn policy() -> Policy { + Policy::parse(sample_toml().as_bytes()).unwrap() +} + +pub fn policy_for_identity(identity: &str) -> Policy { + Policy::parse(sample_toml().replace("pty-team-a", identity).as_bytes()).unwrap() +} + +pub fn tmpdir(tag: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("ap-broker-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d +} + +/// A well-formed surrogate whose bytes depend on `n`. +pub fn surrogate(n: u8) -> String { + format!("aps_{}", format!("{n:02x}").repeat(32)) +} + +pub fn hash(n: u8) -> [u8; 32] { + hash_surrogate(&surrogate(n)).unwrap() +} + +pub fn req(session: &str, generation: u64, n: u8, creds: &[&str]) -> RegisterReq { + RegisterReq { + session: session.into(), + generation, + surrogate_sha256: hex::encode(hash(n)), + credentials: creds.iter().map(|s| s.to_string()).collect(), + } +} + +pub fn sref(session: &str, generation: u64) -> SessionRef { + SessionRef { + session: session.into(), + generation, + } +} + +pub fn plane_with(cfg: PlaneConfig) -> (Arc, SessionPlane) { + let clock = Arc::new(FakeClock::new()); + let plane = SessionPlane::new(cfg, clock.clone()).unwrap(); + (clock, plane) +} + +pub fn plane() -> (Arc, SessionPlane) { + plane_with(PlaneConfig::default()) +} + +/// Move time forward in 30 s steps, renewing the authority's lease and the +/// listed sessions, as a live runtime does. +pub fn advance_renewing( + clock: &FakeClock, + plane: &SessionPlane, + token: &str, + secs: u64, + sessions: &[SessionRef], +) { + let mut left = secs; + while left > 0 { + let step = left.min(30); + clock.advance_secs(step); + left -= step; + plane.renew(token, sessions).unwrap(); + } +} + +/// Same, renewing only the authority's own lease (an empty session list). +pub fn advance_renewing_authority(clock: &FakeClock, plane: &SessionPlane, token: &str, secs: u64) { + advance_renewing(clock, plane, token, secs, &[]); +} diff --git a/crates/ap-client/Cargo.toml b/crates/ap-client/Cargo.toml new file mode 100644 index 0000000..69558fc --- /dev/null +++ b/crates/ap-client/Cargo.toml @@ -0,0 +1,19 @@ +[package] +name = "ap-client" +description = "auth-proxy session-plane client over a Unix socket, for the runtimes that spawn agent sessions (openab-pty, openab). Small dependency set: no HTTP stack, no credential handling." +version.workspace = true +edition.workspace = true +license.workspace = true +publish.workspace = true + +[dependencies] +getrandom.workspace = true +hex.workspace = true +serde.workspace = true +serde_json.workspace = true +sha2.workspace = true +tokio = { version = "1", features = ["net", "io-util", "time", "sync", "rt"] } + +[dev-dependencies] +ap-core.workspace = true +tokio = { version = "1", features = ["macros", "rt-multi-thread"] } diff --git a/crates/ap-client/src/lib.rs b/crates/ap-client/src/lib.rs new file mode 100644 index 0000000..f9eb1ef --- /dev/null +++ b/crates/ap-client/src/lib.rs @@ -0,0 +1,751 @@ +//! auth-proxy session-plane client (Q1-B), Unix socket only. +//! +//! For the process that spawns agent sessions: the openab-pty runtime, or any +//! other session authority on Kubernetes. It talks HTTP/1.1 and JSON to the +//! proxy's session socket and never sees a credential: it generates a +//! surrogate, keeps it only to put it in the child's environment, and sends +//! the proxy `sha256(surrogate)`. +//! +//! Two layers: +//! +//! - [`Client`]: one function per session-plane call, plus [`Client::raw`]. +//! - [`Authority`]: owns the authority token and the live-session list, renews +//! every 30 s, and resyncs when the proxy forgot its sessions. +//! +//! The HTTP exchange is hand-written (one request per connection, +//! `Connection: close`), so the dependency set stays at tokio, serde, sha2, +//! hex and getrandom. The HTTPS session plane and `ap-relay` belong to the +//! deferred ECS rollout and are not here. + +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use std::collections::HashMap; +use std::fmt; +use std::path::PathBuf; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::net::UnixStream; + +/// How often an authority renews itself and its sessions. +pub const RENEW_EVERY: Duration = Duration::from_secs(30); +const IO_TIMEOUT: Duration = Duration::from_secs(10); +const MAX_RESPONSE_BYTES: usize = 2 * 1024 * 1024; + +// ---------------------------------------------------------------- errors + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ClientError { + /// Connect, read or write failed (or timed out). Carries the error kind only. + Io(String), + /// The answer was not the HTTP/JSON the session plane speaks, or an + /// argument could not be sent safely. + Protocol(String), + /// The proxy answered with an error status. + Api { + status: u16, + code: String, + message: String, + }, +} + +impl ClientError { + pub fn status(&self) -> Option { + match self { + ClientError::Api { status, .. } => Some(*status), + _ => None, + } + } + + /// The error code of an API error (`authority_active`, `unauthorized`, ...). + pub fn code(&self) -> Option<&str> { + match self { + ClientError::Api { code, .. } => Some(code), + _ => None, + } + } + + /// 401: the token is wrong or the authority lease lapsed. + pub fn is_unauthorized(&self) -> bool { + self.status() == Some(401) + } + + /// 409 `authority_active`: another authority's lease is live. + pub fn is_authority_active(&self) -> bool { + self.code() == Some("authority_active") + } +} + +impl fmt::Display for ClientError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + ClientError::Io(k) => write!(f, "session plane i/o error: {k}"), + ClientError::Protocol(m) => write!(f, "session plane protocol error: {m}"), + ClientError::Api { + status, + code, + message, + } => write!(f, "session plane answered {status} {code}: {message}"), + } + } +} + +impl std::error::Error for ClientError {} + +// ---------------------------------------------------------------- surrogate + +/// A freshly generated surrogate: `aps_` + 64 lowercase hex. Put it in the +/// child's environment and drop it. `Debug` is redacted. +pub struct Surrogate(String); + +impl Surrogate { + pub fn generate() -> Result { + let mut raw = [0u8; 32]; + getrandom::getrandom(&mut raw) + .map_err(|_| ClientError::Protocol("no randomness available".into()))?; + Ok(Surrogate(format!("aps_{}", hex::encode(raw)))) + } + + /// The value for the child's environment variable. + pub fn expose(&self) -> &str { + &self.0 + } + + pub fn into_string(self) -> String { + self.0 + } + + /// What the proxy stores: sha256 of the whole string, `aps_` included. + pub fn sha256_hex(&self) -> String { + hex::encode(Sha256::digest(self.0.as_bytes())) + } +} + +impl fmt::Debug for Surrogate { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("Surrogate()") + } +} + +// ---------------------------------------------------------------- wire types + +/// One live session, as named in `renew` and `revoke`. +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Hash)] +pub struct SessionRef { + pub session: String, + pub generation: u64, +} + +/// `POST /v1/sessions` body, and one entry of a `PUT /v1/sessions` list. +#[derive(Serialize, Debug, Clone, PartialEq, Eq)] +pub struct Registration { + pub session: String, + pub generation: u64, + pub surrogate_sha256: String, + pub credentials: Vec, +} + +impl Registration { + pub fn new( + session: &str, + generation: u64, + surrogate: &Surrogate, + credentials: &[&str], + ) -> Registration { + Registration { + session: session.into(), + generation, + surrogate_sha256: surrogate.sha256_hex(), + credentials: credentials.iter().map(|c| c.to_string()).collect(), + } + } + + pub fn session_ref(&self) -> SessionRef { + SessionRef { + session: self.session.clone(), + generation: self.generation, + } + } +} + +#[derive(Deserialize, Debug, Clone, PartialEq, Eq)] +pub struct LeaseReply { + pub lease_secs: u64, +} + +#[derive(Deserialize, Debug, Clone, PartialEq, Eq)] +pub struct RenewReply { + pub lease_secs: u64, + #[serde(default)] + pub unknown: Vec, +} + +#[derive(Deserialize, Debug, Clone, PartialEq, Eq)] +pub struct ResyncReply { + pub registered: usize, + pub dropped: usize, +} + +/// An HTTP answer, before status handling. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RawResponse { + pub status: u16, + pub body: Vec, +} + +// ---------------------------------------------------------------- backoff + +#[derive(Clone, Copy, Debug)] +pub struct Backoff { + pub initial: Duration, + pub max: Duration, + /// Give up after this long. `None` retries forever. + pub deadline: Option, +} + +impl Default for Backoff { + fn default() -> Self { + Backoff { + initial: Duration::from_secs(1), + max: Duration::from_secs(15), + deadline: None, + } + } +} + +impl Backoff { + fn next(&self, cur: Duration) -> Duration { + (cur * 2).min(self.max) + } +} + +// ---------------------------------------------------------------- client + +/// One function per session-plane call. Cheap to clone; clones share the token. +#[derive(Clone)] +pub struct Client { + socket: PathBuf, + token: Arc>>, +} + +impl fmt::Debug for Client { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Client") + .field("socket", &self.socket) + .field("token", &"") + .finish() + } +} + +impl Client { + pub fn new(socket: impl Into) -> Client { + Client { + socket: socket.into(), + token: Arc::new(Mutex::new(None)), + } + } + + /// The authority token from the last successful `hello` (or `set_token`). + pub fn token(&self) -> Option { + self.token.lock().unwrap().clone() + } + + pub fn set_token(&self, token: Option) { + *self.token.lock().unwrap() = token; + } + + /// A client for the same socket with its own token slot. + pub fn fresh(&self) -> Client { + Client::new(self.socket.clone()) + } + + /// `POST /v1/hello`. Stores the token. Returns the authority lease length. + pub async fn hello(&self) -> Result { + #[derive(Deserialize)] + struct Hello { + authority_token: String, + lease_secs: u64, + } + let r = self.call("POST", "/v1/hello", false, Some(b"{}")).await?; + let h: Hello = parse_json(&r)?; + self.set_token(Some(h.authority_token)); + Ok(h.lease_secs) + } + + /// `hello`, retried with backoff while another authority's lease is live + /// (409) or the socket is not there yet. Any other answer ends the loop. + pub async fn hello_retry(&self, backoff: Backoff) -> Result { + let start = Instant::now(); + let mut delay = backoff.initial; + loop { + match self.hello().await { + Ok(l) => return Ok(l), + Err(e) if e.is_authority_active() || matches!(e, ClientError::Io(_)) => { + if backoff + .deadline + .is_some_and(|d| start.elapsed() + delay > d) + { + return Err(e); + } + tokio::time::sleep(delay).await; + delay = backoff.next(delay); + } + Err(e) => return Err(e), + } + } + } + + /// `POST /v1/sessions`. Returns the session lease length. + pub async fn register(&self, reg: &Registration) -> Result { + let body = to_json(reg)?; + let r = self.call("POST", "/v1/sessions", true, Some(&body)).await?; + Ok(parse_json::(&r)?.lease_secs) + } + + /// `POST /v1/renew`: renews the authority and the listed sessions. + pub async fn renew(&self, sessions: &[SessionRef]) -> Result { + let body = to_json(&serde_json::json!({ "sessions": sessions }))?; + let r = self.call("POST", "/v1/renew", true, Some(&body)).await?; + parse_json(&r) + } + + /// `DELETE /v1/sessions/{session}/{generation}`. Also succeeds when the + /// proxy does not know the session. + pub async fn revoke(&self, session: &str, generation: u64) -> Result<(), ClientError> { + if !path_safe(session) { + return Err(ClientError::Protocol( + "session must be [A-Za-z0-9._:-]{1,128}".into(), + )); + } + let path = format!("/v1/sessions/{session}/{generation}"); + self.call("DELETE", &path, true, None).await.map(|_| ()) + } + + /// `PUT /v1/sessions`: the list is the whole truth; sessions not in it are + /// revoked. + pub async fn resync(&self, regs: &[Registration]) -> Result { + let body = to_json(&serde_json::json!({ "sessions": regs }))?; + let r = self.call("PUT", "/v1/sessions", true, Some(&body)).await?; + parse_json(&r) + } + + /// Success statuses only; an error status becomes `ClientError::Api`. + async fn call( + &self, + method: &str, + path: &str, + auth: bool, + body: Option<&[u8]>, + ) -> Result { + let token = if auth { + Some(self.token().ok_or_else(|| { + ClientError::Protocol("no authority token: call hello first".into()) + })?) + } else { + None + }; + let r = self.raw(method, path, token.as_deref(), body).await?; + if (200..300).contains(&r.status) { + Ok(r) + } else { + Err(api_error(&r)) + } + } + + /// One request, any status. For callers that need the exact answer, and + /// for tests that send malformed bodies on purpose. + pub async fn raw( + &self, + method: &str, + path: &str, + bearer: Option<&str>, + body: Option<&[u8]>, + ) -> Result { + let head_ok = |s: &str| !s.bytes().any(|b| b <= 0x20 || b == 0x7f); + if !head_ok(method) || !head_ok(path) || bearer.is_some_and(|t| !head_ok(t)) { + return Err(ClientError::Protocol( + "method, path and token must not contain whitespace or control characters".into(), + )); + } + let mut head = + format!("{method} {path} HTTP/1.1\r\nHost: auth-proxy\r\nConnection: close\r\n"); + if let Some(t) = bearer { + head.push_str(&format!("Authorization: Bearer {t}\r\n")); + } + if let Some(b) = body { + head.push_str(&format!( + "Content-Type: application/json\r\nContent-Length: {}\r\n", + b.len() + )); + } + head.push_str("\r\n"); + let socket = self.socket.clone(); + let exchange = async move { + let mut s = UnixStream::connect(&socket) + .await + .map_err(|e| ClientError::Io(format!("{:?}", e.kind())))?; + let mut sent = s.write_all(head.as_bytes()).await; + if sent.is_ok() { + if let Some(b) = body { + sent = s.write_all(b).await; + } + } + // A proxy that refuses a request early (413) may close before it + // has read the whole body: the answer is still on the socket. + if let Err(e) = sent { + if !matches!( + e.kind(), + std::io::ErrorKind::BrokenPipe | std::io::ErrorKind::ConnectionReset + ) { + return Err(ClientError::Io(format!("{:?}", e.kind()))); + } + } + let mut out = Vec::new(); + let mut buf = [0u8; 8192]; + loop { + let n = match s.read(&mut buf).await { + Ok(n) => n, + // The proxy may reset after a refusal it sent already. + Err(e) + if !out.is_empty() && e.kind() == std::io::ErrorKind::ConnectionReset => + { + 0 + } + Err(e) => return Err(ClientError::Io(format!("{:?}", e.kind()))), + }; + if n == 0 { + break; + } + out.extend_from_slice(&buf[..n]); + if out.len() > MAX_RESPONSE_BYTES { + return Err(ClientError::Protocol("response too large".into())); + } + } + parse_response(&out) + }; + match tokio::time::timeout(IO_TIMEOUT, exchange).await { + Ok(r) => r, + Err(_) => Err(ClientError::Io("TimedOut".into())), + } + } +} + +fn path_safe(s: &str) -> bool { + !s.is_empty() + && s.len() <= 128 + && s.bytes() + .all(|b| b.is_ascii_alphanumeric() || b"._:-".contains(&b)) +} + +fn to_json(v: &T) -> Result, ClientError> { + serde_json::to_vec(v).map_err(|_| ClientError::Protocol("cannot encode request".into())) +} + +fn parse_json Deserialize<'de>>(r: &RawResponse) -> Result { + serde_json::from_slice(&r.body) + .map_err(|_| ClientError::Protocol("answer is not the expected JSON".into())) +} + +fn api_error(r: &RawResponse) -> ClientError { + #[derive(Deserialize, Default)] + struct E { + #[serde(default)] + error: String, + #[serde(default)] + message: String, + } + let e: E = serde_json::from_slice(&r.body).unwrap_or_default(); + ClientError::Api { + status: r.status, + code: e.error, + message: e.message, + } +} + +/// Parse a complete HTTP/1.1 answer (read to EOF). +pub fn parse_response(raw: &[u8]) -> Result { + let bad = |m: &str| ClientError::Protocol(m.into()); + let split = raw + .windows(4) + .position(|w| w == b"\r\n\r\n") + .ok_or_else(|| bad("no end of headers"))?; + let head = std::str::from_utf8(&raw[..split]).map_err(|_| bad("headers not UTF-8"))?; + let mut lines = head.split("\r\n"); + let status_line = lines.next().ok_or_else(|| bad("empty answer"))?; + let mut parts = status_line.splitn(3, ' '); + if !parts.next().is_some_and(|v| v.starts_with("HTTP/1.")) { + return Err(bad("not an HTTP/1.x answer")); + } + let status: u16 = parts + .next() + .and_then(|s| s.parse().ok()) + .ok_or_else(|| bad("bad status line"))?; + let mut content_length: Option = None; + let mut chunked = false; + for l in lines { + if let Some((k, v)) = l.split_once(':') { + let (k, v) = (k.trim().to_ascii_lowercase(), v.trim()); + if k == "content-length" { + content_length = Some(v.parse().map_err(|_| bad("bad content-length"))?); + } else if k == "transfer-encoding" && v.to_ascii_lowercase().contains("chunked") { + chunked = true; + } + } + } + let rest = &raw[split + 4..]; + let body = if chunked { + dechunk(rest)? + } else if let Some(n) = content_length { + if rest.len() < n { + return Err(bad("body shorter than content-length")); + } + rest[..n].to_vec() + } else { + rest.to_vec() + }; + Ok(RawResponse { status, body }) +} + +fn dechunk(mut rest: &[u8]) -> Result, ClientError> { + let bad = || ClientError::Protocol("bad chunked body".into()); + let mut out = Vec::new(); + loop { + let eol = rest.windows(2).position(|w| w == b"\r\n").ok_or_else(bad)?; + let size_txt = std::str::from_utf8(&rest[..eol]).map_err(|_| bad())?; + let size_txt = size_txt.split(';').next().unwrap_or("").trim(); + let n = usize::from_str_radix(size_txt, 16).map_err(|_| bad())?; + rest = &rest[eol + 2..]; + if n == 0 { + return Ok(out); + } + if rest.len() < n + 2 { + return Err(bad()); + } + out.extend_from_slice(&rest[..n]); + rest = &rest[n + 2..]; + } +} + +// ---------------------------------------------------------------- authority + +#[derive(Clone, Copy, Debug)] +pub struct AuthorityConfig { + pub renew_every: Duration, + pub backoff: Backoff, +} + +impl Default for AuthorityConfig { + fn default() -> Self { + AuthorityConfig { + renew_every: RENEW_EVERY, + backoff: Backoff::default(), + } + } +} + +/// What one renew pass did. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum RenewOutcome { + /// Every live session was known to the proxy. + Renewed, + /// The proxy had forgotten sessions (it restarted): the full list was re-sent. + Resynced, + /// The authority lease had lapsed: a new `hello` won, then the full list was re-sent. + Reacquired, +} + +/// The session authority's side of Q1-B. Holds the authority token and the +/// registrations of the live sessions (hashes and credential ids, never the +/// surrogates, which only the spawned children hold). +pub struct Authority { + client: Client, + cfg: AuthorityConfig, + live: Mutex>, +} + +impl Authority { + /// Send `hello` before binding listeners or spawning anything, retrying + /// with backoff while a previous authority's 90 s lock is live. + pub async fn connect( + socket: impl Into, + cfg: AuthorityConfig, + ) -> Result { + let client = Client::new(socket); + client.hello_retry(cfg.backoff).await?; + Ok(Authority { + client, + cfg, + live: Mutex::new(HashMap::new()), + }) + } + + pub fn client(&self) -> &Client { + &self.client + } + + /// Generate a surrogate, register its hash, and return the surrogate for + /// the child's environment. The session is only tracked when the proxy + /// accepted it. + pub async fn register( + &self, + session: &str, + generation: u64, + credentials: &[&str], + ) -> Result { + let s = Surrogate::generate()?; + let reg = Registration::new(session, generation, &s, credentials); + self.client.register(®).await?; + self.live.lock().unwrap().insert(reg.session_ref(), reg); + Ok(s) + } + + /// End a session. It stops being tracked first, so a resync can never + /// bring it back; an error from the proxy is still returned. + pub async fn revoke(&self, session: &str, generation: u64) -> Result<(), ClientError> { + self.live.lock().unwrap().remove(&SessionRef { + session: session.into(), + generation, + }); + self.client.revoke(session, generation).await + } + + pub fn live_sessions(&self) -> Vec { + let mut v: Vec<_> = self.live.lock().unwrap().keys().cloned().collect(); + v.sort_by(|a, b| (&a.session, a.generation).cmp(&(&b.session, b.generation))); + v + } + + async fn resync(&self) -> Result { + let regs: Vec = self.live.lock().unwrap().values().cloned().collect(); + self.client.resync(®s).await + } + + /// One renew pass: renew everything; if the proxy lists sessions as + /// unknown, resend the full list; if the token was refused, win `hello` + /// again and resend the full list. + pub async fn renew_once(&self) -> Result { + let refs = self.live_sessions(); + match self.client.renew(&refs).await { + Ok(r) if r.unknown.is_empty() => Ok(RenewOutcome::Renewed), + Ok(_) => { + self.resync().await?; + Ok(RenewOutcome::Resynced) + } + Err(e) if e.is_unauthorized() => { + self.client.hello_retry(self.cfg.backoff).await?; + self.resync().await?; + Ok(RenewOutcome::Reacquired) + } + Err(e) => Err(e), + } + } + + /// Renew every `renew_every` for as long as the task lives. After an error + /// it retries with backoff. It never tears sessions down: the proxy's + /// leases are what end them. Abort the task to stop renewing. + pub async fn run_renew_loop(self: Arc) { + let mut retry = None::; + loop { + tokio::time::sleep(retry.unwrap_or(self.cfg.renew_every)).await; + retry = match self.renew_once().await { + Ok(_) => None, + Err(_) => Some(match retry { + None => self.cfg.backoff.initial, + Some(d) => self.cfg.backoff.next(d), + }), + }; + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn surrogate_has_the_proxy_format_and_hash() { + let s = Surrogate::generate().unwrap(); + assert!(ap_core::surrogate::is_surrogate(s.expose()), "{s:?}"); + assert_eq!( + s.sha256_hex(), + hex::encode(ap_core::surrogate::hash_surrogate(s.expose()).unwrap()) + ); + assert_ne!(s.expose(), Surrogate::generate().unwrap().expose()); + assert_eq!(format!("{s:?}"), "Surrogate()"); + } + + #[test] + fn registration_carries_only_the_hash() { + let s = Surrogate::generate().unwrap(); + let reg = Registration::new("sess-1", 2, &s, &["kiro", "anthropic"]); + let json = serde_json::to_string(®).unwrap(); + assert!(!json.contains(s.expose())); + assert!(json.contains(&s.sha256_hex())); + assert_eq!(reg.session_ref().generation, 2); + } + + #[test] + fn parses_content_length_chunked_and_eof_bodies() { + let r = + parse_response(b"HTTP/1.1 201 Created\r\ncontent-length: 2\r\n\r\n{}extra").unwrap(); + assert_eq!((r.status, r.body.as_slice()), (201, &b"{}"[..])); + let r = parse_response( + b"HTTP/1.1 200 OK\r\ntransfer-encoding: chunked\r\n\r\n3\r\nabc\r\n2;x=y\r\nde\r\n0\r\n\r\n", + ) + .unwrap(); + assert_eq!(r.body, b"abcde"); + let r = parse_response(b"HTTP/1.1 204 No Content\r\n\r\n").unwrap(); + assert_eq!((r.status, r.body.len()), (204, 0)); + assert!(parse_response(b"HTTP/1.1 200 OK\r\ncontent-length: 9\r\n\r\nab").is_err()); + assert!(parse_response(b"garbage").is_err()); + assert!(parse_response(b"SMTP 200 x\r\n\r\n").is_err()); + } + + #[test] + fn api_errors_carry_code_and_status() { + let e = api_error(&RawResponse { + status: 409, + body: br#"{"error":"authority_active","message":"another authority's lease is live"}"# + .to_vec(), + }); + assert!(e.is_authority_active()); + assert_eq!(e.status(), Some(409)); + let e = api_error(&RawResponse { + status: 401, + body: b"not json".to_vec(), + }); + assert!(e.is_unauthorized()); + } + + #[tokio::test] + async fn refuses_header_injection_and_missing_token() { + let c = Client::new("/nonexistent/s.sock"); + let e = c.raw("POST", "/v1/hello", Some("a\r\nX: y"), None).await; + assert!(matches!(e, Err(ClientError::Protocol(_)))); + let e = c.raw("POST", "/v1/hello HTTP/1.1", None, None).await; + assert!(matches!(e, Err(ClientError::Protocol(_)))); + let e = c.renew(&[]).await.unwrap_err(); + assert!(matches!(e, ClientError::Protocol(_)), "{e}"); + let e = c.revoke("bad session", 1).await.unwrap_err(); + assert!(matches!(e, ClientError::Protocol(_)), "{e}"); + // No socket: an I/O error, which hello_retry treats as "not up yet". + let e = c.hello().await.unwrap_err(); + assert!(matches!(e, ClientError::Io(_)), "{e}"); + } + + #[tokio::test] + async fn hello_retry_honors_its_deadline() { + let c = Client::new("/nonexistent/s.sock"); + let t0 = Instant::now(); + let e = c + .hello_retry(Backoff { + initial: Duration::from_millis(20), + max: Duration::from_millis(40), + deadline: Some(Duration::from_millis(150)), + }) + .await + .unwrap_err(); + assert!(matches!(e, ClientError::Io(_))); + assert!(t0.elapsed() < Duration::from_secs(2)); + } +} diff --git a/crates/ap-core/Cargo.toml b/crates/ap-core/Cargo.toml new file mode 100644 index 0000000..1982289 --- /dev/null +++ b/crates/ap-core/Cargo.toml @@ -0,0 +1,22 @@ +[package] +name = "ap-core" +description = "auth-proxy core: config model and validation, canonicalization, policy, error dialects, audit record. No network I/O, no credential values." +version.workspace = true +edition.workspace = true +license.workspace = true +publish.workspace = true + +[features] +# Test-only: lets a route carry `connect_to` (a resolver override, like curl +# --resolve). Off in every shipped build, where the key is an unknown field and +# the policy is rejected. Only dev-dependencies and the matrix build turn it on. +test-resolve = [] + +[dependencies] +hex.workspace = true +http.workspace = true +serde.workspace = true +serde_json.workspace = true +sha2.workspace = true +subtle.workspace = true +toml.workspace = true diff --git a/crates/ap-core/src/audit.rs b/crates/ap-core/src/audit.rs new file mode 100644 index 0000000..53abdd3 --- /dev/null +++ b/crates/ap-core/src/audit.rs @@ -0,0 +1,227 @@ +//! The audit record: one JSON line per decision, identities and codes only. +//! +//! The record cannot carry the `/ap/` prefix. The only path type +//! its constructor takes is `RoutePath`, which is the route-relative path and +//! refuses anything that starts with `/ap/`, has a query, or contains a +//! key-looking string. Every other text field is passed through `safe_field`. +//! There is no field for the caller key, the surrogate, the authority token or +//! a credential, and no way to add free-form text. + +use crate::canon::{safe_field, RoutePath}; +use crate::code::Code; +use serde::Serialize; + +#[derive(Serialize, Debug, Clone, PartialEq, Eq)] +pub struct AuditRec { + identity: String, + session: String, + generation: Option, + route: String, + method: String, + path: String, + aws_target: String, + decision: &'static str, + code: &'static str, + status: u16, + duration_ms: u64, + /// Response-body bytes already relayed to the client when an admitted + /// request failed mid-stream (`upstream_reset`). `null` on every other line. + bytes_sent: Option, +} + +/// What the caller knows when it writes the line. All text is optional: a +/// refusal before the caller key is verified knows no route or session. +#[derive(Default, Debug, Clone)] +pub struct AuditInput<'a> { + pub identity: Option<&'a str>, + pub session: Option<&'a str>, + pub generation: Option, + pub route: Option<&'a str>, + pub method: &'a str, + pub aws_target: Option<&'a str>, + pub duration_ms: u64, +} + +impl AuditRec { + /// An allowed request. `path` is route-relative. + pub fn allowed(input: &AuditInput<'_>, path: &RoutePath, status: u16) -> AuditRec { + AuditRec::build(input, path, "allow", "ok", status) + } + + /// A refused request. Pass `RoutePath::none()` for refusals before the + /// caller key was verified. + pub fn refused(input: &AuditInput<'_>, path: &RoutePath, code: Code) -> AuditRec { + AuditRec::build(input, path, "deny", code.as_str(), code.status().as_u16()) + } + + /// An admitted request that failed after admission (upstream failure, + /// reset mid-stream). `code` is a fixed label such as `upstream_reset`. + /// `bytes_sent` is the number of response-body bytes the client had already + /// been sent when the failure hit; a count, never content. + pub fn failed( + input: &AuditInput<'_>, + path: &RoutePath, + code: &'static str, + status: u16, + bytes_sent: u64, + ) -> AuditRec { + let mut rec = AuditRec::build(input, path, "error", code, status); + rec.bytes_sent = Some(bytes_sent); + rec + } + + fn build( + input: &AuditInput<'_>, + path: &RoutePath, + decision: &'static str, + code: &'static str, + status: u16, + ) -> AuditRec { + let f = |s: Option<&str>| s.map(safe_field).unwrap_or_else(|| "-".into()); + AuditRec { + identity: f(input.identity), + session: f(input.session), + generation: input.generation, + route: f(input.route), + method: safe_field(input.method), + path: path.as_str().to_string(), + aws_target: f(input.aws_target), + decision, + code, + status, + duration_ms: input.duration_ms, + bytes_sent: None, + } + } + + pub fn path(&self) -> &str { + &self.path + } + + /// One JSON line (no trailing newline). `t_ms` is the Unix time in ms. + pub fn to_line(&self, t_ms: u64) -> String { + let mut v = serde_json::to_value(self).expect("audit record serializes"); + v.as_object_mut() + .expect("object") + .insert("t".into(), t_ms.into()); + v.to_string() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn full_input() -> AuditInput<'static> { + AuditInput { + identity: Some("pty-team-a"), + session: Some("sess-1"), + generation: Some(3), + route: Some("kiro-krs"), + method: "POST", + aws_target: Some("Svc.Op"), + duration_ms: 12, + } + } + + #[test] + fn fully_populated_record_has_no_key_or_prefix() { + let rec = AuditRec::allowed(&full_input(), &RoutePath::new("/v1/messages"), 200); + let line = rec.to_line(1); + assert!(!line.contains("apk_") && !line.contains("aps_") && !line.contains("apt_")); + assert!(!line.contains("/ap/"), "{line}"); + let v: serde_json::Value = serde_json::from_str(&line).unwrap(); + for k in [ + "identity", + "session", + "generation", + "route", + "method", + "path", + "aws_target", + "decision", + "code", + "status", + "duration_ms", + "bytes_sent", + "t", + ] { + assert!(v.get(k).is_some(), "missing {k}"); + } + assert_eq!( + v.as_object().unwrap().len(), + 13, + "no field beyond the documented ones" + ); + assert_eq!(v["path"], "/v1/messages"); + assert!(v["bytes_sent"].is_null(), "only failed lines carry a count"); + } + + #[test] + fn failed_line_carries_the_byte_count_and_nothing_else_new() { + let rec = AuditRec::failed( + &full_input(), + &RoutePath::new("/v1/messages"), + "upstream_reset", + 200, + 4096, + ); + let v: serde_json::Value = serde_json::from_str(&rec.to_line(1)).unwrap(); + assert_eq!(v["code"], "upstream_reset"); + assert_eq!(v["decision"], "error"); + assert_eq!(v["bytes_sent"], 4096); + assert_eq!(v.as_object().unwrap().len(), 13); + let line = v.to_string(); + assert!(!line.contains("/ap/") && !line.contains("aps_") && !line.contains("apk_")); + } + + #[test] + fn prefix_and_keys_are_scrubbed_from_every_text_field() { + let key = format!("apk_{}", "a".repeat(64)); + let sur = format!("aps_{}", "b".repeat(64)); + let tok = format!("apt_{}", "c".repeat(64)); + let dirty_path = format!("/ap/{key}/kiro-krs/v1/x"); + let query_path = format!("/v1/x?token={sur}"); + let input = AuditInput { + identity: Some(&key), + session: Some(&sur), + generation: None, + route: Some(&tok), + method: &key, + aws_target: Some(&sur), + duration_ms: 0, + }; + for path in [&dirty_path, &query_path, &key] { + for rec in [ + AuditRec::allowed(&input, &RoutePath::new(path), 200), + AuditRec::refused(&input, &RoutePath::new(path), Code::PolicyDenied), + AuditRec::failed(&input, &RoutePath::new(path), "upstream_reset", 502, 0), + ] { + let line = rec.to_line(0); + assert!( + !line.contains("apk_") && !line.contains("aps_") && !line.contains("apt_"), + "{line}" + ); + assert!(!line.contains("/ap/"), "{line}"); + } + } + } + + #[test] + fn refusal_before_verification_logs_no_path() { + let rec = AuditRec::refused( + &AuditInput { + method: "GET", + ..Default::default() + }, + &RoutePath::none(), + Code::CallerRejected, + ); + assert_eq!(rec.path(), "-"); + let v: serde_json::Value = serde_json::from_str(&rec.to_line(0)).unwrap(); + assert_eq!(v["code"], "caller_rejected"); + assert_eq!(v["status"], 403); + assert_eq!(v["decision"], "deny"); + assert_eq!(v["route"], "-"); + } +} diff --git a/crates/ap-core/src/canon.rs b/crates/ap-core/src/canon.rs new file mode 100644 index 0000000..83422fa --- /dev/null +++ b/crates/ap-core/src/canon.rs @@ -0,0 +1,261 @@ +//! Canonicalization: upstream host validation, ambiguous-path refusal, and the +//! one place the `/ap///` prefix is taken apart. +//! +//! The prefix carries the caller key. The types here make sure it cannot reach +//! a log line: `ApPath::verify` is the only way to get at the route and the +//! rest, it consumes the caller key, and `RoutePath` (the only path type the +//! audit record accepts) refuses to hold anything that looks like the prefix. + +use std::net::IpAddr; + +/// Validate an upstream host: lowercase DNS name, no IP literal, no userinfo, +/// no port, no trailing dot, LDH labels, at least two labels. +pub fn canonical_host(h: &str) -> Result<(), String> { + if h.is_empty() || h.len() > 253 { + return Err("empty or too long".into()); + } + if h.parse::().is_ok() || h.starts_with('[') { + return Err("IP literal".into()); + } + if h != h.to_ascii_lowercase() { + return Err("not lowercase".into()); + } + let labels: Vec<&str> = h.split('.').collect(); + if labels.len() < 2 { + return Err("single label".into()); + } + for l in &labels { + let ok = !l.is_empty() + && l.len() <= 63 + && !l.starts_with('-') + && !l.ends_with('-') + && l.bytes() + .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-'); + if !ok { + return Err("bad label (userinfo, port, trailing dot or non-LDH)".into()); + } + } + // An all-numeric last label is an IPv4 spelling the IpAddr parser misses + // (127.1, 0x7f.0.0.1). + if labels.last().unwrap().bytes().all(|b| b.is_ascii_digit()) { + return Err("numeric TLD (IPv4 spelling)".into()); + } + Ok(()) +} + +/// Raw path checks. Run on the still-encoded path so that no decoding layer +/// can disagree with the policy check about what the path is. +pub fn path_ambiguous(p: &str) -> bool { + let lower = p.to_ascii_lowercase(); + if ["%2e", "%2f", "%5c", "%00", "%25"] + .iter() + .any(|s| lower.contains(s)) + || p.contains('\\') + { + return true; + } + let segs: Vec<&str> = p.split('/').skip(1).collect(); + segs.iter() + .enumerate() + .any(|(i, s)| *s == "." || *s == ".." || (s.is_empty() && i + 1 != segs.len())) +} + +/// `/ap///`, split but not yet trusted. Holds the +/// caller key, so it has no `Debug` and no accessor for the key. +pub struct ApPath<'a> { + caller_key: &'a str, + route: &'a str, + rest: &'a str, +} + +impl<'a> ApPath<'a> { + /// Split a request path. `None` when the shape is wrong. Callers must have + /// run `path_ambiguous` first. + pub fn split(path: &'a str) -> Option> { + let mut it = path.splitn(5, '/'); + let (empty, ap, key, route, rest) = (it.next(), it.next(), it.next(), it.next(), it.next()); + if empty != Some("") || ap != Some("ap") { + return None; + } + let (key, route) = ( + key.filter(|k| !k.is_empty())?, + route.filter(|r| !r.is_empty())?, + ); + Some(ApPath { + caller_key: key, + route, + rest: rest.unwrap_or(""), + }) + } + + /// Check the caller key with `ok` (the policy's constant-time compare) and + /// drop it. Only a verified path can produce a route name or a + /// route-relative path. + pub fn verify(self, ok: impl FnOnce(&str) -> bool) -> Option> { + ok(self.caller_key).then_some(VerifiedPath { + route: self.route, + rest: self.rest, + }) + } + + /// The route segment of a path whose caller key is not (yet) verified. + /// Only for choosing an error dialect; never log it. + pub fn unverified_route(&self) -> &'a str { + self.route + } +} + +/// A path whose caller key has been verified and discarded. +#[derive(Debug, Clone, Copy)] +pub struct VerifiedPath<'a> { + route: &'a str, + rest: &'a str, +} + +impl<'a> VerifiedPath<'a> { + pub fn route(&self) -> &'a str { + self.route + } + + /// The upstream path, `/` + rest, without the query. + pub fn rest_path(&self) -> String { + format!("/{}", self.rest) + } + + /// The loggable form of the route-relative path. + pub fn route_relative(&self) -> RoutePath { + RoutePath::new(&self.rest_path()) + } +} + +const MAX_FIELD: usize = 256; +/// Substrings that must never appear in any log field: caller key, surrogate +/// and authority-token prefixes. +const FORBIDDEN: &[&str] = &["apk_", "aps_", "apt_"]; + +/// Clean a value for an audit line: printable ASCII only, bounded, and never +/// anything that looks like a caller key, surrogate or authority token. +/// Returns `-` otherwise. +pub fn safe_field(s: &str) -> String { + let lower = s.to_ascii_lowercase(); + if s.is_empty() + || s.len() > MAX_FIELD + || !s.bytes().all(|b| (0x21..=0x7e).contains(&b)) + || FORBIDDEN.iter().any(|f| lower.contains(f)) + { + "-".into() + } else { + s.to_string() + } +} + +/// A route-relative request path (no `/ap/` prefix, no query), the +/// only path type an `AuditRec` accepts. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RoutePath(String); + +impl RoutePath { + /// Never fails and never carries a prefix: a value that starts with `/ap/`, + /// has a query, or looks like a key becomes `-`. + pub fn new(path: &str) -> RoutePath { + if path.starts_with("/ap/") || path.contains(['?', '#']) { + return RoutePath::none(); + } + RoutePath(safe_field(path)) + } + + /// For refusals before the caller key is verified. + pub fn none() -> RoutePath { + RoutePath("-".into()) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn hosts() { + for ok in ["api.anthropic.com", "runtime.us-east-1.kiro.dev", "a-b.c"] { + assert!(canonical_host(ok).is_ok(), "{ok}"); + } + for bad in [ + "127.0.0.1", + "::1", + "[::1]", + "127.1", + "user@api.x.com", + "api.x.com.", + "API.x.com", + "api.x.com:443", + "localhost", + "0x7f.0.0.1", + "a..b", + "-a.b", + "", + ] { + assert!(canonical_host(bad).is_err(), "{bad}"); + } + } + + #[test] + fn paths() { + for bad in [ + "/ap/k/r/../x", + "/ap/k/r/%2e%2e/x", + "/ap/k/r/a%2Fb", + "/ap//r/x", + "/ap/k/r/./x", + "/ap/k/r/a\\b", + "/ap/k/r/%252e", + ] { + assert!(path_ambiguous(bad), "{bad}"); + } + for ok in ["/ap/k/r/v1/messages", "/ap/k/r/", "/ap/k/r"] { + assert!(!path_ambiguous(ok), "{ok}"); + } + } + + #[test] + fn split_and_verify() { + let p = ApPath::split("/ap/apk_KEY/anthropic/v1/messages").unwrap(); + assert_eq!(p.unverified_route(), "anthropic"); + assert!(p.verify(|k| k == "wrong").is_none()); + let v = ApPath::split("/ap/apk_KEY/anthropic/v1/messages") + .unwrap() + .verify(|k| k == "apk_KEY") + .unwrap(); + assert_eq!(v.route(), "anthropic"); + assert_eq!(v.rest_path(), "/v1/messages"); + assert_eq!(v.route_relative().as_str(), "/v1/messages"); + + let v = ApPath::split("/ap/k/r").unwrap().verify(|_| true).unwrap(); + assert_eq!(v.rest_path(), "/"); + for bad in ["/ap/k", "/ap//r/x", "/x/k/r/", "ap/k/r", "/ap", "/apx/k/r/"] { + assert!(ApPath::split(bad).is_none(), "{bad}"); + } + } + + #[test] + fn route_path_never_carries_the_prefix() { + for bad in [ + "/ap/apk_00/anthropic/v1/messages", + "/v1/x?key=apk_00", + "/v1/apk_deadbeef", + "/v1/APS_deadbeef", + "/v1/apt_deadbeef/x", + "/v1/\u{7f}x", + "/v1/ünï", + "", + ] { + assert_eq!(RoutePath::new(bad).as_str(), "-", "{bad:?}"); + } + assert_eq!(RoutePath::new("/v1/messages").as_str(), "/v1/messages"); + assert_eq!(RoutePath::none().as_str(), "-"); + assert_eq!(RoutePath::new(&"/a".repeat(200)).as_str(), "-"); + } +} diff --git a/crates/ap-core/src/code.rs b/crates/ap-core/src/code.rs new file mode 100644 index 0000000..7eb5ed3 --- /dev/null +++ b/crates/ap-core/src/code.rs @@ -0,0 +1,243 @@ +//! Refusal codes (design doc section 4 table), status mapping and error dialects. + +use http::StatusCode; +use serde::Deserialize; +use std::fmt; + +/// Every way a request can be refused. A refusal is final for the request: +/// nothing goes upstream. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Code { + AbsoluteForm, + HostRejected, + PathAmbiguous, + SurrogateAmbiguous, + CallerRejected, + SurrogateMissing, + SurrogateMalformed, + SurrogateUnknown, + SurrogateRevoked, + SurrogateExpired, + SurrogateWrongCaller, + SurrogateWrongRoute, + PolicyEmpty, + PolicyDenied, + RouteUnknown, + ConnectRefused, + BodyTooLarge, + WebsocketUnsupported, + UpstreamUnavailable, + PolicyUnavailable, + BrokerUnavailable, +} + +impl Code { + pub const ALL: [Code; 21] = [ + Code::AbsoluteForm, + Code::HostRejected, + Code::PathAmbiguous, + Code::SurrogateAmbiguous, + Code::CallerRejected, + Code::SurrogateMissing, + Code::SurrogateMalformed, + Code::SurrogateUnknown, + Code::SurrogateRevoked, + Code::SurrogateExpired, + Code::SurrogateWrongCaller, + Code::SurrogateWrongRoute, + Code::PolicyEmpty, + Code::PolicyDenied, + Code::RouteUnknown, + Code::ConnectRefused, + Code::BodyTooLarge, + Code::WebsocketUnsupported, + Code::UpstreamUnavailable, + Code::PolicyUnavailable, + Code::BrokerUnavailable, + ]; + + pub const fn as_str(self) -> &'static str { + match self { + Code::AbsoluteForm => "absolute_form", + Code::HostRejected => "host_rejected", + Code::PathAmbiguous => "path_ambiguous", + Code::SurrogateAmbiguous => "surrogate_ambiguous", + Code::CallerRejected => "caller_rejected", + Code::SurrogateMissing => "surrogate_missing", + Code::SurrogateMalformed => "surrogate_malformed", + Code::SurrogateUnknown => "surrogate_unknown", + Code::SurrogateRevoked => "surrogate_revoked", + Code::SurrogateExpired => "surrogate_expired", + Code::SurrogateWrongCaller => "surrogate_wrong_caller", + Code::SurrogateWrongRoute => "surrogate_wrong_route", + Code::PolicyEmpty => "policy_empty", + Code::PolicyDenied => "policy_denied", + Code::RouteUnknown => "route_unknown", + Code::ConnectRefused => "connect_refused", + Code::BodyTooLarge => "body_too_large", + Code::WebsocketUnsupported => "websocket_unsupported", + Code::UpstreamUnavailable => "upstream_unavailable", + Code::PolicyUnavailable => "policy_unavailable", + Code::BrokerUnavailable => "broker_unavailable", + } + } + + /// Phase 1 status mapping. Every surrogate state is 403 (backlog item 3): + /// a 401 makes some CLIs retry for minutes, and an env-delivered + /// surrogate can never be re-minted inside a running CLI. + pub const fn status(self) -> StatusCode { + match self { + Code::AbsoluteForm + | Code::HostRejected + | Code::PathAmbiguous + | Code::SurrogateAmbiguous => StatusCode::BAD_REQUEST, + Code::CallerRejected + | Code::SurrogateMissing + | Code::SurrogateMalformed + | Code::SurrogateUnknown + | Code::SurrogateRevoked + | Code::SurrogateExpired + | Code::SurrogateWrongCaller + | Code::SurrogateWrongRoute + | Code::PolicyEmpty + | Code::PolicyDenied => StatusCode::FORBIDDEN, + Code::RouteUnknown => StatusCode::NOT_FOUND, + Code::ConnectRefused => StatusCode::METHOD_NOT_ALLOWED, + Code::BodyTooLarge => StatusCode::PAYLOAD_TOO_LARGE, + Code::WebsocketUnsupported => StatusCode::NOT_IMPLEMENTED, + Code::UpstreamUnavailable => StatusCode::BAD_GATEWAY, + Code::PolicyUnavailable | Code::BrokerUnavailable => StatusCode::SERVICE_UNAVAILABLE, + } + } + + pub const fn message(self) -> &'static str { + match self { + Code::AbsoluteForm => "absolute-form request target refused", + Code::HostRejected => "Host must be exactly one listener authority", + Code::PathAmbiguous => "ambiguous path refused", + Code::SurrogateAmbiguous => "more than one surrogate presented", + Code::CallerRejected => "caller key not recognised", + Code::SurrogateMissing => "no surrogate presented", + Code::SurrogateMalformed => "surrogate malformed", + Code::SurrogateUnknown => "surrogate not recognised", + Code::SurrogateRevoked => "surrogate revoked", + Code::SurrogateExpired => "surrogate lease lapsed", + Code::SurrogateWrongCaller => "surrogate belongs to another identity", + Code::SurrogateWrongRoute => "surrogate not bound to this route", + Code::PolicyEmpty => "policy is empty; nothing is allowed", + Code::PolicyDenied => "request not allowed by policy", + Code::RouteUnknown => "expected /ap/// with a known route", + Code::ConnectRefused => "CONNECT is not supported", + Code::BodyTooLarge => "request body too large", + Code::WebsocketUnsupported => "WebSocket upgrade is not supported", + Code::UpstreamUnavailable => "upstream unavailable", + Code::PolicyUnavailable => "policy unavailable; refusing", + Code::BrokerUnavailable => "credential store unavailable; refusing", + } + } +} + +impl fmt::Display for Code { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.as_str()) + } +} + +#[derive(Deserialize, Clone, Copy, Default, PartialEq, Eq, Debug)] +#[serde(rename_all = "lowercase")] +pub enum ErrorShape { + #[default] + Json, + /// AWS JSON protocol (`__type` + `message`), so kiro-cli shows the message. + Aws, +} + +/// Status, headers and body of a refusal, in the route's error dialect. +pub fn deny_parts( + shape: ErrorShape, + code: Code, +) -> (StatusCode, Vec<(&'static str, String)>, String) { + let mut hs = vec![("x-auth-proxy-error", code.as_str().to_string())]; + let body = match shape { + ErrorShape::Json => { + hs.push(("content-type", "application/json".into())); + serde_json::json!({"type": "error", "error": {"type": code.as_str(), "message": format!("auth-proxy: {}", code.message())}}) + .to_string() + } + ErrorShape::Aws => { + let t = if code.status().is_server_error() { + "ServiceUnavailableException" + } else { + "AccessDeniedException" + }; + hs.push(("content-type", "application/x-amz-json-1.0".into())); + hs.push(("x-amzn-errortype", t.into())); + serde_json::json!({"__type": t, "message": format!("auth-proxy: {} ({})", code.message(), code.as_str())}).to_string() + } + }; + (code.status(), hs, body) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn all_is_complete_and_names_unique() { + let names: std::collections::HashSet<_> = Code::ALL.iter().map(|c| c.as_str()).collect(); + assert_eq!(names.len(), Code::ALL.len()); + } + + #[test] + fn status_mapping_matches_design_table() { + use Code::*; + for c in [ + AbsoluteForm, + HostRejected, + PathAmbiguous, + SurrogateAmbiguous, + ] { + assert_eq!(c.status(), 400, "{c}"); + } + for c in [ + CallerRejected, + SurrogateMissing, + SurrogateMalformed, + SurrogateUnknown, + SurrogateRevoked, + SurrogateExpired, + SurrogateWrongCaller, + SurrogateWrongRoute, + PolicyEmpty, + PolicyDenied, + ] { + assert_eq!(c.status(), 403, "{c}"); + } + assert_eq!(RouteUnknown.status(), 404); + assert_eq!(ConnectRefused.status(), 405); + assert_eq!(BodyTooLarge.status(), 413); + assert_eq!(WebsocketUnsupported.status(), 501); + assert_eq!(UpstreamUnavailable.status(), 502); + assert_eq!(PolicyUnavailable.status(), 503); + assert_eq!(BrokerUnavailable.status(), 503); + } + + #[test] + fn dialects() { + let (st, hs, body) = deny_parts(ErrorShape::Aws, Code::SurrogateRevoked); + assert_eq!(st, 403); + assert!(hs.contains(&("x-amzn-errortype", "AccessDeniedException".into()))); + let v: serde_json::Value = serde_json::from_str(&body).unwrap(); + assert_eq!(v["__type"], "AccessDeniedException"); + assert!(v["message"].as_str().unwrap().contains("surrogate_revoked")); + + let (st, _, body) = deny_parts(ErrorShape::Aws, Code::BrokerUnavailable); + assert_eq!(st, 503); + assert!(body.contains("ServiceUnavailableException")); + + let (_, hs, body) = deny_parts(ErrorShape::Json, Code::PolicyDenied); + assert!(hs.contains(&("content-type", "application/json".into()))); + let v: serde_json::Value = serde_json::from_str(&body).unwrap(); + assert_eq!(v["error"]["type"], "policy_denied"); + } +} diff --git a/crates/ap-core/src/config.rs b/crates/ap-core/src/config.rs new file mode 100644 index 0000000..223d135 --- /dev/null +++ b/crates/ap-core/src/config.rs @@ -0,0 +1,549 @@ +//! The Q3-A policy file: one TOML file per identity, validated as a whole. +//! +//! Any validation failure makes the whole file unusable (exit code 2 at +//! startup, `policy_unavailable` at reload). Unknown keys are errors. + +use crate::canon::canonical_host; +use crate::code::ErrorShape; +use crate::headers::{AUTH_HEADERS, HOP_HEADERS}; +use serde::Deserialize; +use std::collections::{HashMap, HashSet}; +use std::fmt; +use std::net::SocketAddr; +use std::path::PathBuf; +use std::str::FromStr; + +pub const MAX_GRANTS: usize = 256; +pub const MAX_CONFIG_BYTES: usize = 1024 * 1024; +const MAX_PASS_HEADERS: usize = 16; + +/// All validation failures of one file, reported together. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ConfigError(pub Vec); + +impl fmt::Display for ConfigError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.0.join("; ")) + } +} + +impl std::error::Error for ConfigError {} + +impl ConfigError { + fn one(msg: impl Into) -> ConfigError { + ConfigError(vec![msg.into()]) + } +} + +#[derive(Deserialize, Debug, Clone)] +#[serde(deny_unknown_fields)] +pub struct Config { + pub version: u32, + /// Audit name of the identity. + pub identity: String, + /// sha256 of the caller key, 64 lowercase hex. The key itself is never stored. + pub caller_key_sha256: String, + /// The single agent-facing listener. Optional: the binary may take it from + /// its command line. There is no way to configure a second one. + #[serde(default)] + pub listener: Option, + #[serde(default, rename = "route")] + pub routes: Vec, + #[serde(default, rename = "credential")] + pub credentials: Vec, + #[serde(default, rename = "grant")] + pub grants: Vec, + #[serde(default)] + pub egress: EgressCfg, +} + +#[derive(Deserialize, Debug, Clone)] +#[serde(deny_unknown_fields)] +pub struct ListenerCfg { + /// Must be a loopback address with a non-zero port (`P`). + pub listen: SocketAddr, + /// Exact `Host` values a client may send (DNS-rebinding defence). Default: + /// `127.0.0.1:P` and `localhost:P`. + #[serde(default)] + pub authorities: Vec, +} + +impl ListenerCfg { + pub fn effective_authorities(&self) -> Vec { + if self.authorities.is_empty() { + let p = self.listen.port(); + vec![format!("127.0.0.1:{p}"), format!("localhost:{p}")] + } else { + self.authorities.clone() + } + } +} + +#[derive(Deserialize, Debug, Clone)] +#[serde(deny_unknown_fields)] +pub struct RouteCfg { + pub name: String, + pub host: String, + #[serde(default = "d_port")] + pub port: u16, + /// Test-only resolver override (like curl --resolve). The destination + /// identity (SNI, Host, certificate name) is still `host`. The field exists + /// only in builds with the `test-resolve` feature; in every shipped build a + /// policy that sets it is rejected as an unknown key. + #[cfg(feature = "test-resolve")] + #[serde(default)] + pub connect_to: Option, + #[serde(default)] + pub error_shape: ErrorShape, + #[serde(default = "d_auth")] + pub surrogate_header: String, + #[serde(default = "d_bearer")] + pub surrogate_scheme: String, + #[serde(default = "d_auth")] + pub credential_header: String, + #[serde(default = "d_bearer")] + pub credential_scheme: String, + /// Request headers that must reach the upstream untouched. Stripping is a + /// deny list (auth and hop-by-hop headers), so these pass by construction; + /// the list is validated so it cannot name a stripped header. + #[serde(default)] + pub pass_headers: Vec, +} + +fn d_port() -> u16 { + 443 +} +fn d_auth() -> String { + "authorization".into() +} +fn d_bearer() -> String { + "Bearer".into() +} + +impl RouteCfg { + /// The resolver override of a `test-resolve` build; always `None` otherwise. + pub fn resolve_override(&self) -> Option { + #[cfg(feature = "test-resolve")] + { + self.connect_to + } + #[cfg(not(feature = "test-resolve"))] + { + None + } + } + + /// `Host` header value the upstream sees (port only when not 443). + pub fn authority(&self) -> String { + if self.port == 443 { + self.host.clone() + } else { + format!("{}:{}", self.host, self.port) + } + } +} + +#[derive(Deserialize, Debug, Clone)] +#[serde(deny_unknown_fields)] +pub struct CredentialCfg { + pub id: String, + pub source: CredentialSource, + pub routes: Vec, +} + +#[derive(Deserialize, Debug, Clone)] +#[serde(deny_unknown_fields)] +pub struct GrantCfg { + pub credential: String, + pub route: String, + pub methods: Vec, + /// Each entry starts and ends with `/` and matches by prefix. `/` alone + /// allows every path on the route. + pub paths: Vec, + /// Empty = no constraint. Otherwise exactly one `X-Amz-Target` header, + /// equal to one of these. + #[serde(default)] + pub aws_targets: Vec, +} + +#[derive(Deserialize, Debug, Clone, Default)] +#[serde(deny_unknown_fields)] +pub struct EgressCfg { + /// `host:port` entries for ap-egress. + #[serde(default)] + pub allow: Vec, +} + +impl EgressCfg { + /// Parsed entries. Only meaningful on a validated config. + pub fn entries(&self) -> Vec<(String, u16)> { + self.allow + .iter() + .filter_map(|e| parse_host_port(e).ok()) + .collect() + } +} + +/// Where a credential value comes from. Reference syntax follows octobroker: +/// `k8s::`, `file:`, `env:`. Phase 1 resolves +/// `k8s:` and `file:` (Secret files); `env:` parses only. `aws:secretsmanager:` +/// is deferred with the ECS rollout and rejected. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum CredentialSource { + K8s { secret: String, key: String }, + File(PathBuf), + Env(String), +} + +impl FromStr for CredentialSource { + type Err = String; + + fn from_str(s: &str) -> Result { + if let Some(rest) = s.strip_prefix("k8s:") { + let (secret, key) = rest + .split_once(':') + .ok_or("k8s source must be k8s::")?; + let secret_ok = !secret.is_empty() + && secret.len() <= 253 + && secret.bytes().all(|b| { + b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-' || b == b'.' + }) + && !secret.starts_with(['-', '.']) + && !secret.ends_with(['-', '.']); + let key_ok = !key.is_empty() + && key.len() <= 253 + && key != "." + && key != ".." + && key + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_' || b == b'.'); + if !secret_ok { + return Err("k8s source: bad secret name".into()); + } + if !key_ok { + return Err("k8s source: bad key name".into()); + } + Ok(CredentialSource::K8s { + secret: secret.into(), + key: key.into(), + }) + } else if let Some(p) = s.strip_prefix("file:") { + let ok = p.starts_with('/') + && p.len() <= 4096 + && !p.bytes().any(|b| b < 0x20 || b == 0x7f) + && !p.split('/').any(|seg| seg == ".."); + if !ok { + return Err("file source must be an absolute path without '..'".into()); + } + Ok(CredentialSource::File(PathBuf::from(p))) + } else if let Some(n) = s.strip_prefix("env:") { + let ok = !n.is_empty() + && n.len() <= 128 + && !n.as_bytes()[0].is_ascii_digit() + && n.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_'); + if !ok { + return Err("env source must be env: ([A-Za-z_][A-Za-z0-9_]*)".into()); + } + Ok(CredentialSource::Env(n.into())) + } else if s.starts_with("aws:") { + Err( + "aws: sources are deferred with the ECS rollout and not supported in Phase 1" + .into(), + ) + } else { + Err("unknown source scheme (expected k8s:, file: or env:)".into()) + } + } +} + +impl<'de> Deserialize<'de> for CredentialSource { + fn deserialize>(d: D) -> Result { + let s = String::deserialize(d)?; + s.parse().map_err(serde::de::Error::custom) + } +} + +/// `host:port` with a canonical host and a port from 1 to 65535. +pub fn parse_host_port(e: &str) -> Result<(String, u16), String> { + let (host, port) = e.rsplit_once(':').ok_or("expected host:port")?; + canonical_host(host).map_err(|m| format!("host rejected: {m}"))?; + if port.is_empty() || port.len() > 5 || !port.bytes().all(|b| b.is_ascii_digit()) { + return Err("port must be digits".into()); + } + match port.parse::() { + Ok(p) if p >= 1 => Ok((host.to_string(), p)), + _ => Err("port must be 1..=65535".into()), + } +} + +fn ident_ok(s: &str, max: usize, extra: &[u8]) -> bool { + !s.is_empty() + && s.len() <= max + && s.bytes() + .all(|b| b.is_ascii_alphanumeric() || extra.contains(&b)) +} + +fn route_name_ok(s: &str) -> bool { + !s.is_empty() + && s.len() <= 32 + && s.bytes() + .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-') +} + +fn lower_hex64(s: &str) -> bool { + s.len() == 64 + && s.bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) +} + +fn http_token(s: &str) -> bool { + !s.is_empty() + && s.len() <= 64 + && s.bytes() + .all(|b| b.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&b)) +} + +fn grant_path_err(p: &str) -> Option<&'static str> { + if !p.starts_with('/') { + return Some("must start with '/'"); + } + if !p.ends_with('/') { + return Some("must end with '/' (exact '/' or a prefix ending in '/')"); + } + if p.len() > 512 || !p.bytes().all(|b| (0x21..=0x7e).contains(&b)) { + return Some("must be printable ASCII, at most 512 bytes"); + } + if p.contains(['%', '\\', '?', '#']) { + return Some("must not contain '%', '\\', '?' or '#'"); + } + if p.contains("//") { + return Some("must not contain '//'"); + } + if p.split('/').any(|s| s == "." || s == "..") { + return Some("must not contain a dot segment"); + } + None +} + +impl Config { + /// Parse and validate. Never returns a config that failed validation. + pub fn parse(raw: &[u8]) -> Result { + if raw.len() > MAX_CONFIG_BYTES { + return Err(ConfigError::one("config larger than 1 MiB")); + } + let text = std::str::from_utf8(raw).map_err(|_| ConfigError::one("config is not UTF-8"))?; + let cfg: Config = + toml::from_str(text).map_err(|e| ConfigError::one(format!("parse: {e}")))?; + cfg.validate()?; + Ok(cfg) + } + + pub fn route(&self, name: &str) -> Option<&RouteCfg> { + self.routes.iter().find(|r| r.name == name) + } + + pub fn credential(&self, id: &str) -> Option<&CredentialCfg> { + self.credentials.iter().find(|c| c.id == id) + } + + pub fn validate(&self) -> Result<(), ConfigError> { + let mut errs: Vec = Vec::new(); + let mut e = |m: String| errs.push(m); + + if self.version != 1 { + e(format!("version must be 1, got {}", self.version)); + } + if !ident_ok(&self.identity, 64, b"._:-") { + e("identity must be 1-64 characters of [A-Za-z0-9._:-]".into()); + } + if !lower_hex64(&self.caller_key_sha256) { + e("caller_key_sha256 must be 64 lowercase hex characters".into()); + } + + if let Some(l) = &self.listener { + if !l.listen.ip().is_loopback() { + e(format!( + "listener.listen {} is not a loopback address", + l.listen + )); + } + if l.listen.port() == 0 { + e("listener.listen port must not be 0".into()); + } + for a in &l.authorities { + if a.is_empty() || a.len() > 255 || !a.bytes().all(|b| (0x21..=0x7e).contains(&b)) { + e(format!( + "listener.authorities entry {a:?} is not a plain Host value" + )); + } + } + } + + // routes + let mut route_names = HashSet::new(); + for r in &self.routes { + if !route_name_ok(&r.name) { + e(format!( + "route name {:?} must match [a-z0-9-]{{1,32}}", + r.name + )); + } else if !route_names.insert(r.name.as_str()) { + e(format!("route name {:?} is not unique", r.name)); + } + if let Err(m) = canonical_host(&r.host) { + e(format!("route {}: upstream host rejected: {m}", r.name)); + } + if r.port == 0 { + e(format!("route {}: port 0", r.name)); + } + for (what, h) in [ + ("surrogate_header", &r.surrogate_header), + ("credential_header", &r.credential_header), + ] { + if !AUTH_HEADERS.contains(&h.as_str()) { + e(format!( + "route {}: {what} {h:?} is not a known auth header", + r.name + )); + } + } + for (what, s) in [ + ("surrogate_scheme", &r.surrogate_scheme), + ("credential_scheme", &r.credential_scheme), + ] { + if !(s.is_empty() || http_token(s)) { + e(format!("route {}: {what} must be empty or a token", r.name)); + } + } + if r.pass_headers.len() > MAX_PASS_HEADERS { + e(format!( + "route {}: more than {MAX_PASS_HEADERS} pass_headers", + r.name + )); + } + for h in &r.pass_headers { + let lower_ok = *h == h.to_ascii_lowercase() && http_token(h); + if !lower_ok { + e(format!( + "route {}: pass_headers entry {h:?} must be a lowercase header name", + r.name + )); + } else if AUTH_HEADERS.contains(&h.as_str()) || HOP_HEADERS.contains(&h.as_str()) { + e(format!( + "route {}: pass_headers entry {h:?} is stripped by design", + r.name + )); + } + } + } + + // credentials + let mut cred_ids = HashSet::new(); + let route_host: HashMap<&str, &str> = self + .routes + .iter() + .map(|r| (r.name.as_str(), r.host.as_str())) + .collect(); + let mut credential_hosts: HashSet<&str> = HashSet::new(); + for c in &self.credentials { + if !ident_ok(&c.id, 64, b"._-") { + e(format!( + "credential id {:?} must be 1-64 characters of [A-Za-z0-9._-]", + c.id + )); + } else if !cred_ids.insert(c.id.as_str()) { + e(format!("credential id {:?} is not unique", c.id)); + } + if c.routes.is_empty() { + e(format!("credential {}: routes is empty", c.id)); + } + let mut seen = HashSet::new(); + for rn in &c.routes { + if !seen.insert(rn.as_str()) { + e(format!("credential {}: route {rn:?} listed twice", c.id)); + } + match route_host.get(rn.as_str()) { + Some(h) => { + credential_hosts.insert(*h); + } + None => e(format!("credential {}: route {rn:?} does not exist", c.id)), + } + } + } + + // grants + if self.grants.len() > MAX_GRANTS { + e(format!( + "more than {MAX_GRANTS} grants ({})", + self.grants.len() + )); + } + for (i, g) in self.grants.iter().enumerate() { + let at = format!("grant #{}", i + 1); + match self.credential(&g.credential) { + None => e(format!( + "{at}: credential {:?} does not exist", + g.credential + )), + Some(c) if !c.routes.contains(&g.route) => e(format!( + "{at}: route {:?} is not one of credential {:?}'s routes", + g.route, g.credential + )), + Some(_) => {} + } + if g.methods.is_empty() { + e(format!("{at}: methods is empty")); + } + for m in &g.methods { + let ok = !m.is_empty() + && m.len() <= 16 + && m.bytes() + .all(|b| b.is_ascii_uppercase() || b.is_ascii_digit() || b == b'-'); + if !ok { + e(format!("{at}: method {m:?} must be an upper-case token")); + } + } + if g.paths.is_empty() { + e(format!("{at}: paths is empty")); + } + for p in &g.paths { + if let Some(why) = grant_path_err(p) { + e(format!("{at}: path {p:?} {why}")); + } + } + for t in &g.aws_targets { + let ok = !t.is_empty() + && t.len() <= 128 + && t.bytes().all(|b| (0x21..=0x7e).contains(&b) && b != b','); + if !ok { + e(format!( + "{at}: aws_targets entry {t:?} must be a plain token without ','" + )); + } + } + } + + // egress + for ent in &self.egress.allow { + match parse_host_port(ent) { + Err(m) => e(format!("egress.allow entry {ent:?}: {m}")), + Ok((h, _)) => { + // Baseline rule, no opt-out: a CONNECT tunnel to a credential + // route host could carry another credential the agent found + // straight to that host. + if credential_hosts.contains(h.as_str()) { + e(format!( + "egress.allow entry {ent:?}: host is a credential route host" + )); + } + } + } + } + + if errs.is_empty() { + Ok(()) + } else { + Err(ConfigError(errs)) + } + } +} diff --git a/crates/ap-core/src/headers.rs b/crates/ap-core/src/headers.rs new file mode 100644 index 0000000..72f750d --- /dev/null +++ b/crates/ap-core/src/headers.rs @@ -0,0 +1,88 @@ +//! Header lists and request-header stripping, ported from the Phase 0 spike. + +use http::{header, HeaderMap, HeaderName}; + +/// Headers that can carry a credential. All are removed before forwarding; +/// then exactly one (the route's credential header) is set. +pub const AUTH_HEADERS: &[&str] = &[ + "authorization", + "proxy-authorization", + "x-api-key", + "x-goog-api-key", + "api-key", + "cookie", + "x-amz-security-token", +]; + +/// Hop-by-hop headers (RFC 9110 section 7.6.1) plus framing headers the +/// forwarder sets itself. +pub const HOP_HEADERS: &[&str] = &[ + "connection", + "keep-alive", + "proxy-connection", + "te", + "trailer", + "transfer-encoding", + "upgrade", + "host", + "content-length", +]; + +/// Remove hop-by-hop headers, headers named by `Connection`, and every auth +/// header. Everything else passes (so route `pass_headers` survive by +/// construction). +pub fn strip_request_headers(h: &mut HeaderMap) { + let named: Vec = h + .get_all(header::CONNECTION) + .iter() + .filter_map(|v| v.to_str().ok()) + .flat_map(|v| v.split(',')) + .filter_map(|n| HeaderName::from_bytes(n.trim().as_bytes()).ok()) + .collect(); + for n in named { + h.remove(n); + } + for n in HOP_HEADERS.iter().chain(AUTH_HEADERS) { + h.remove(*n); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use http::HeaderValue; + + #[test] + fn strips_auth_hop_and_connection_named() { + let mut h = HeaderMap::new(); + for (k, v) in [ + ("authorization", "Bearer x"), + ("x-api-key", "k"), + ("cookie", "c"), + ("x-amz-security-token", "t"), + ("connection", "close, x-secret-hop"), + ("x-secret-hop", "1"), + ("keep-alive", "5"), + ("tokentype", "API_KEY"), + ("x-amz-target", "Svc.Op"), + ] { + h.append(HeaderName::from_static(k), HeaderValue::from_static(v)); + } + h.append( + HeaderName::from_static("authorization"), + HeaderValue::from_static("Bearer y"), + ); + strip_request_headers(&mut h); + let left: Vec<&str> = h.keys().map(|k| k.as_str()).collect(); + assert_eq!(left.len(), 2, "{left:?}"); + assert!(h.contains_key("tokentype") && h.contains_key("x-amz-target")); + } + + #[test] + fn lists_are_lowercase() { + for n in AUTH_HEADERS.iter().chain(HOP_HEADERS) { + assert_eq!(*n, n.to_ascii_lowercase()); + assert!(HeaderName::from_bytes(n.as_bytes()).is_ok()); + } + } +} diff --git a/crates/ap-core/src/lib.rs b/crates/ap-core/src/lib.rs new file mode 100644 index 0000000..2bd2f68 --- /dev/null +++ b/crates/ap-core/src/lib.rs @@ -0,0 +1,28 @@ +//! auth-proxy core. No network I/O and no credential values. +//! +//! - `config`: the Q3-A policy file model and its validation +//! - `policy`: compiled snapshot, grant evaluation, the reloading store +//! - `canon`: host and path canonicalization, the `/ap/` prefix +//! - `code`: refusal codes, status mapping, error dialects +//! - `headers`: auth and hop-by-hop header lists and stripping +//! - `surrogate`: surrogate and caller-key formats, the registry hash +//! - `audit`: the audit record (cannot carry the caller-key prefix) + +pub mod audit; +pub mod canon; +pub mod code; +pub mod config; +pub mod headers; +pub mod policy; +pub mod stamp; +pub mod surrogate; +#[doc(hidden)] +pub mod testing; + +pub use audit::{AuditInput, AuditRec}; +pub use canon::{canonical_host, path_ambiguous, ApPath, RoutePath, VerifiedPath}; +pub use code::{deny_parts, Code, ErrorShape}; +pub use config::{Config, ConfigError, CredentialSource}; +pub use headers::{strip_request_headers, AUTH_HEADERS, HOP_HEADERS}; +pub use policy::{aws_target_ok, Policy, PolicyStore}; +pub use stamp::FileStamp; diff --git a/crates/ap-core/src/policy.rs b/crates/ap-core/src/policy.rs new file mode 100644 index 0000000..08ad588 --- /dev/null +++ b/crates/ap-core/src/policy.rs @@ -0,0 +1,511 @@ +//! Compiled policy snapshot, grant evaluation and the reloading store. + +use crate::code::Code; +use crate::config::{Config, ConfigError, CredentialCfg, RouteCfg, MAX_CONFIG_BYTES}; +use crate::stamp::FileStamp; +use sha2::{Digest, Sha256}; +use std::io::Read; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex}; +use subtle::ConstantTimeEq; + +/// An immutable, fully validated snapshot of one identity's policy file. +#[derive(Debug)] +pub struct Policy { + cfg: Config, + caller_sha256: [u8; 32], +} + +impl Policy { + pub fn parse(raw: &[u8]) -> Result { + Policy::from_config(Config::parse(raw)?) + } + + /// Re-validates, so a `Policy` always comes from a valid `Config`. + pub fn from_config(cfg: Config) -> Result { + cfg.validate()?; + let mut caller_sha256 = [0u8; 32]; + // validate() guarantees 64 lowercase hex characters. + hex::decode_to_slice(&cfg.caller_key_sha256, &mut caller_sha256) + .map_err(|e| ConfigError(vec![format!("caller_key_sha256: {e}")]))?; + Ok(Policy { cfg, caller_sha256 }) + } + + pub fn config(&self) -> &Config { + &self.cfg + } + + pub fn identity(&self) -> &str { + &self.cfg.identity + } + + pub fn route(&self, name: &str) -> Option<&RouteCfg> { + self.cfg.route(name) + } + + pub fn credential(&self, id: &str) -> Option<&CredentialCfg> { + self.cfg.credential(id) + } + + /// Constant-time check of a presented caller key against the stored hash. + pub fn caller_matches(&self, key: &str) -> bool { + let h: [u8; 32] = Sha256::digest(key.as_bytes()).into(); + bool::from(h.ct_eq(&self.caller_sha256)) + } + + /// No grant at all: nothing is allowed. + pub fn has_no_grants(&self) -> bool { + self.cfg.grants.is_empty() + } + + /// Evaluate grants for a request whose surrogate is bound to + /// `session_credentials`. `path` is the route-relative path (no query, + /// already checked for ambiguity). `aws_targets` holds the value of every + /// `X-Amz-Target` header the request carried. + /// + /// Returns the id of the credential whose grant allows the request. + pub fn authorize( + &self, + session_credentials: &[String], + route: &str, + method: &str, + path: &str, + aws_targets: &[&[u8]], + ) -> Result<&str, Code> { + if self.cfg.grants.is_empty() { + return Err(Code::PolicyEmpty); + } + self.cfg + .grants + .iter() + .find(|g| { + g.route == route + && session_credentials.contains(&g.credential) + && g.methods.iter().any(|m| m == method) + && g.paths.iter().any(|p| path.starts_with(p.as_str())) + && aws_target_ok(&g.aws_targets, aws_targets) + }) + .map(|g| g.credential.as_str()) + .ok_or(Code::PolicyDenied) + } +} + +/// The `aws_targets` matcher. An empty list is no constraint. Otherwise the +/// request must carry exactly one `X-Amz-Target` value, equal to an entry: +/// zero headers and two headers (even two equal ones) both deny. +pub fn aws_target_ok(allowed: &[String], presented: &[&[u8]]) -> bool { + if allowed.is_empty() { + return true; + } + match presented { + [one] => allowed.iter().any(|a| a.as_bytes() == *one), + _ => false, + } +} + +struct State { + good: Option<(FileStamp, Arc)>, + /// A file that failed to parse or validate, keyed by its stamp, so an + /// unchanged bad file is not re-parsed per request. I/O errors are never + /// cached: the next request tries again. + bad: Option, + last_error: Option, +} + +/// Re-reads the policy file when its mtime, size or inode changes. Any stat, +/// read, parse or validation failure makes the policy unavailable, which +/// refuses every request: a good snapshot is never kept after the file has gone +/// bad. Readers get an `Arc` to one immutable snapshot, so a swap is atomic. +pub struct PolicyStore { + path: PathBuf, + state: Mutex, +} + +impl PolicyStore { + pub fn new(path: impl Into) -> PolicyStore { + PolicyStore { + path: path.into(), + state: Mutex::new(State { + good: None, + bad: None, + last_error: None, + }), + } + } + + /// Startup form: load now, and fail with the validation error (exit code 2). + pub fn open(path: impl Into) -> Result { + let s = PolicyStore::new(path); + s.refresh()?; + Ok(s) + } + + pub fn path(&self) -> &Path { + &self.path + } + + /// The snapshot for this request, or `policy_unavailable`. + pub fn current(&self) -> Result, Code> { + self.refresh().map_err(|_| Code::PolicyUnavailable) + } + + /// Why the policy is unavailable, for the operator's log (never contains a + /// secret: the file holds hashes and references only). + pub fn last_error(&self) -> Option { + self.state.lock().unwrap().last_error.clone() + } + + fn refresh(&self) -> Result, String> { + let mut st = self.state.lock().unwrap(); + let outcome = self.refresh_locked(&mut st); + st.last_error = outcome.as_ref().err().cloned(); + outcome + } + + fn refresh_locked(&self, st: &mut State) -> Result, String> { + let mut file = match std::fs::File::open(&self.path) { + Ok(f) => f, + Err(e) => { + st.good = None; + st.bad = None; + return Err(format!("open policy: {e}")); + } + }; + // Stat the open handle so the stamp describes the bytes we read. + let stamp = match file.metadata() { + Ok(md) => FileStamp::of(&md), + Err(e) => { + st.good = None; + st.bad = None; + return Err(format!("stat policy: {e}")); + } + }; + if let Some((s, p)) = &st.good { + if *s == stamp { + return Ok(p.clone()); + } + } + if st.bad == Some(stamp) { + st.good = None; + return Err(st + .last_error + .clone() + .unwrap_or_else(|| "policy invalid".into())); + } + let mut raw = Vec::new(); + if let Err(e) = (&mut file) + .take(MAX_CONFIG_BYTES as u64 + 1) + .read_to_end(&mut raw) + { + st.good = None; + st.bad = None; + return Err(format!("read policy: {e}")); + } + match Policy::parse(&raw) { + Ok(p) => { + let p = Arc::new(p); + st.good = Some((stamp, p.clone())); + st.bad = None; + Ok(p) + } + Err(e) => { + st.good = None; + st.bad = Some(stamp); + Err(e.to_string()) + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::testing::{sample_toml, SAMPLE_CALLER_KEY}; + use std::fs; + use std::time::{Duration, SystemTime}; + + fn tmpdir(tag: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("ap-core-{tag}-{}", std::process::id())); + let _ = fs::remove_dir_all(&d); + fs::create_dir_all(&d).unwrap(); + d + } + + /// Write and force a distinct mtime so the test does not depend on clock + /// granularity. + fn write(path: &Path, content: &str, n: u64) { + fs::write(path, content).unwrap(); + let f = fs::OpenOptions::new().write(true).open(path).unwrap(); + f.set_modified(SystemTime::UNIX_EPOCH + Duration::from_secs(1_700_000_000 + n)) + .unwrap(); + } + + /// Replace the file in one rename, as kubelet does, so a reader never sees + /// a half-written file. + fn write_atomic(path: &Path, content: &str, n: u64) { + let tmp = path.with_extension("tmp"); + write(&tmp, content, n); + fs::rename(&tmp, path).unwrap(); + } + + fn sample() -> Policy { + Policy::parse(sample_toml().as_bytes()).unwrap() + } + + #[test] + fn caller_key_constant_time_compare_semantics() { + let p = sample(); + assert!(p.caller_matches(SAMPLE_CALLER_KEY)); + assert!(!p.caller_matches("apk_x")); + assert!(!p.caller_matches("")); + assert!(!p.caller_matches(&SAMPLE_CALLER_KEY.to_uppercase())); + } + + #[test] + fn aws_targets_matcher() { + let allowed = vec!["Svc.A".to_string(), "Svc.B".to_string()]; + assert!(aws_target_ok(&allowed, &[b"Svc.A"])); + assert!(aws_target_ok(&allowed, &[b"Svc.B"])); + assert!(!aws_target_ok(&allowed, &[b"Svc.C"])); + assert!(!aws_target_ok(&allowed, &[]), "zero headers deny"); + assert!( + !aws_target_ok(&allowed, &[b"Svc.A", b"Svc.A"]), + "two headers deny" + ); + assert!(!aws_target_ok(&allowed, &[b"Svc.A", b"Svc.C"])); + assert!(!aws_target_ok(&allowed, &[b"Svc.A, Svc.B"])); + assert!( + !aws_target_ok(&allowed, &[b"svc.a"]), + "exact, case-sensitive" + ); + assert!(aws_target_ok(&[], &[]), "no constraint without aws_targets"); + assert!(aws_target_ok(&[], &[b"x", b"y"])); + } + + #[test] + fn authorize_decisions() { + let p = sample(); + let kiro = vec!["kiro".to_string()]; + let target: &[&[u8]] = &[b"AmazonCodeWhispererStreamingService.GenerateAssistantResponse"]; + assert_eq!( + p.authorize(&kiro, "kiro-krs", "POST", "/", target), + Ok("kiro") + ); + // wrong target, none, two + assert_eq!( + p.authorize(&kiro, "kiro-krs", "POST", "/", &[b"Other.Op"]), + Err(Code::PolicyDenied) + ); + assert_eq!( + p.authorize(&kiro, "kiro-krs", "POST", "/", &[]), + Err(Code::PolicyDenied) + ); + assert_eq!( + p.authorize(&kiro, "kiro-krs", "POST", "/", &[target[0], target[0]]), + Err(Code::PolicyDenied) + ); + // wrong method, other route without grant, session without the credential + assert_eq!( + p.authorize(&kiro, "kiro-krs", "GET", "/", target), + Err(Code::PolicyDenied) + ); + assert_eq!( + p.authorize(&kiro, "kiro-q", "POST", "/", target), + Err(Code::PolicyDenied) + ); + assert_eq!( + p.authorize(&[], "kiro-krs", "POST", "/", target), + Err(Code::PolicyDenied) + ); + // prefix grant on the anthropic route + let ant = vec!["anthropic".to_string()]; + assert_eq!( + p.authorize(&ant, "anthropic", "POST", "/v1/messages", &[]), + Ok("anthropic") + ); + assert_eq!( + p.authorize(&ant, "anthropic", "POST", "/v1/", &[]), + Ok("anthropic") + ); + assert_eq!( + p.authorize(&ant, "anthropic", "POST", "/v1", &[]), + Err(Code::PolicyDenied) + ); + assert_eq!( + p.authorize(&ant, "anthropic", "POST", "/v2/x", &[]), + Err(Code::PolicyDenied) + ); + assert_eq!( + p.authorize(&ant, "anthropic", "DELETE", "/v1/messages", &[]), + Err(Code::PolicyDenied) + ); + } + + #[test] + fn empty_policy_denies_with_policy_empty() { + let p = Policy::parse( + format!( + "version = 1\nidentity = \"x\"\ncaller_key_sha256 = \"{}\"\n", + crate::testing::SAMPLE_CALLER_SHA256 + ) + .as_bytes(), + ) + .unwrap(); + assert!(p.has_no_grants()); + assert_eq!( + p.authorize(&["kiro".into()], "kiro-krs", "POST", "/", &[]), + Err(Code::PolicyEmpty) + ); + } + + // ---- R1 cases (ported from the spike matrix) ---- + + #[test] + fn store_r1_zero_bytes_corrupt_deleted_other_path_and_recovery() { + let d = tmpdir("r1"); + let f = d.join("policy.toml"); + let good = sample_toml(); + + write(&f, &good, 1); + let store = PolicyStore::open(&f).unwrap(); + assert_eq!(store.current().unwrap().identity(), "pty-team-a"); + + // 0 bytes + write(&f, "", 2); + assert_eq!(store.current().unwrap_err(), Code::PolicyUnavailable); + assert!(store.last_error().is_some()); + // unchanged bad file stays unavailable (and is not re-parsed into good) + assert_eq!(store.current().unwrap_err(), Code::PolicyUnavailable); + + // recovery on restore + write(&f, &good, 3); + assert!(store.current().is_ok()); + assert!(store.last_error().is_none()); + + // corrupt + write(&f, "this is = = not toml [[", 4); + assert_eq!(store.current().unwrap_err(), Code::PolicyUnavailable); + // valid TOML, failed validation (route name upper-case) + write( + &f, + &good.replace("name = \"anthropic\"", "name = \"Anthropic\""), + 5, + ); + assert_eq!(store.current().unwrap_err(), Code::PolicyUnavailable); + write(&f, &good, 6); + assert!(store.current().is_ok()); + + // deleted after a good load: never serve the stale snapshot + fs::remove_file(&f).unwrap(); + assert_eq!(store.current().unwrap_err(), Code::PolicyUnavailable); + write(&f, &good, 7); + assert!(store.current().is_ok()); + + // grants for another path or method only: valid, but denies + let other = good.replace( + "methods = [\"POST\"]\npaths = [\"/v1/\"]", + "methods = [\"GET\"]\npaths = [\"/models/\"]", + ); + assert_ne!(other, good); + write(&f, &other, 8); + let p = store.current().unwrap(); + assert_eq!( + p.authorize( + &["anthropic".into()], + "anthropic", + "POST", + "/v1/messages", + &[] + ), + Err(Code::PolicyDenied) + ); + let _ = fs::remove_dir_all(&d); + } + + #[test] + fn store_open_fails_on_bad_file_and_missing_file() { + let d = tmpdir("open"); + let f = d.join("policy.toml"); + assert!(PolicyStore::open(&f).is_err(), "missing"); + write(&f, "", 1); + assert!(PolicyStore::open(&f).is_err(), "0 bytes"); + write(&f, "version = 2\n", 2); + assert!(PolicyStore::open(&f).is_err(), "bad"); + let _ = fs::remove_dir_all(&d); + } + + #[test] + fn store_detects_atomic_symlink_swap_with_same_size_and_mtime() { + // ConfigMap layout: policy.toml -> ..data/policy.toml, ..data -> ..vN + #[cfg(unix)] + { + use std::os::unix::fs::symlink; + let d = tmpdir("swap"); + let a = sample_toml(); + let b = sample_toml().replace("pty-team-a", "pty-team-b"); + assert_eq!(a.len(), b.len()); + fs::create_dir(d.join("..v1")).unwrap(); + fs::create_dir(d.join("..v2")).unwrap(); + write(&d.join("..v1/policy.toml"), &a, 1); + write(&d.join("..v2/policy.toml"), &b, 1); + symlink("..v1", d.join("..data")).unwrap(); + symlink("..data/policy.toml", d.join("policy.toml")).unwrap(); + let store = PolicyStore::open(d.join("policy.toml")).unwrap(); + assert_eq!(store.current().unwrap().identity(), "pty-team-a"); + symlink("..v2", d.join("..data_tmp")).unwrap(); + fs::rename(d.join("..data_tmp"), d.join("..data")).unwrap(); + assert_eq!(store.current().unwrap().identity(), "pty-team-b"); + let _ = fs::remove_dir_all(&d); + } + } + + #[test] + fn no_half_applied_swap_under_concurrent_requests() { + let d = tmpdir("conc"); + let f = d.join("policy.toml"); + let a = sample_toml(); + let b = sample_toml().replace("pty-team-a", "pty-team-b"); + write_atomic(&f, &a, 1); + let store = Arc::new(PolicyStore::open(&f).unwrap()); + let stop = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let readers: Vec<_> = (0..4) + .map(|_| { + let (s, stop) = (store.clone(), stop.clone()); + std::thread::spawn(move || { + let mut seen = 0u32; + // do-while: observe at least once even if the writer finishes before + // this thread is first scheduled (seen on a 4-core aarch64 host) + loop { + match s.current() { + Ok(p) => { + // a snapshot is internally consistent: identity and grants + // always come from the same file + assert!(["pty-team-a", "pty-team-b"].contains(&p.identity())); + assert_eq!(p.config().grants.len(), 3); + assert!(p.caller_matches(SAMPLE_CALLER_KEY)); + } + Err(c) => assert_eq!(c, Code::PolicyUnavailable), + } + seen += 1; + if stop.load(std::sync::atomic::Ordering::Relaxed) { + break; + } + } + seen + }) + }) + .collect(); + for i in 0..60u64 { + if i % 7 == 6 { + write_atomic(&f, "", 10 + i); + } else { + write_atomic(&f, if i % 2 == 0 { &a } else { &b }, 10 + i); + } + } + stop.store(true, std::sync::atomic::Ordering::Relaxed); + for r in readers { + assert!(r.join().unwrap() > 0); + } + let _ = fs::remove_dir_all(&d); + } +} diff --git a/crates/ap-core/src/stamp.rs b/crates/ap-core/src/stamp.rs new file mode 100644 index 0000000..91c6eb9 --- /dev/null +++ b/crates/ap-core/src/stamp.rs @@ -0,0 +1,33 @@ +//! A cheap change detector for files that are re-read when they change. + +use std::fs::Metadata; +use std::time::{SystemTime, UNIX_EPOCH}; + +/// mtime, size and (on Unix) device and inode. Kubelet replaces Secret and +/// ConfigMap contents by flipping a symlink to a new directory, which gives +/// the file a new inode even when mtime and size happen to match. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub struct FileStamp { + mtime: SystemTime, + len: u64, + dev: u64, + ino: u64, +} + +impl FileStamp { + pub fn of(md: &Metadata) -> FileStamp { + #[cfg(unix)] + let (dev, ino) = { + use std::os::unix::fs::MetadataExt; + (md.dev(), md.ino()) + }; + #[cfg(not(unix))] + let (dev, ino) = (0, 0); + FileStamp { + mtime: md.modified().unwrap_or(UNIX_EPOCH), + len: md.len(), + dev, + ino, + } + } +} diff --git a/crates/ap-core/src/surrogate.rs b/crates/ap-core/src/surrogate.rs new file mode 100644 index 0000000..5324b8d --- /dev/null +++ b/crates/ap-core/src/surrogate.rs @@ -0,0 +1,64 @@ +//! Surrogate and caller-key formats. +//! +//! A surrogate is `aps_` + 64 lowercase hex, a caller key `apk_` + 64 lowercase +//! hex. The registry is keyed by `sha256` of the whole surrogate string, +//! including the `aps_` prefix, exactly as the CLI presents it in its +//! credential slot. The session authority must hash the same bytes. + +use crate::code::Code; +use sha2::{Digest, Sha256}; + +fn prefixed_hex64(s: &str, prefix: &str) -> bool { + s.len() == prefix.len() + 64 + && s.starts_with(prefix) + && s[prefix.len()..] + .bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) +} + +pub fn is_surrogate(s: &str) -> bool { + prefixed_hex64(s, "aps_") +} + +pub fn is_caller_key(s: &str) -> bool { + prefixed_hex64(s, "apk_") +} + +/// The registry key for a presented surrogate, or `surrogate_malformed`. +pub fn hash_surrogate(s: &str) -> Result<[u8; 32], Code> { + if is_surrogate(s) { + Ok(Sha256::digest(s.as_bytes()).into()) + } else { + Err(Code::SurrogateMalformed) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn formats() { + let ok = format!("aps_{}", "0123456789abcdef".repeat(4)); + assert!(is_surrogate(&ok)); + assert!(hash_surrogate(&ok).is_ok()); + for bad in [ + "".to_string(), + "aps_".to_string(), + format!("aps_{}", "0".repeat(63)), + format!("aps_{}", "0".repeat(65)), + format!("aps_{}", "A".repeat(64)), + format!("apk_{}", "0".repeat(64)), + format!("aps_{}g", "0".repeat(63)), + format!(" aps_{}", "0".repeat(64)), + ] { + assert_eq!( + hash_surrogate(&bad), + Err(Code::SurrogateMalformed), + "{bad:?}" + ); + } + assert!(is_caller_key(&format!("apk_{}", "f".repeat(64)))); + assert!(!is_caller_key(&format!("aps_{}", "f".repeat(64)))); + } +} diff --git a/crates/ap-core/src/testing.rs b/crates/ap-core/src/testing.rs new file mode 100644 index 0000000..553d4bc --- /dev/null +++ b/crates/ap-core/src/testing.rs @@ -0,0 +1,96 @@ +//! Fixtures shared by the workspace's tests. Sample values only: the hosts, +//! secret names and the caller key below are made up. + +pub const SAMPLE_CALLER_KEY: &str = + "apk_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; +pub const SAMPLE_CALLER_SHA256: &str = + "568d4a822d8e13b84959ce5e7ae2ca69ea3698da858dba712b49c022886de406"; + +/// The design doc's Q3-A sketch with sample values: two credentials, five +/// routes, three grants (one with `aws_targets`), an egress allowlist. +pub fn sample_toml() -> String { + format!( + r#"version = 1 +identity = "pty-team-a" +caller_key_sha256 = "{SAMPLE_CALLER_SHA256}" + +[[route]] +name = "anthropic" +host = "api.anthropic.com" +surrogate_header = "x-api-key" +surrogate_scheme = "" +credential_header = "x-api-key" +credential_scheme = "" + +[[route]] +name = "kiro-cps" +host = "profile.us-east-1.kiro.dev" +error_shape = "aws" + +[[route]] +name = "kiro-krs" +host = "runtime.us-east-1.kiro.dev" +error_shape = "aws" +surrogate_header = "authorization" +credential_header = "authorization" +pass_headers = ["tokentype"] + +[[route]] +name = "kiro-cw" +host = "cw.us-east-1.kiro.dev" +error_shape = "aws" + +[[route]] +name = "kiro-q" +host = "api.q.service" +error_shape = "aws" + +[[credential]] +id = "anthropic" +source = "k8s:auth-proxy-anthropic:api_key" +routes = ["anthropic"] + +[[credential]] +id = "kiro" +source = "k8s:auth-proxy-kiro:api_key" +routes = ["kiro-cps", "kiro-krs", "kiro-cw", "kiro-q"] + +[[grant]] +credential = "anthropic" +route = "anthropic" +methods = ["POST"] +paths = ["/v1/"] + +[[grant]] +credential = "kiro" +route = "kiro-krs" +methods = ["POST"] +paths = ["/"] +aws_targets = ["AmazonCodeWhispererStreamingService.GenerateAssistantResponse"] + +[[grant]] +credential = "kiro" +route = "kiro-cps" +methods = ["POST"] +paths = ["/"] + +[egress] +allow = ["github.com:443", "registry.npmjs.org:443", "pypi.org:443", + "files.pythonhosted.org:443", "index.crates.io:443", "static.crates.io:443"] +"# + ) +} + +#[cfg(test)] +mod tests { + use super::*; + use sha2::{Digest, Sha256}; + + #[test] + fn sample_hash_matches_sample_key() { + assert_eq!( + hex::encode(Sha256::digest(SAMPLE_CALLER_KEY.as_bytes())), + SAMPLE_CALLER_SHA256 + ); + } +} diff --git a/crates/ap-core/tests/config.rs b/crates/ap-core/tests/config.rs new file mode 100644 index 0000000..e9f8c83 --- /dev/null +++ b/crates/ap-core/tests/config.rs @@ -0,0 +1,534 @@ +//! Q3-A validation: the doc sketch is accepted, every listed rule rejects. + +use ap_core::config::{parse_host_port, Config, CredentialSource}; +use ap_core::testing::{sample_toml, SAMPLE_CALLER_SHA256}; + +fn rejects(label: &str, from: &str, to: &str, needle: &str) { + let base = sample_toml(); + assert!(base.contains(from), "{label}: fixture lacks {from:?}"); + let mutated = base.replacen(from, to, 1); + let err = Config::parse(mutated.as_bytes()).expect_err(label); + let msg = err.to_string(); + assert!(msg.contains(needle), "{label}: {msg:?} lacks {needle:?}"); +} + +fn rejects_append(label: &str, extra: &str, needle: &str) { + let mutated = format!("{}\n{extra}", sample_toml()); + let err = Config::parse(mutated.as_bytes()).expect_err(label); + let msg = err.to_string(); + assert!(msg.contains(needle), "{label}: {msg:?} lacks {needle:?}"); +} + +#[test] +fn accepts_the_doc_sketch() { + let c = Config::parse(sample_toml().as_bytes()).unwrap(); + assert_eq!(c.version, 1); + assert_eq!(c.identity, "pty-team-a"); + assert_eq!(c.caller_key_sha256, SAMPLE_CALLER_SHA256); + assert_eq!(c.routes.len(), 5); + assert_eq!(c.credentials.len(), 2); + assert_eq!(c.grants.len(), 3); + assert_eq!(c.egress.entries().len(), 6); + assert_eq!( + c.credential("kiro").unwrap().source, + CredentialSource::K8s { + secret: "auth-proxy-kiro".into(), + key: "api_key".into() + } + ); + let krs = c.route("kiro-krs").unwrap(); + assert_eq!(krs.port, 443); + assert_eq!(krs.credential_scheme, "Bearer"); + assert_eq!(krs.pass_headers, ["tokentype"]); + assert_eq!(krs.authority(), "runtime.us-east-1.kiro.dev"); +} + +#[test] +fn rejects_top_level() { + rejects("version", "version = 1", "version = 2", "version must be 1"); + rejects( + "identity", + "identity = \"pty-team-a\"", + "identity = \"a b\"", + "identity", + ); + rejects( + "identity empty", + "identity = \"pty-team-a\"", + "identity = \"\"", + "identity", + ); + rejects( + "hash length", + SAMPLE_CALLER_SHA256, + &SAMPLE_CALLER_SHA256[..63], + "64 lowercase hex", + ); + rejects( + "hash upper-case", + SAMPLE_CALLER_SHA256, + &SAMPLE_CALLER_SHA256.to_uppercase(), + "64 lowercase hex", + ); + rejects_append("unknown top-level key", "bogus = 1", "unknown field"); + rejects_append( + "unknown route key", + "[[route]]\nname = \"x\"\nhost = \"a.b\"\nbogus = 1", + "unknown field", + ); +} + +#[test] +fn rejects_routes() { + rejects( + "route name case", + "name = \"anthropic\"", + "name = \"Anthropic\"", + "route name", + ); + rejects( + "route name empty", + "name = \"anthropic\"", + "name = \"\"", + "route name", + ); + rejects( + "route name too long", + "name = \"anthropic\"", + &format!("name = \"{}\"", "a".repeat(33)), + "route name", + ); + rejects( + "route name underscore", + "name = \"kiro-q\"", + "name = \"kiro_q\"", + "route name", + ); + rejects( + "route name duplicate", + "name = \"kiro-q\"", + "name = \"kiro-cw\"", + "not unique", + ); + for (label, host) in [ + ("ip literal", "127.0.0.1"), + ("ipv6", "[::1]"), + ("numeric tld", "127.1"), + ("userinfo", "user@api.x.com"), + ("port", "api.x.com:443"), + ("trailing dot", "api.x.com."), + ("upper", "API.x.com"), + ("single label", "localhost"), + ("empty label", "a..b"), + ] { + rejects( + label, + "host = \"api.anthropic.com\"", + &format!("host = \"{host}\""), + "upstream host rejected", + ); + } + rejects( + "port 0", + "host = \"api.anthropic.com\"", + "host = \"api.anthropic.com\"\nport = 0", + "port 0", + ); + rejects( + "unknown surrogate header", + "surrogate_header = \"x-api-key\"", + "surrogate_header = \"x-custom\"", + "not a known auth header", + ); + rejects( + "unknown credential header", + "credential_header = \"x-api-key\"", + "credential_header = \"x-custom\"", + "not a known auth header", + ); + rejects( + "pass header stripped", + "pass_headers = [\"tokentype\"]", + "pass_headers = [\"authorization\"]", + "stripped by design", + ); + rejects( + "pass header hop", + "pass_headers = [\"tokentype\"]", + "pass_headers = [\"host\"]", + "stripped by design", + ); + rejects( + "pass header upper", + "pass_headers = [\"tokentype\"]", + "pass_headers = [\"TokenType\"]", + "lowercase header name", + ); + rejects( + "bad scheme", + "surrogate_scheme = \"\"", + "surrogate_scheme = \"Bearer x\"", + "surrogate_scheme", + ); +} + +#[test] +fn rejects_credentials() { + rejects( + "credential route missing", + "routes = [\"anthropic\"]", + "routes = [\"nope\"]", + "does not exist", + ); + rejects( + "credential routes empty", + "routes = [\"anthropic\"]", + "routes = []", + "routes is empty", + ); + rejects( + "credential route twice", + "routes = [\"anthropic\"]", + "routes = [\"anthropic\", \"anthropic\"]", + "listed twice", + ); + rejects( + "credential id dup", + "id = \"anthropic\"", + "id = \"kiro\"", + "not unique", + ); + rejects( + "credential id bad", + "id = \"anthropic\"", + "id = \"a b\"", + "credential id", + ); + for (label, src, needle) in [ + ("aws deferred", "aws:secretsmanager:prod/key", "deferred"), + ("unknown scheme", "vault:x", "unknown source scheme"), + ("k8s no key", "k8s:only-secret", "k8s::"), + ("k8s upper secret", "k8s:Bad:key", "bad secret name"), + ("k8s dotdot key", "k8s:s:..", "bad key name"), + ("k8s slash key", "k8s:s:a/b", "bad key name"), + ("file relative", "file:rel/path", "absolute path"), + ("file dotdot", "file:/a/../b", "absolute path"), + ("env digit", "env:1X", "env:"), + ("env empty", "env:", "env:"), + ] { + rejects( + label, + "source = \"k8s:auth-proxy-anthropic:api_key\"", + &format!("source = \"{src}\""), + needle, + ); + } +} + +#[test] +fn accepts_file_and_env_source_syntax() { + for src in [ + "file:/run/secrets/key", + "env:ANTHROPIC_API_KEY", + "k8s:s.v1:k_2", + ] { + let t = sample_toml().replacen( + "source = \"k8s:auth-proxy-anthropic:api_key\"", + &format!("source = \"{src}\""), + 1, + ); + Config::parse(t.as_bytes()).unwrap_or_else(|e| panic!("{src}: {e}")); + } +} + +#[test] +fn rejects_grants() { + rejects( + "grant credential missing", + "credential = \"anthropic\"\nroute = \"anthropic\"", + "credential = \"ghost\"\nroute = \"anthropic\"", + "credential \"ghost\" does not exist", + ); + rejects( + "grant route not in credential", + "credential = \"anthropic\"\nroute = \"anthropic\"", + "credential = \"anthropic\"\nroute = \"kiro-q\"", + "is not one of credential", + ); + rejects( + "methods lower-case", + "methods = [\"POST\"]\npaths = [\"/v1/\"]", + "methods = [\"post\"]\npaths = [\"/v1/\"]", + "upper-case token", + ); + rejects( + "methods empty", + "methods = [\"POST\"]\npaths = [\"/v1/\"]", + "methods = []\npaths = [\"/v1/\"]", + "methods is empty", + ); + rejects( + "paths empty", + "paths = [\"/v1/\"]", + "paths = []", + "paths is empty", + ); + for (label, p, needle) in [ + ("no leading slash", "v1/", "must start with '/'"), + ("no trailing slash", "/v1", "must end with '/'"), + ("dot segment", "/v1/./x/", "dot segment"), + ("dotdot segment", "/v1/../x/", "dot segment"), + ("percent", "/v1/%2e/", "'%'"), + ("double slash", "/v1//x/", "'//'"), + ("backslash", "/v1\\\\x/", "must not contain '%'"), + ("query", "/v1/?x/", "'?'"), + ("non-ascii", "/v1/é/", "printable ASCII"), + ] { + rejects( + label, + "paths = [\"/v1/\"]", + &format!("paths = [\"{p}\"]"), + needle, + ); + } + rejects( + "aws target comma", + "aws_targets = [\"AmazonCodeWhispererStreamingService.GenerateAssistantResponse\"]", + "aws_targets = [\"A.b, C.d\"]", + "aws_targets", + ); + rejects( + "aws target empty", + "aws_targets = [\"AmazonCodeWhispererStreamingService.GenerateAssistantResponse\"]", + "aws_targets = [\"\"]", + "aws_targets", + ); +} + +#[test] +fn grant_count_limit_is_256() { + let grant = "\n[[grant]]\ncredential = \"anthropic\"\nroute = \"anthropic\"\nmethods = [\"POST\"]\npaths = [\"/v1/\"]\n"; + // the sample has 3 grants + let ok = format!("{}{}", sample_toml(), grant.repeat(253)); + assert_eq!(Config::parse(ok.as_bytes()).unwrap().grants.len(), 256); + let too_many = format!("{}{}", sample_toml(), grant.repeat(254)); + let e = Config::parse(too_many.as_bytes()).unwrap_err().to_string(); + assert!(e.contains("more than 256 grants"), "{e}"); +} + +#[test] +fn rejects_egress() { + for (label, entry, needle) in [ + ("no port", "github.com", "host:port"), + ("port 0", "github.com:0", "1..=65535"), + ("port too big", "github.com:65536", "1..=65535"), + ("port non-digit", "github.com:44x", "digits"), + ("port plus", "github.com:+443", "digits"), + ("ip literal", "10.0.0.1:443", "host rejected"), + ("ipv6", "[::1]:443", "host rejected"), + ("upper host", "GitHub.com:443", "host rejected"), + ("userinfo", "u@github.com:443", "host rejected"), + ("trailing dot", "github.com.:443", "host rejected"), + ( + "credential route host", + "api.anthropic.com:443", + "credential route host", + ), + ( + "credential route host other port", + "runtime.us-east-1.kiro.dev:8443", + "credential route host", + ), + ] { + rejects( + label, + "allow = [\"github.com:443\",", + &format!("allow = [\"{entry}\","), + needle, + ); + } + // There is no opt-out: the former `egress.allow_route_hosts` key is an unknown + // field, so a policy that sets it (to allow a route host, or alone) is rejected. + for (label, t) in [ + ( + "opt-out with a route host", + sample_toml() + .replacen( + "allow = [\"github.com:443\",", + "allow = [\"api.anthropic.com:443\",", + 1, + ) + .replacen("[egress]", "[egress]\nallow_route_hosts = true", 1), + ), + ( + "opt-out alone", + sample_toml().replacen("[egress]", "[egress]\nallow_route_hosts = true", 1), + ), + ( + "opt-out false", + sample_toml().replacen("[egress]", "[egress]\nallow_route_hosts = false", 1), + ), + ] { + let e = Config::parse(t.as_bytes()).expect_err(label).to_string(); + assert!(e.contains("allow_route_hosts"), "{label}: {e}"); + } +} + +#[test] +fn route_host_check_only_covers_routes_used_by_a_credential() { + // a route that no credential references does not block an egress entry + let t = sample_toml().replacen( + "allow = [\"github.com:443\",", + "allow = [\"unused.example.com:443\",", + 1, + ) + "\n[[route]]\nname = \"unused\"\nhost = \"unused.example.com\"\n"; + Config::parse(t.as_bytes()).unwrap(); +} + +#[test] +fn listener_is_one_loopback_address_only() { + let with = |l: &str| format!("{}\n{l}", sample_toml()); + let ok = with("[listener]\nlisten = \"127.0.0.1:18080\""); + let c = Config::parse(ok.as_bytes()).unwrap(); + assert_eq!( + c.listener.unwrap().effective_authorities(), + ["127.0.0.1:18080", "localhost:18080"] + ); + Config::parse(with("[listener]\nlisten = \"[::1]:18080\"").as_bytes()).unwrap(); + for (label, l, needle) in [ + ( + "all interfaces", + "[listener]\nlisten = \"0.0.0.0:8080\"", + "not a loopback", + ), + ( + "lan", + "[listener]\nlisten = \"192.168.0.5:8080\"", + "not a loopback", + ), + ( + "port 0", + "[listener]\nlisten = \"127.0.0.1:0\"", + "port must not be 0", + ), + ( + "second listener key", + "[listener]\nlisten = \"127.0.0.1:8080\"\nadmin_listen = \"127.0.0.1:9000\"", + "unknown field", + ), + ( + "two listeners", + "[listener]\nlisten = [\"127.0.0.1:8080\", \"127.0.0.1:8081\"]", + "invalid", + ), + ( + "array of tables", + "[[listener]]\nlisten = \"127.0.0.1:8080\"\n[[listener]]\nlisten = \"127.0.0.1:8081\"", + "invalid", + ), + ( + "authority with space", + "[listener]\nlisten = \"127.0.0.1:8080\"\nauthorities = [\"a b\"]", + "plain Host", + ), + ] { + let e = Config::parse(with(l).as_bytes()) + .expect_err(label) + .to_string(); + assert!(e.contains(needle), "{label}: {e}"); + } +} + +#[test] +fn errors_are_reported_together() { + let t = sample_toml() + .replacen("version = 1", "version = 9", 1) + .replacen("name = \"anthropic\"", "name = \"A\"", 1); + let e = Config::parse(t.as_bytes()).unwrap_err(); + assert!(e.0.len() >= 2, "{e}"); +} + +#[test] +fn empty_and_garbage_files_are_errors() { + for raw in [&b""[..], b"\xff\xfe", b"not = [toml", b"version = 1\n"] { + assert!(Config::parse(raw).is_err()); + } + assert!(Config::parse(&vec![b'#'; 1024 * 1024 + 1]).is_err()); +} + +#[test] +fn host_port_parser() { + assert_eq!( + parse_host_port("github.com:443").unwrap(), + ("github.com".into(), 443) + ); + assert!(parse_host_port("github.com:").is_err()); + assert!(parse_host_port(":443").is_err()); +} + +/// `route.connect_to` is a test aid. A shipped build (no `test-resolve` feature) +/// has no such key, so a policy that sets it is rejected. Under `cargo test +/// --workspace` the feature is on for every crate (the proxy's integration tests +/// need it), so this runs with `cargo test -p ap-core`; CI also runs the shipped +/// release binary against such a policy (`scripts/check-no-test-resolve.sh`). +#[cfg(not(feature = "test-resolve"))] +#[test] +fn connect_to_is_rejected_in_a_shipped_build() { + let t = sample_toml().replacen( + "[[route]]\n", + "[[route]]\nconnect_to = \"127.0.0.1:9\"\n", + 1, + ); + let e = Config::parse(t.as_bytes()).unwrap_err().to_string(); + assert!(e.contains("connect_to"), "{e}"); +} + +#[cfg(feature = "test-resolve")] +#[test] +fn connect_to_parses_in_a_test_resolve_build() { + let t = sample_toml().replacen( + "[[route]]\n", + "[[route]]\nconnect_to = \"127.0.0.1:9\"\n", + 1, + ); + let c = Config::parse(t.as_bytes()).unwrap(); + assert_eq!( + c.routes[0].resolve_override(), + Some("127.0.0.1:9".parse().unwrap()) + ); +} + +/// Shipped policies (everything under `deploy/`) must parse, and none may use +/// `aws_targets`: the matcher stays dormant until a real grant needs it. +#[test] +fn shipped_policies_parse_and_use_no_aws_targets() { + fn walk(dir: &std::path::Path, out: &mut Vec) { + for e in std::fs::read_dir(dir).unwrap() { + let p = e.unwrap().path(); + if p.is_dir() { + walk(&p, out); + } else if p.extension().is_some_and(|x| x == "toml") { + out.push(p); + } + } + } + let deploy = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../deploy"); + let mut files = Vec::new(); + walk(&deploy, &mut files); + assert!( + files.iter().any(|f| f.ends_with("policy.example.toml")), + "the example policy was not found under deploy/: {files:?}" + ); + for f in files { + let raw = std::fs::read(&f).unwrap(); + let c = Config::parse(&raw).unwrap_or_else(|e| panic!("{}: {e}", f.display())); + for (i, g) in c.grants.iter().enumerate() { + assert!( + g.aws_targets.is_empty(), + "{}: grant #{} uses aws_targets, which is dormant (no shipped policy may use it)", + f.display(), + i + 1 + ); + } + } +} diff --git a/crates/ap-egress/Cargo.toml b/crates/ap-egress/Cargo.toml new file mode 100644 index 0000000..fea51cb --- /dev/null +++ b/crates/ap-egress/Cargo.toml @@ -0,0 +1,21 @@ +[package] +name = "ap-egress" +description = "auth-proxy egress: a CONNECT-only allowlist proxy for non-credential traffic. Holds no credential, depends on no broker, never terminates TLS." +version.workspace = true +edition.workspace = true +license.workspace = true +publish.workspace = true + +[[bin]] +name = "ap-egress" +path = "src/main.rs" + +# Do NOT add ap-broker, reqwest, rustls or hyper-rustls here. scripts/check-egress-deps.sh +# fails CI if any of them enters this crate's normal dependency tree. +[dependencies] +ap-core.workspace = true +tokio.workspace = true + +[dev-dependencies] +ap-core.workspace = true +tokio.workspace = true diff --git a/crates/ap-egress/src/lib.rs b/crates/ap-egress/src/lib.rs new file mode 100644 index 0000000..3c45c71 --- /dev/null +++ b/crates/ap-egress/src/lib.rs @@ -0,0 +1,367 @@ +//! ap-egress: CONNECT-only allowlist proxy (Q3-E2). +//! +//! Accepts `CONNECT host:port` only, where the exact `host:port` is in the +//! policy's `[egress].allow`. Resolves the name once, refuses the request if +//! any answer is a non-public address, then connects to one of those exact +//! validated addresses (no second resolution) and copies bytes. It never +//! terminates TLS and logs only `host:port` and the decision. + +use ap_core::canon::safe_field; +use ap_core::PolicyStore; +use std::future::Future; +use std::io; +use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; +use std::pin::Pin; +use std::sync::Arc; +use std::time::Duration; +use tokio::io::{copy_bidirectional, AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}; +use tokio::net::{TcpListener, TcpStream}; + +const MAX_HEAD: usize = 8 * 1024; + +pub type ResolveFuture<'a> = Pin>> + Send + 'a>>; + +/// Name resolution. Injectable so tests can script answers. +pub trait Resolver: Send + Sync { + fn resolve<'a>(&'a self, host: &'a str, port: u16) -> ResolveFuture<'a>; +} + +/// The system resolver (getaddrinfo through tokio). +pub struct SystemResolver; + +impl Resolver for SystemResolver { + fn resolve<'a>(&'a self, host: &'a str, port: u16) -> ResolveFuture<'a> { + Box::pin(async move { Ok(tokio::net::lookup_host((host, port)).await?.collect()) }) + } +} + +/// True for every address the proxy must never connect to. +pub fn forbidden_ip(ip: IpAddr) -> bool { + match ip { + IpAddr::V4(v) => forbidden_v4(v), + IpAddr::V6(v) => forbidden_v6(v), + } +} + +fn forbidden_v4(v: Ipv4Addr) -> bool { + let o = v.octets(); + v.is_loopback() + || v.is_private() + || v.is_link_local() + || v.is_unspecified() + || v.is_multicast() + || v.is_broadcast() + || o[0] == 0 + || o[0] >= 240 + || (o[0] == 100 && (o[1] & 0xc0) == 64) // 100.64.0.0/10 CGNAT + || (o[0] == 192 && o[1] == 0 && o[2] == 0) // 192.0.0.0/24 + || (o[0] == 198 && (o[1] & 0xfe) == 18) // 198.18.0.0/15 +} + +fn forbidden_v6(v: Ipv6Addr) -> bool { + let s = v.segments(); + if v.is_loopback() || v.is_unspecified() || v.is_multicast() { + return true; + } + if (s[0] & 0xfe00) == 0xfc00 || (s[0] & 0xffc0) == 0xfe80 { + return true; // ULA, link-local + } + // v4-mapped ::ffff:a.b.c.d, v4-compatible ::a.b.c.d, NAT64 64:ff9b::/96 + let embedded = + |hi: u16, lo: u16| Ipv4Addr::new((hi >> 8) as u8, hi as u8, (lo >> 8) as u8, lo as u8); + if s[..5] == [0; 5] && (s[5] == 0xffff || s[5] == 0) { + return forbidden_v4(embedded(s[6], s[7])); + } + if s[0] == 0x64 && s[1] == 0xff9b && s[2..6] == [0; 4] { + return forbidden_v4(embedded(s[6], s[7])); + } + false +} + +#[derive(Clone)] +pub struct Options { + pub connect_timeout: Duration, + pub idle_timeout: Duration, + pub head_timeout: Duration, + /// Address filter. Production uses `forbidden_ip`; tests replace it so a + /// loopback echo server can stand in for an upstream. + pub forbidden: fn(IpAddr) -> bool, +} + +impl Default for Options { + fn default() -> Options { + Options { + connect_timeout: Duration::from_secs(10), + idle_timeout: Duration::from_secs(300), + head_timeout: Duration::from_secs(10), + forbidden: forbidden_ip, + } + } +} + +pub struct Egress { + pub store: PolicyStore, + pub resolver: Box, + pub opts: Options, +} + +enum Refusal { + Malformed, + Method, + NotAllowed(&'static str), + Unavailable, + BadGateway(&'static str), + Timeout, +} + +impl Refusal { + fn status(&self) -> (u16, &'static str) { + match self { + Refusal::Malformed => (400, "Bad Request"), + Refusal::Method => (405, "Method Not Allowed"), + Refusal::NotAllowed(_) => (403, "Forbidden"), + Refusal::Unavailable => (503, "Service Unavailable"), + Refusal::BadGateway(_) => (502, "Bad Gateway"), + Refusal::Timeout => (504, "Gateway Timeout"), + } + } + fn reason(&self) -> &'static str { + match self { + Refusal::Malformed => "malformed", + Refusal::Method => "method_not_allowed", + Refusal::NotAllowed(r) | Refusal::BadGateway(r) => r, + Refusal::Unavailable => "policy_unavailable", + Refusal::Timeout => "connect_timeout", + } + } +} + +fn audit(decision: &str, target: &str, reason: &str) { + println!( + "ap-egress decision={decision} target={} reason={reason}", + safe_field(target) + ); +} + +/// Accept loop. Runs until the listener fails. +pub async fn serve(listener: TcpListener, egress: Arc) -> io::Result<()> { + loop { + let (sock, _) = listener.accept().await?; + let eg = egress.clone(); + tokio::spawn(async move { + handle(sock, &eg).await; + }); + } +} + +/// Read the request head. Returns the head text and any bytes read past it. +async fn read_head(s: &mut S) -> Result<(String, Vec), Refusal> { + let mut buf = Vec::with_capacity(512); + let mut chunk = [0u8; 1024]; + loop { + if let Some(i) = buf.windows(4).position(|w| w == b"\r\n\r\n") { + let rest = buf.split_off(i + 4); + let head = String::from_utf8(buf).map_err(|_| Refusal::Malformed)?; + return Ok((head, rest)); + } + if buf.len() > MAX_HEAD { + return Err(Refusal::Malformed); + } + let n = s.read(&mut chunk).await.map_err(|_| Refusal::Malformed)?; + if n == 0 { + return Err(Refusal::Malformed); + } + buf.extend_from_slice(&chunk[..n]); + } +} + +/// `CONNECT host:port HTTP/1.x` -> (host lowercased, port, raw target). +fn parse_connect(head: &str) -> Result<(String, u16, String), Refusal> { + let line = head.split("\r\n").next().unwrap_or(""); + let mut parts = line.split(' '); + let (method, target, version, extra) = (parts.next(), parts.next(), parts.next(), parts.next()); + let (Some(method), Some(target), Some(version), None) = (method, target, version, extra) else { + return Err(Refusal::Malformed); + }; + if !version.starts_with("HTTP/1.") { + return Err(Refusal::Malformed); + } + if method != "CONNECT" { + return Err(Refusal::Method); + } + let raw = target.to_string(); + let (host, port) = target + .rsplit_once(':') + .ok_or(Refusal::NotAllowed("not_host_port"))?; + if host.starts_with('[') || host.parse::().is_ok() || host.contains(':') { + return Err(Refusal::NotAllowed("ip_literal")); + } + if port.is_empty() || port.len() > 5 || !port.bytes().all(|b| b.is_ascii_digit()) { + return Err(Refusal::NotAllowed("bad_port")); + } + let port: u16 = port.parse().map_err(|_| Refusal::NotAllowed("bad_port"))?; + Ok((host.to_ascii_lowercase(), port, raw)) +} + +async fn handle(mut client: TcpStream, eg: &Egress) { + let head = tokio::time::timeout(eg.opts.head_timeout, read_head(&mut client)).await; + let (head, rest) = match head { + Ok(Ok(v)) => v, + Ok(Err(r)) => return refuse(&mut client, "-", r).await, + Err(_) => return refuse(&mut client, "-", Refusal::Malformed).await, + }; + let (host, port, raw) = match parse_connect(&head) { + Ok(v) => v, + Err(r) => { + let t = head.split(' ').nth(1).unwrap_or("-").to_string(); + return refuse(&mut client, &t, r).await; + } + }; + let target = format!("{host}:{port}"); + match connect_upstream(eg, &host, port).await { + Ok(mut up) => { + audit("allow", &target, "ok"); + if client + .write_all(b"HTTP/1.1 200 Connection Established\r\n\r\n") + .await + .is_err() + { + return; + } + if !rest.is_empty() && up.write_all(&rest).await.is_err() { + return; + } + tunnel(client, up, eg.opts.idle_timeout).await; + } + Err(r) => { + let t = if matches!(r, Refusal::NotAllowed("ip_literal")) { + &raw + } else { + &target + }; + refuse(&mut client, t, r).await + } + } +} + +/// Policy check, one resolution, address check, then connect to one of the +/// validated addresses from that single answer. +async fn connect_upstream(eg: &Egress, host: &str, port: u16) -> Result { + let policy = eg.store.current().map_err(|_| Refusal::Unavailable)?; + let listed = policy + .config() + .egress + .entries() + .iter() + .any(|(h, p)| h == host && *p == port); + if !listed { + return Err(Refusal::NotAllowed("not_allowlisted")); + } + let addrs = eg + .resolver + .resolve(host, port) + .await + .map_err(|_| Refusal::BadGateway("resolve_failed"))?; + if addrs.is_empty() { + return Err(Refusal::BadGateway("resolve_empty")); + } + if addrs.iter().any(|a| (eg.opts.forbidden)(a.ip())) { + return Err(Refusal::NotAllowed("forbidden_address")); + } + let mut last = Refusal::BadGateway("connect_failed"); + for a in addrs { + match tokio::time::timeout(eg.opts.connect_timeout, TcpStream::connect(a)).await { + Ok(Ok(s)) => return Ok(s), + Ok(Err(_)) => last = Refusal::BadGateway("connect_failed"), + Err(_) => last = Refusal::Timeout, + } + } + Err(last) +} + +async fn tunnel(mut client: TcpStream, mut up: TcpStream, idle: Duration) { + // The idle timeout is a rolling deadline on the whole copy: it restarts on + // every chunk, which copy_bidirectional does not expose, so wrap both + // directions in a stream that bumps a shared activity clock. + let last = Arc::new(std::sync::Mutex::new(tokio::time::Instant::now())); + let mut c = Tracked { + inner: &mut client, + last: last.clone(), + }; + let mut u = Tracked { + inner: &mut up, + last: last.clone(), + }; + let copy = copy_bidirectional(&mut c, &mut u); + tokio::pin!(copy); + loop { + let deadline = *last.lock().unwrap() + idle; + tokio::select! { + _ = &mut copy => return, + _ = tokio::time::sleep_until(deadline) => { + if *last.lock().unwrap() + idle <= tokio::time::Instant::now() { + return; + } + } + } + } +} + +struct Tracked<'a, S> { + inner: &'a mut S, + last: Arc>, +} + +impl Tracked<'_, S> { + fn bump(&self) { + *self.last.lock().unwrap() = tokio::time::Instant::now(); + } +} + +impl AsyncRead for Tracked<'_, S> { + fn poll_read( + mut self: Pin<&mut Self>, + cx: &mut std::task::Context<'_>, + buf: &mut tokio::io::ReadBuf<'_>, + ) -> std::task::Poll> { + let r = Pin::new(&mut *self.inner).poll_read(cx, buf); + if matches!(r, std::task::Poll::Ready(Ok(()))) { + self.bump(); + } + r + } +} + +impl AsyncWrite for Tracked<'_, S> { + fn poll_write( + mut self: Pin<&mut Self>, + cx: &mut std::task::Context<'_>, + buf: &[u8], + ) -> std::task::Poll> { + let r = Pin::new(&mut *self.inner).poll_write(cx, buf); + if matches!(r, std::task::Poll::Ready(Ok(n)) if n > 0) { + self.bump(); + } + r + } + fn poll_flush( + mut self: Pin<&mut Self>, + cx: &mut std::task::Context<'_>, + ) -> std::task::Poll> { + Pin::new(&mut *self.inner).poll_flush(cx) + } + fn poll_shutdown( + mut self: Pin<&mut Self>, + cx: &mut std::task::Context<'_>, + ) -> std::task::Poll> { + Pin::new(&mut *self.inner).poll_shutdown(cx) + } +} + +async fn refuse(client: &mut TcpStream, target: &str, r: Refusal) { + let (code, text) = r.status(); + audit("refuse", target, r.reason()); + let body = format!("HTTP/1.1 {code} {text}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"); + let _ = client.write_all(body.as_bytes()).await; + let _ = client.shutdown().await; +} diff --git a/crates/ap-egress/src/main.rs b/crates/ap-egress/src/main.rs new file mode 100644 index 0000000..2e936db --- /dev/null +++ b/crates/ap-egress/src/main.rs @@ -0,0 +1,80 @@ +//! ap-egress binary. `ap-egress --policy PATH [--listen 127.0.0.1:3128]` +//! (env twins AP_POLICY, AP_EGRESS_LISTEN). Exit 2 on bad arguments or policy. + +use ap_core::PolicyStore; +use ap_egress::{serve, Egress, Options, SystemResolver}; +use std::net::SocketAddr; +use std::sync::Arc; + +const USAGE: &str = "\ +ap-egress: CONNECT-only egress allowlist proxy + + --policy PATH policy file (same TOML as auth-proxy; only [egress] is used) AP_POLICY (required) + --listen ADDR loopback listen address [127.0.0.1:3128] AP_EGRESS_LISTEN + --help + +Exit codes: 0 clean stop, 2 invalid arguments or policy. +"; + +fn parse() -> Result, String> { + let mut policy = std::env::var("AP_POLICY").ok(); + let mut listen = std::env::var("AP_EGRESS_LISTEN").unwrap_or_else(|_| "127.0.0.1:3128".into()); + let mut it = std::env::args().skip(1); + while let Some(a) = it.next() { + match a.as_str() { + "--help" | "-h" => return Ok(None), + "--policy" => policy = Some(it.next().ok_or("--policy needs a value")?), + "--listen" => listen = it.next().ok_or("--listen needs a value")?, + _ => return Err(format!("unknown argument {a:?}")), + } + } + let policy = policy.ok_or("--policy (or AP_POLICY) is required")?; + let addr: SocketAddr = listen.parse().map_err(|_| "--listen: not an address")?; + if !addr.ip().is_loopback() { + return Err("--listen must be a loopback address".into()); + } + Ok(Some((policy, addr))) +} + +#[tokio::main] +async fn main() { + std::panic::set_hook(Box::new(|_| eprintln!("ap-egress: internal error (panic)"))); + let (policy, addr) = match parse() { + Ok(Some(v)) => v, + Ok(None) => { + print!("{USAGE}"); + return; + } + Err(e) => { + eprintln!("ap-egress: {e}"); + std::process::exit(2); + } + }; + let store = match PolicyStore::open(&policy) { + Ok(s) => s, + Err(e) => { + eprintln!("ap-egress: policy: {e}"); + std::process::exit(2); + } + }; + let listener = match tokio::net::TcpListener::bind(addr).await { + Ok(l) => l, + Err(e) => { + eprintln!("ap-egress: bind {addr}: {}", e.kind()); + std::process::exit(2); + } + }; + eprintln!("ap-egress: listening on {addr}"); + let eg = Arc::new(Egress { + store, + resolver: Box::new(SystemResolver), + opts: Options::default(), + }); + tokio::select! { + r = serve(listener, eg) => { + eprintln!("ap-egress: accept failed: {:?}", r.err().map(|e| e.kind())); + std::process::exit(2); + } + _ = tokio::signal::ctrl_c() => {} + } +} diff --git a/crates/ap-egress/tests/connect.rs b/crates/ap-egress/tests/connect.rs new file mode 100644 index 0000000..3204060 --- /dev/null +++ b/crates/ap-egress/tests/connect.rs @@ -0,0 +1,323 @@ +use ap_core::testing::sample_toml; +use ap_egress::{forbidden_ip, serve, Egress, Options, ResolveFuture, Resolver}; +use std::collections::HashMap; +use std::net::{IpAddr, SocketAddr}; +use std::path::PathBuf; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::net::{TcpListener, TcpStream}; + +/// Scripted answers per call: the nth call returns answers[min(n, len-1)]. +struct Script { + answers: Mutex>>>, + calls: AtomicUsize, +} + +impl Resolver for Script { + fn resolve<'a>(&'a self, host: &'a str, _port: u16) -> ResolveFuture<'a> { + Box::pin(async move { + let n = self.calls.fetch_add(1, Ordering::SeqCst); + let m = self.answers.lock().unwrap(); + let v = m + .get(host) + .ok_or_else(|| std::io::Error::other("nxdomain"))?; + Ok(v[n.min(v.len() - 1)].clone()) + }) + } +} + +fn permissive(_: IpAddr) -> bool { + false +} + +struct Rig { + proxy: SocketAddr, + accepted: Arc, + echo: SocketAddr, + script: Arc