From f1d24a55a965a861acc6ed1971c383ca8185c475 Mon Sep 17 00:00:00 2001 From: chaodu-agent <274062505+chaodu-agent@users.noreply.github.com> Date: Mon, 16 Nov 2026 07:14:54 -0500 Subject: [PATCH 01/18] feat: add workspace with ap-core and ap-broker libraries (FEAT-001) ap-core: Q3-A config model and validation, policy snapshot with stat-per-request PolicyStore (fails closed), aws_targets matcher, grant evaluation, refusal codes and error dialects, canonicalization, and an AuditRec that only accepts a route-relative path (no /ap/). ap-broker: session registry (15 min lease, 12 h absolute TTL cap, resync), authority lock (90 s lease, hash persisted), S1 FileStore, Broker trait and LocalBroker. No network I/O; no aws-sm, no ECS pieces. Verified on macmini (cargo 1.99.1), not locally: - cargo fmt --check: ok - cargo clippy --workspace --all-targets -- -D warnings: clean - cargo test -p ap-core -p ap-broker: 22 unit + 13 config (ap-core), 24 plane + 8 store (ap-broker), all passed --- .gitignore | 1 + Cargo.lock | 341 +++++++++++ Cargo.toml | 29 + crates/ap-broker/Cargo.toml | 17 + crates/ap-broker/src/authority.rs | 172 ++++++ crates/ap-broker/src/broker.rs | 90 +++ crates/ap-broker/src/clock.rs | 59 ++ crates/ap-broker/src/error.rs | 75 +++ crates/ap-broker/src/lib.rs | 26 + crates/ap-broker/src/plane.rs | 206 +++++++ crates/ap-broker/src/registry.rs | 400 +++++++++++++ crates/ap-broker/src/store.rs | 129 +++++ crates/ap-broker/tests/plane.rs | 789 ++++++++++++++++++++++++++ crates/ap-broker/tests/store.rs | 364 ++++++++++++ crates/ap-broker/tests/support/mod.rs | 81 +++ crates/ap-core/Cargo.toml | 16 + crates/ap-core/src/audit.rs | 198 +++++++ crates/ap-core/src/canon.rs | 261 +++++++++ crates/ap-core/src/code.rs | 243 ++++++++ crates/ap-core/src/config.rs | 535 +++++++++++++++++ crates/ap-core/src/headers.rs | 88 +++ crates/ap-core/src/lib.rs | 28 + crates/ap-core/src/policy.rs | 506 +++++++++++++++++ crates/ap-core/src/stamp.rs | 33 ++ crates/ap-core/src/surrogate.rs | 64 +++ crates/ap-core/src/testing.rs | 96 ++++ crates/ap-core/tests/config.rs | 451 +++++++++++++++ 27 files changed, 5298 insertions(+) create mode 100644 .gitignore create mode 100644 Cargo.lock create mode 100644 Cargo.toml create mode 100644 crates/ap-broker/Cargo.toml create mode 100644 crates/ap-broker/src/authority.rs create mode 100644 crates/ap-broker/src/broker.rs create mode 100644 crates/ap-broker/src/clock.rs create mode 100644 crates/ap-broker/src/error.rs create mode 100644 crates/ap-broker/src/lib.rs create mode 100644 crates/ap-broker/src/plane.rs create mode 100644 crates/ap-broker/src/registry.rs create mode 100644 crates/ap-broker/src/store.rs create mode 100644 crates/ap-broker/tests/plane.rs create mode 100644 crates/ap-broker/tests/store.rs create mode 100644 crates/ap-broker/tests/support/mod.rs create mode 100644 crates/ap-core/Cargo.toml create mode 100644 crates/ap-core/src/audit.rs create mode 100644 crates/ap-core/src/canon.rs create mode 100644 crates/ap-core/src/code.rs create mode 100644 crates/ap-core/src/config.rs create mode 100644 crates/ap-core/src/headers.rs create mode 100644 crates/ap-core/src/lib.rs create mode 100644 crates/ap-core/src/policy.rs create mode 100644 crates/ap-core/src/stamp.rs create mode 100644 crates/ap-core/src/surrogate.rs create mode 100644 crates/ap-core/src/testing.rs create mode 100644 crates/ap-core/tests/config.rs 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..0c7abb4 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,341 @@ +# 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", + "hex", + "serde", + "serde_json", + "sha2", + "subtle", + "zeroize", +] + +[[package]] +name = "ap-core" +version = "0.1.0" +dependencies = [ + "hex", + "http", + "serde", + "serde_json", + "sha2", + "subtle", + "toml", +] + +[[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 = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +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 = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[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", + "libc", + "wasi", +] + +[[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 = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", +] + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[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 = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[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 = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[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 = "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 = "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 = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "winnow" +version = "0.7.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945" +dependencies = [ + "memchr", +] + +[[package]] +name = "zeroize" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" + +[[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..f6717a4 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,29 @@ +[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" } +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..e5bc563 --- /dev/null +++ b/crates/ap-broker/src/broker.rs @@ -0,0 +1,90 @@ +//! 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::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>; +} + +pub struct LocalBroker { + plane: Arc, + store: Arc, +} + +impl LocalBroker { + pub fn new(plane: Arc, store: Arc) -> LocalBroker { + LocalBroker { plane, store } + } + + 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 = 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..5086c5b --- /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}; +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..987db9c --- /dev/null +++ b/crates/ap-broker/src/plane.rs @@ -0,0 +1,206 @@ +//! 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) + } + + 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..d40b97f --- /dev/null +++ b/crates/ap-broker/tests/plane.rs @@ -0,0 +1,789 @@ +//! 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()); +} 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-core/Cargo.toml b/crates/ap-core/Cargo.toml new file mode 100644 index 0000000..894bc97 --- /dev/null +++ b/crates/ap-core/Cargo.toml @@ -0,0 +1,16 @@ +[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 + +[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..e7e6242 --- /dev/null +++ b/crates/ap-core/src/audit.rs @@ -0,0 +1,198 @@ +//! 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, +} + +/// 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`. + pub fn failed( + input: &AuditInput<'_>, + path: &RoutePath, + code: &'static str, + status: u16, + ) -> AuditRec { + AuditRec::build(input, path, "error", code, status) + } + + 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, + } + } + + 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", + "t", + ] { + assert!(v.get(k).is_some(), "missing {k}"); + } + assert_eq!( + v.as_object().unwrap().len(), + 12, + "no field beyond the documented ones" + ); + assert_eq!(v["path"], "/v1/messages"); + } + + #[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), + ] { + 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..e417612 --- /dev/null +++ b/crates/ap-core/src/config.rs @@ -0,0 +1,535 @@ +//! 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`. + #[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 { + /// `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, + /// Turns off the check that an egress host is not a credential route host. + #[serde(default)] + pub allow_route_hosts: bool, +} + +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, _)) => { + if !self.egress.allow_route_hosts && credential_hosts.contains(h.as_str()) { + e(format!( + "egress.allow entry {ent:?}: host is a credential route host \ + (set egress.allow_route_hosts = true to allow)" + )); + } + } + } + } + + 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..ac60d7a --- /dev/null +++ b/crates/ap-core/src/policy.rs @@ -0,0 +1,506 @@ +//! 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; + while !stop.load(std::sync::atomic::Ordering::Relaxed) { + 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; + } + 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..11146b3 --- /dev/null +++ b/crates/ap-core/tests/config.rs @@ -0,0 +1,451 @@ +//! 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, + ); + } + // explicit opt-out + let t = sample_toml() + .replacen( + "allow = [\"github.com:443\",", + "allow = [\"api.anthropic.com:443\",", + 1, + ) + .replacen("[egress]", "[egress]\nallow_route_hosts = true", 1); + Config::parse(t.as_bytes()).unwrap(); +} + +#[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()); +} From f57d06d7ee1c15a880ab243dcf3626b3bce12029 Mon Sep 17 00:00:00 2001 From: chaodu-agent <274062505+chaodu-agent@users.noreply.github.com> Date: Mon, 16 Nov 2026 07:38:52 -0500 Subject: [PATCH 02/18] feat: add auth-proxy binary, ap-client, ported matrix and integration tests (FEAT-002) ap-proxy (bin `auth-proxy`): one loopback agent listener, session-plane and admin Unix sockets, the section 4 pipeline, audit to stdout. Request bodies stream with a cap (413), upstream is HTTP/2 via ALPN, redirects are never followed. No tracing or access-log layer exists, the caller key is dropped by ApPath::verify, pre-verification refusals audit path "-", upstream error text is never printed, and the panic hook prints a fixed line (owner condition b). ap-client: UDS session-plane client, surrogate generation, Authority with renew loop, resync on unknown, hello retry with backoff. ap-broker gains SessionPlane::revoke_all for the admin socket. Tests: hello race after an authority restart (owner condition a), no /ap/ or secret in any log (b), session plane, policy, aws_targets. tests/matrix ports the 25 Phase 0 rows (Phase 1 expectations) plus 6 rows. Verified on macmini (macOS, cargo 1.99.1, system python3 3.9.6), after rsync: - cargo fmt --check: ok - cargo clippy --workspace --all-targets -- -D warnings: clean - cargo test --workspace: all pass (ap-core 22+13, ap-broker 25+8, ap-client 6, ap-proxy unit 13, hello_race 3, no_caller_key_in_logs 1, policy 5, session_plane 13) - cargo build --release; python3 tests/matrix/matrix.py --bin target/release: Phase 0 rows 25/25 PASS, added rows 6/6 PASS - negative control: logging the request URI to stderr makes no_caller_key_in_logs fail (reverted, not committed) Not run: the k8s iptables rule-set test (no cluster), HTTP/2 upstream (the mock upstream speaks HTTP/1.1 only). --- Cargo.lock | 1490 ++++++++++++++++- Cargo.toml | 5 + crates/ap-broker/src/plane.rs | 13 + crates/ap-broker/tests/plane.rs | 18 + crates/ap-client/Cargo.toml | 19 + crates/ap-client/src/lib.rs | 751 +++++++++ crates/ap-proxy/Cargo.toml | 30 + crates/ap-proxy/src/admin.rs | 66 + crates/ap-proxy/src/agent.rs | 542 ++++++ crates/ap-proxy/src/app.rs | 56 + crates/ap-proxy/src/args.rs | 280 ++++ crates/ap-proxy/src/audit.rs | 136 ++ crates/ap-proxy/src/main.rs | 245 +++ crates/ap-proxy/src/plane_http.rs | 386 +++++ crates/ap-proxy/src/sock.rs | 107 ++ crates/ap-proxy/tests/hello_race.rs | 254 +++ .../ap-proxy/tests/no_caller_key_in_logs.rs | 345 ++++ crates/ap-proxy/tests/policy.rs | 422 +++++ crates/ap-proxy/tests/session_plane.rs | 566 +++++++ crates/ap-proxy/tests/support/mod.rs | 678 ++++++++ tests/matrix/harness.py | 382 +++++ tests/matrix/matrix.py | 571 +++++++ tests/matrix/upstream.py | 150 ++ 23 files changed, 7420 insertions(+), 92 deletions(-) create mode 100644 crates/ap-client/Cargo.toml create mode 100644 crates/ap-client/src/lib.rs create mode 100644 crates/ap-proxy/Cargo.toml create mode 100644 crates/ap-proxy/src/admin.rs create mode 100644 crates/ap-proxy/src/agent.rs create mode 100644 crates/ap-proxy/src/app.rs create mode 100644 crates/ap-proxy/src/args.rs create mode 100644 crates/ap-proxy/src/audit.rs create mode 100644 crates/ap-proxy/src/main.rs create mode 100644 crates/ap-proxy/src/plane_http.rs create mode 100644 crates/ap-proxy/src/sock.rs create mode 100644 crates/ap-proxy/tests/hello_race.rs create mode 100644 crates/ap-proxy/tests/no_caller_key_in_logs.rs create mode 100644 crates/ap-proxy/tests/policy.rs create mode 100644 crates/ap-proxy/tests/session_plane.rs create mode 100644 crates/ap-proxy/tests/support/mod.rs create mode 100644 tests/matrix/harness.py create mode 100644 tests/matrix/matrix.py create mode 100644 tests/matrix/upstream.py diff --git a/Cargo.lock b/Cargo.lock index 0c7abb4..46a1802 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7,7 +7,7 @@ name = "ap-broker" version = "0.1.0" dependencies = [ "ap-core", - "getrandom", + "getrandom 0.2.17", "hex", "serde", "serde_json", @@ -16,6 +16,19 @@ dependencies = [ "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" @@ -29,6 +42,94 @@ dependencies = [ "toml", ] +[[package]] +name = "ap-proxy" +version = "0.1.0" +dependencies = [ + "ap-broker", + "ap-client", + "ap-core", + "axum", + "futures-util", + "hex", + "http", + "reqwest", + "serde", + "serde_json", + "sha2", + "tokio", +] + +[[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" @@ -38,18 +139,51 @@ 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" @@ -59,6 +193,15 @@ 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" @@ -79,12 +222,114 @@ dependencies = [ "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" @@ -102,8 +347,43 @@ 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]] @@ -129,175 +409,891 @@ dependencies = [ ] [[package]] -name = "indexmap" -version = "2.14.2" +name = "http-body" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" dependencies = [ - "equivalent", - "hashbrown", + "bytes", + "http", ] [[package]] -name = "itoa" -version = "1.0.19" +name = "http-body-util" +version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] [[package]] -name = "libc" -version = "0.2.191" +name = "httparse" +version = "1.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" [[package]] -name = "memchr" -version = "2.8.3" +name = "httpdate" +version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" [[package]] -name = "proc-macro2" -version = "1.0.107" +name = "hyper" +version = "1.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c" dependencies = [ - "unicode-ident", + "atomic-waker", + "bytes", + "futures-channel", + "futures-core", + "h2", + "http", + "http-body", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", ] [[package]] -name = "quote" -version = "1.0.47" +name = "hyper-rustls" +version = "0.27.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53" dependencies = [ - "proc-macro2", + "http", + "hyper", + "hyper-util", + "rustls", + "tokio", + "tokio-rustls", + "tower-service", + "webpki-roots", ] [[package]] -name = "serde" -version = "1.0.229" +name = "hyper-util" +version = "0.1.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" dependencies = [ - "serde_core", - "serde_derive", + "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 = "serde_core" -version = "1.0.229" +name = "icu_collections" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" dependencies = [ - "serde_derive", + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", ] [[package]] -name = "serde_derive" -version = "1.0.229" +name = "icu_locale_core" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" dependencies = [ - "proc-macro2", - "quote", - "syn", + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", ] [[package]] -name = "serde_json" -version = "1.0.154" +name = "icu_normalizer" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" dependencies = [ - "itoa", - "memchr", - "serde", - "serde_core", - "zmij", + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", ] [[package]] -name = "serde_spanned" -version = "0.6.9" +name = "icu_normalizer_data" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3" -dependencies = [ - "serde", -] +checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" [[package]] -name = "sha2" -version = "0.10.9" +name = "icu_properties" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" dependencies = [ - "cfg-if", - "cpufeatures", - "digest", + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", ] [[package]] -name = "subtle" -version = "2.6.1" +name = "icu_properties_data" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" +checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" [[package]] -name = "syn" -version = "3.0.10" +name = "icu_provider" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" dependencies = [ - "proc-macro2", - "quote", - "unicode-ident", + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", ] [[package]] -name = "toml" -version = "0.8.23" +name = "idna" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" dependencies = [ - "serde", - "serde_spanned", - "toml_datetime", - "toml_edit", + "idna_adapter", + "smallvec", + "utf8_iter", ] [[package]] -name = "toml_datetime" -version = "0.6.11" +name = "idna_adapter" +version = "1.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "22cddaf88f4fbc13c51aebbf5f8eceb5c7c5a9da2ac40a13519eb5b0a0e8f11c" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" dependencies = [ - "serde", + "icu_normalizer", + "icu_properties", ] [[package]] -name = "toml_edit" -version = "0.22.27" +name = "indexmap" +version = "2.14.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" dependencies = [ - "indexmap", - "serde", - "serde_spanned", - "toml_datetime", - "toml_write", - "winnow", + "equivalent", + "hashbrown", ] [[package]] -name = "toml_write" -version = "0.1.2" +name = "ipnet" +version = "2.12.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801" +checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" [[package]] -name = "typenum" -version = "1.20.1" +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" @@ -307,18 +1303,245 @@ 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" @@ -328,12 +1551,95 @@ 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" diff --git a/Cargo.toml b/Cargo.toml index f6717a4..217f45b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,6 +13,11 @@ 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" diff --git a/crates/ap-broker/src/plane.rs b/crates/ap-broker/src/plane.rs index 987db9c..cb6441e 100644 --- a/crates/ap-broker/src/plane.rs +++ b/crates/ap-broker/src/plane.rs @@ -190,6 +190,19 @@ impl SessionPlane { 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(); diff --git a/crates/ap-broker/tests/plane.rs b/crates/ap-broker/tests/plane.rs index d40b97f..16843fb 100644 --- a/crates/ap-broker/tests/plane.rs +++ b/crates/ap-broker/tests/plane.rs @@ -787,3 +787,21 @@ fn authority_lease_is_configurable_for_tests_only_down_to_3_s() { 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-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-proxy/Cargo.toml b/crates/ap-proxy/Cargo.toml new file mode 100644 index 0000000..111d4d0 --- /dev/null +++ b/crates/ap-proxy/Cargo.toml @@ -0,0 +1,30 @@ +[package] +name = "ap-proxy" +description = "auth-proxy: the credential-swapping reverse proxy. Loopback agent listener, session-plane and admin Unix sockets, in-process broker." +version.workspace = true +edition.workspace = true +license.workspace = true +publish.workspace = true + +[[bin]] +name = "auth-proxy" +path = "src/main.rs" + +[dependencies] +ap-core.workspace = true +ap-broker.workspace = true +axum.workspace = true +futures-util.workspace = true +http.workspace = true +reqwest.workspace = true +serde.workspace = true +serde_json.workspace = true +tokio.workspace = true + +[dev-dependencies] +ap-client.workspace = true +ap-core.workspace = true +hex.workspace = true +sha2.workspace = true +serde_json.workspace = true +tokio.workspace = true diff --git a/crates/ap-proxy/src/admin.rs b/crates/ap-proxy/src/admin.rs new file mode 100644 index 0000000..2163225 --- /dev/null +++ b/crates/ap-proxy/src/admin.rs @@ -0,0 +1,66 @@ +//! The admin plane: a Unix socket in a directory only the proxy container +//! mounts. Two calls, neither of which returns a credential or a token: +//! `POST /admin/revoke-all` and `GET /admin/status`. + +use crate::agent::fixed_json; +use crate::app::App; +use crate::audit::PlaneEvent; +use axum::body::Body; +use axum::extract::{Request, State}; +use axum::response::Response; +use http::{header, Method}; +use std::sync::Arc; + +fn json(status: u16, v: serde_json::Value) -> Response { + Response::builder() + .status(status) + .header(header::CONTENT_TYPE, "application/json") + .body(Body::from(v.to_string())) + .unwrap() +} + +pub async fn handler(State(app): State>, req: Request) -> Response { + let (m, p) = (req.method().clone(), req.uri().path().to_string()); + match (m, p.as_str()) { + (Method::POST, "/admin/revoke-all") => { + let n = app.plane.revoke_all(); + app.audit.plane(&PlaneEvent { + call: "revoke-all", + count: Some(n), + status: 200, + result: "ok", + ..Default::default() + }); + json(200, serde_json::json!({ "revoked": n })) + } + (Method::GET, "/admin/status") => { + let (policy, identity) = match app.policy.current() { + Ok(p) => ("ok", Some(p.identity().to_string())), + Err(_) => ("unavailable", None), + }; + app.audit.plane(&PlaneEvent { + call: "status", + status: 200, + result: "ok", + ..Default::default() + }); + json( + 200, + serde_json::json!({ + "authority_live": app.plane.authority_live(), + "sessions": app.plane.session_count(), + "policy": policy, + "identity": identity, + }), + ) + } + (_, "/admin/revoke-all") | (_, "/admin/status") => fixed_json( + 405, + r#"{"error":"method_not_allowed","message":"method not allowed"}"#, + ), + _ => fixed_json( + 404, + r#"{"error":"not_found","message":"unknown admin call"}"#, + ), + } +} diff --git a/crates/ap-proxy/src/agent.rs b/crates/ap-proxy/src/agent.rs new file mode 100644 index 0000000..8720592 --- /dev/null +++ b/crates/ap-proxy/src/agent.rs @@ -0,0 +1,542 @@ +//! The agent listener: design doc section 4, step by step. +//! +//! LOGGING RULE (owner condition b). The request URI carries the caller key +//! (`/ap///...`) and never reaches a log: +//! +//! - no tracing or access-log layer is installed anywhere in this process; +//! - `ApPath::verify` is the single place the prefix is taken apart, and it +//! hands back a `VerifiedPath` that holds only the route and the rest, so +//! everything after caller verification (audit, upstream URL, errors) cannot +//! see the key; +//! - a request refused before the key is verified is audited with path `-`; +//! - upstream errors are never formatted: `reqwest` error text embeds the URL, +//! so only fixed codes are logged; +//! - the panic hook (main.rs) prints a fixed string, and `handler` turns a +//! panic into a fixed 500. + +use crate::app::App; +use ap_broker::Broker; +use ap_core::surrogate::hash_surrogate; +use ap_core::{ + canon::path_ambiguous, deny_parts, strip_request_headers, ApPath, AuditInput, AuditRec, Code, + ErrorShape, RoutePath, HOP_HEADERS, +}; +use axum::body::Body; +use axum::extract::{Request, State}; +use axum::response::Response; +use futures_util::{FutureExt, StreamExt}; +use http::{header, HeaderMap, HeaderName, HeaderValue, Method}; +use std::panic::AssertUnwindSafe; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::Arc; +use std::time::Instant; + +/// How much of an oversized body is read and discarded before the 413. +const DRAIN_LIMIT: u64 = 64 * 1024 * 1024; + +pub async fn handler(State(app): State>, req: Request) -> Response { + match AssertUnwindSafe(handle(app, req)).catch_unwind().await { + Ok(r) => r, + Err(_) => fixed_json( + 500, + r#"{"type":"error","error":{"type":"internal_error","message":"auth-proxy: internal error"}}"#, + ), + } +} + +pub fn fixed_json(status: u16, body: &'static str) -> Response { + Response::builder() + .status(status) + .header(header::CONTENT_TYPE, "application/json") + .body(Body::from(body)) + .unwrap() +} + +/// What the audit line learns as the request moves through the pipeline. +#[derive(Default, Clone)] +struct Ctx { + identity: Option, + session: Option, + generation: Option, + route: Option, + aws_target: Option, +} + +impl Ctx { + fn input<'a>(&'a self, method: &'a str, t0: Instant) -> AuditInput<'a> { + AuditInput { + identity: self.identity.as_deref(), + session: self.session.as_deref(), + generation: self.generation, + route: self.route.as_deref(), + method, + aws_target: self.aws_target.as_deref(), + duration_ms: t0.elapsed().as_millis() as u64, + } + } +} + +fn deny_response(shape: ErrorShape, code: Code) -> Response { + let (status, headers, body) = deny_parts(shape, code); + let mut r = Response::builder().status(status); + for (k, v) in headers { + r = r.header(k, v); + } + r.body(Body::from(body)).unwrap() +} + +/// Audit the refusal, then build it in the route's error dialect. +fn refuse( + app: &App, + ctx: &Ctx, + method: &str, + t0: Instant, + path: &RoutePath, + shape: ErrorShape, + code: Code, +) -> Response { + app.audit + .request(&AuditRec::refused(&ctx.input(method, t0), path, code)); + match code { + Code::PolicyUnavailable => { + let why = app.policy.last_error().unwrap_or_default(); + app.warn_limited("policy_unavailable", &format!("policy unavailable: {why}")); + } + Code::BrokerUnavailable => { + app.warn_limited("broker_unavailable", "credential store unavailable"); + } + _ => {} + } + deny_response(shape, code) +} + +/// The dialect of the route named in a path whose caller key is not verified. +/// Only used to choose how to word a refusal; the name is never logged. +fn guess_shape(app: &App, path: &str) -> ErrorShape { + let Some(ap) = ApPath::split(path) else { + return ErrorShape::Json; + }; + match app.policy.current() { + Ok(p) => p + .route(ap.unverified_route()) + .map(|r| r.error_shape) + .unwrap_or_default(), + Err(_) => ErrorShape::Json, + } +} + +fn is_websocket_upgrade(h: &HeaderMap) -> bool { + h.get_all(header::UPGRADE).iter().any(|v| { + v.to_str() + .is_ok_and(|s| s.to_ascii_lowercase().contains("websocket")) + }) +} + +/// Exactly one surrogate in the route's header, in the route's scheme. +fn presented_surrogate<'a>( + headers: &'a HeaderMap, + route: &ap_core::config::RouteCfg, +) -> Result<&'a str, Code> { + let vals: Vec<&HeaderValue> = headers + .get_all(route.surrogate_header.as_str()) + .iter() + .collect(); + match vals.as_slice() { + [] => Err(Code::SurrogateMissing), + [one] => { + let raw = one.to_str().map_err(|_| Code::SurrogateMalformed)?; + if raw.contains(',') { + return Err(Code::SurrogateAmbiguous); + } + if route.surrogate_scheme.is_empty() { + return Ok(raw); + } + let p = route.surrogate_scheme.len() + 1; + let b = raw.as_bytes(); + if b.len() > p + && b[..route.surrogate_scheme.len()] + .eq_ignore_ascii_case(route.surrogate_scheme.as_bytes()) + && b[route.surrogate_scheme.len()] == b' ' + { + Ok(&raw[p..]) + } else { + Err(Code::SurrogateMalformed) + } + } + _ => Err(Code::SurrogateAmbiguous), + } +} + +/// Read and discard what the client is still sending, bounded in bytes and +/// time, so the refusal is delivered instead of being lost to a connection +/// reset. A client that sends more than the limit gets the reset. +pub async fn drain(body: Body, limit: u64) { + let mut s = body.into_data_stream(); + let mut n = 0u64; + let _ = tokio::time::timeout(std::time::Duration::from_secs(10), async { + while let Some(Ok(b)) = s.next().await { + n += b.len() as u64; + if n > limit { + break; + } + } + }) + .await; +} + +/// Counts request-body bytes and fails the stream once the cap is crossed. +fn capped( + body: Body, + max: u64, + over: Arc, +) -> impl futures_util::Stream> + Send + 'static { + let seen = AtomicU64::new(0); + body.into_data_stream().map(move |r| match r { + Ok(b) => { + let total = seen.fetch_add(b.len() as u64, Ordering::Relaxed) + b.len() as u64; + if total > max { + over.store(true, Ordering::Relaxed); + Err(std::io::Error::other("request body over the cap")) + } else { + Ok(b) + } + } + Err(_) => Err(std::io::Error::other("request body read failed")), + }) +} + +async fn handle(app: Arc, req: Request) -> Response { + let t0 = Instant::now(); + let (parts, body) = req.into_parts(); + let method = parts.method.as_str().to_owned(); + let none = RoutePath::none(); + let mut ctx = Ctx::default(); + + // 1. CONNECT and WebSocket upgrades. + if parts.method == Method::CONNECT { + return refuse( + &app, + &ctx, + &method, + t0, + &none, + ErrorShape::Json, + Code::ConnectRefused, + ); + } + if is_websocket_upgrade(&parts.headers) { + let shape = guess_shape(&app, parts.uri.path()); + return refuse( + &app, + &ctx, + &method, + t0, + &none, + shape, + Code::WebsocketUnsupported, + ); + } + + // 2. Canonicalize: origin-form, exactly one Host equal to a listener + // authority, no ambiguous path. + if parts.uri.scheme().is_some() || parts.uri.authority().is_some() { + let shape = guess_shape(&app, parts.uri.path()); + return refuse(&app, &ctx, &method, t0, &none, shape, Code::AbsoluteForm); + } + let hosts: Vec<&HeaderValue> = parts.headers.get_all(header::HOST).iter().collect(); + let host_ok = hosts.len() == 1 + && hosts[0] + .to_str() + .is_ok_and(|h| app.authorities.iter().any(|a| a == h)); + if !host_ok { + let shape = guess_shape(&app, parts.uri.path()); + return refuse(&app, &ctx, &method, t0, &none, shape, Code::HostRejected); + } + let path = parts.uri.path(); + if path_ambiguous(path) { + let shape = guess_shape(&app, path); + return refuse(&app, &ctx, &method, t0, &none, shape, Code::PathAmbiguous); + } + + // 3. /ap///...: the caller key is checked against the + // policy's hash, in constant time, and dropped. + let Some(ap) = ApPath::split(path) else { + return refuse( + &app, + &ctx, + &method, + t0, + &none, + ErrorShape::Json, + Code::RouteUnknown, + ); + }; + let policy = match app.policy.current() { + Ok(p) => p, + Err(code) => { + return refuse(&app, &ctx, &method, t0, &none, ErrorShape::Json, code); + } + }; + let shape_unverified = policy + .route(ap.unverified_route()) + .map(|r| r.error_shape) + .unwrap_or_default(); + let Some(vp) = ap.verify(|k| policy.caller_matches(k)) else { + return refuse( + &app, + &ctx, + &method, + t0, + &none, + shape_unverified, + Code::CallerRejected, + ); + }; + ctx.identity = Some(policy.identity().to_string()); + let rp = vp.route_relative(); + let Some(route) = policy.route(vp.route()) else { + return refuse( + &app, + &ctx, + &method, + t0, + &rp, + ErrorShape::Json, + Code::RouteUnknown, + ); + }; + ctx.route = Some(route.name.clone()); + let shape = route.error_shape; + let deny = |ctx: &Ctx, code: Code| refuse(&app, ctx, &method, t0, &rp, shape, code); + + // 4. Exactly one surrogate, well formed. + let hash = match presented_surrogate(&parts.headers, route).and_then(hash_surrogate) { + Ok(h) => h, + Err(code) => return deny(&ctx, code), + }; + + // 5. Registry lookup by sha256(surrogate). + let binding = match app.broker.admit(&hash, &route.name, &policy) { + Ok(b) => b, + Err(code) => return deny(&ctx, code), + }; + ctx.session = Some(binding.session.clone()); + ctx.generation = Some(binding.generation); + + // 6. Policy: method, path and AWS target against the grants. + let targets: Vec<&[u8]> = parts + .headers + .get_all("x-amz-target") + .iter() + .map(|v| v.as_bytes()) + .collect(); + if let [one] = targets.as_slice() { + ctx.aws_target = std::str::from_utf8(one).ok().map(str::to_string); + } + let credential_id = match policy.authorize( + &binding.credentials, + &route.name, + &method, + &vp.rest_path(), + &targets, + ) { + Ok(id) => id.to_string(), + Err(code) => return deny(&ctx, code), + }; + + // 7. The credential value, read from the store now. + let secret = match app.broker.secret(&credential_id, &policy) { + Ok(s) => s, + Err(code) => return deny(&ctx, code), + }; + let mut value = Vec::with_capacity(route.credential_scheme.len() + 1 + secret.expose().len()); + if !route.credential_scheme.is_empty() { + value.extend_from_slice(route.credential_scheme.as_bytes()); + value.push(b' '); + } + value.extend_from_slice(secret.expose()); + let mut credential_value = match HeaderValue::from_bytes(&value) { + Ok(v) => v, + Err(_) => return deny(&ctx, Code::BrokerUnavailable), + }; + credential_value.set_sensitive(true); + drop(secret); + + // Body cap: a declared length over the cap is refused before anything goes out. + let declared: Option = parts + .headers + .get(header::CONTENT_LENGTH) + .and_then(|v| v.to_str().ok()) + .and_then(|v| v.parse().ok()); + if declared.is_some_and(|n| n > app.max_body) { + drain(body, DRAIN_LIMIT).await; + return deny(&ctx, Code::BodyTooLarge); + } + let has_body = + declared.is_some_and(|n| n > 0) || parts.headers.contains_key(header::TRANSFER_ENCODING); + + // 8. Strip every auth and hop-by-hop header, keep the rest (so + // `pass_headers` survive), set exactly one credential header. + let mut h = parts.headers.clone(); + strip_request_headers(&mut h); + let cred_name = HeaderName::from_bytes(route.credential_header.as_bytes()).unwrap(); + h.insert(cred_name, credential_value); + if let Some(n) = declared { + h.insert(header::CONTENT_LENGTH, HeaderValue::from(n)); + } + let query = parts + .uri + .query() + .map(|q| format!("?{q}")) + .unwrap_or_default(); + let url = format!("https://{}{}{}", route.authority(), vp.rest_path(), query); + + let over = Arc::new(AtomicBool::new(false)); + let mut rb = app.client.request(parts.method.clone(), url).headers(h); + if has_body { + rb = rb.body(reqwest::Body::wrap_stream(capped( + body, + app.max_body, + over.clone(), + ))); + } + let up = match rb.send().await { + Ok(r) => r, + Err(_) => { + // The error text embeds the URL: only the fixed code is used. + let code = if over.load(Ordering::Relaxed) { + Code::BodyTooLarge + } else { + Code::UpstreamUnavailable + }; + return deny(&ctx, code); + } + }; + + let status = up.status(); + app.audit.request(&AuditRec::allowed( + &ctx.input(&method, t0), + &rp, + status.as_u16(), + )); + let mut r = Response::builder().status(status); + for (k, v) in up.headers() { + if !HOP_HEADERS.contains(&k.as_str()) || k == header::CONTENT_LENGTH { + r = r.header(k, v); + } + } + // Streamed chunk by chunk (SSE, AWS eventstream): nothing is buffered. An + // upstream failure mid-stream closes the client stream without a synthetic + // success, and adds one audit line. + let (app2, ctx2, rp2, method2) = (app.clone(), ctx.clone(), rp.clone(), method.clone()); + let code = status.as_u16(); + let mut logged = false; + let stream = up.bytes_stream().map(move |chunk| { + if chunk.is_err() && !logged { + logged = true; + app2.audit.request(&AuditRec::failed( + &ctx2.input(&method2, t0), + &rp2, + "upstream_reset", + code, + )); + } + chunk + }); + r.body(Body::from_stream(stream)).unwrap() +} + +#[cfg(test)] +mod tests { + use super::*; + use ap_core::testing::sample_toml; + use ap_core::Policy; + + fn route(name: &str) -> ap_core::config::RouteCfg { + let p = Policy::parse(sample_toml().as_bytes()).unwrap(); + p.route(name).unwrap().clone() + } + + fn headers(pairs: &[(&str, &str)]) -> HeaderMap { + let mut h = HeaderMap::new(); + for (k, v) in pairs { + h.append( + HeaderName::from_bytes(k.as_bytes()).unwrap(), + HeaderValue::from_str(v).unwrap(), + ); + } + h + } + + #[test] + fn surrogate_extraction() { + let bearer = route("kiro-krs"); + let key = route("anthropic"); + let s = format!("aps_{}", "ab".repeat(32)); + let h = headers(&[("authorization", &format!("Bearer {s}"))]); + assert_eq!(presented_surrogate(&h, &bearer), Ok(s.as_str())); + let h = headers(&[("authorization", &format!("bearer {s}"))]); + assert_eq!(presented_surrogate(&h, &bearer), Ok(s.as_str())); + assert_eq!( + presented_surrogate(&headers(&[]), &bearer), + Err(Code::SurrogateMissing) + ); + let h = headers(&[("authorization", &s)]); + assert_eq!( + presented_surrogate(&h, &bearer), + Err(Code::SurrogateMalformed) + ); + let h = headers(&[("authorization", "Bearer")]); + assert_eq!( + presented_surrogate(&h, &bearer), + Err(Code::SurrogateMalformed) + ); + let h = headers(&[ + ("authorization", &format!("Bearer {s}")), + ("authorization", &format!("Bearer {s}")), + ]); + assert_eq!( + presented_surrogate(&h, &bearer), + Err(Code::SurrogateAmbiguous) + ); + let h = headers(&[("authorization", &format!("Bearer {s}, Bearer {s}"))]); + assert_eq!( + presented_surrogate(&h, &bearer), + Err(Code::SurrogateAmbiguous) + ); + // schemeless route + let h = headers(&[("x-api-key", &s)]); + assert_eq!(presented_surrogate(&h, &key), Ok(s.as_str())); + let h = headers(&[("x-api-key", &format!("Bearer {s}"))]); + assert_eq!( + presented_surrogate(&h, &key).and_then(hash_surrogate), + Err(Code::SurrogateMalformed) + ); + } + + #[test] + fn websocket_detection() { + assert!(is_websocket_upgrade(&headers(&[("upgrade", "WebSocket")]))); + assert!(is_websocket_upgrade(&headers(&[( + "upgrade", + "h2c, websocket" + )]))); + assert!(!is_websocket_upgrade(&headers(&[("upgrade", "h2c")]))); + assert!(!is_websocket_upgrade(&headers(&[]))); + } + + #[tokio::test] + async fn cap_fails_the_stream_and_sets_the_flag() { + let over = Arc::new(AtomicBool::new(false)); + let s = capped(Body::from(vec![0u8; 100]), 99, over.clone()); + let items: Vec<_> = s.collect().await; + assert!(items.iter().any(|r| r.is_err())); + assert!(over.load(Ordering::Relaxed)); + + let over = Arc::new(AtomicBool::new(false)); + let s = capped(Body::from(vec![0u8; 100]), 100, over.clone()); + let items: Vec<_> = s.collect().await; + assert!(items.iter().all(|r| r.is_ok())); + assert!(!over.load(Ordering::Relaxed)); + } +} diff --git a/crates/ap-proxy/src/app.rs b/crates/ap-proxy/src/app.rs new file mode 100644 index 0000000..a1c4b7e --- /dev/null +++ b/crates/ap-proxy/src/app.rs @@ -0,0 +1,56 @@ +//! Shared state of one proxy process. + +use crate::audit::Audit; +use ap_broker::{LocalBroker, SessionPlane}; +use ap_core::PolicyStore; +use std::collections::HashMap; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +pub struct App { + pub policy: PolicyStore, + pub broker: LocalBroker, + pub plane: Arc, + pub client: reqwest::Client, + /// Exact `Host` values the agent listener accepts. + pub authorities: Vec, + pub max_body: u64, + pub audit: Audit, + warned: Mutex>, +} + +const WARN_EVERY: Duration = Duration::from_secs(30); + +impl App { + pub fn new( + policy: PolicyStore, + broker: LocalBroker, + client: reqwest::Client, + authorities: Vec, + max_body: u64, + ) -> App { + let plane = broker.plane().clone(); + App { + policy, + broker, + plane, + client, + authorities, + max_body, + audit: Audit::default(), + warned: Mutex::new(HashMap::new()), + } + } + + /// An operator message on stderr, at most once per `WARN_EVERY` per key. + /// Callers pass fixed text or the policy loader's own message; never + /// anything taken from a request. + pub fn warn_limited(&self, key: &'static str, msg: &str) { + let mut w = self.warned.lock().unwrap(); + let due = w.get(key).is_none_or(|t| t.elapsed() >= WARN_EVERY); + if due { + w.insert(key, Instant::now()); + eprintln!("auth-proxy: {msg}"); + } + } +} diff --git a/crates/ap-proxy/src/args.rs b/crates/ap-proxy/src/args.rs new file mode 100644 index 0000000..e5c8fea --- /dev/null +++ b/crates/ap-proxy/src/args.rs @@ -0,0 +1,280 @@ +//! Command line and environment. Every option has an `AP_*` environment +//! twin; the command line wins. Any problem is a startup failure (exit 2). + +use std::net::SocketAddr; +use std::path::PathBuf; + +pub const USAGE: &str = "\ +auth-proxy: credential-swapping reverse proxy (Phase 1, Kubernetes) + + --policy PATH policy file (TOML, one identity) AP_POLICY (required) + --secrets-dir DIR credential Secret volumes (proxy-only) AP_SECRETS_DIR + [/run/secrets/auth-proxy] + --listen ADDR agent listener, loopback only, e.g. AP_LISTEN + 127.0.0.1:18080 (else policy [listener]) + --session-socket PATH session plane (shared with the agent) AP_SESSION_SOCKET + [/run/auth-proxy/session.sock] + --session-socket-mode OCT mode of the session socket AP_SESSION_SOCKET_MODE [660] + --admin-socket PATH admin plane (proxy-only mount) AP_ADMIN_SOCKET + [/run/auth-proxy-admin/admin.sock] + --state-dir DIR proxy-private state (authority token hash) AP_STATE_DIR + [/var/lib/auth-proxy] + --max-body-bytes N request body cap, 413 above it AP_MAX_BODY_BYTES [33554432] + --ca-file PATH PEM roots for upstream TLS (replaces the AP_CA_FILE + built-in roots; used by tests) + --authority-lease-secs N authority lease, >= 3 AP_AUTHORITY_LEASE_SECS [90] + --session-lease-secs N session lease, >= 1 AP_SESSION_LEASE_SECS [900] + --absolute-ttl-secs N session absolute TTL AP_ABSOLUTE_TTL_SECS [43200] + --max-sessions N registered sessions cap AP_MAX_SESSIONS [256] + --help + +Exit codes: 0 clean stop, 2 invalid arguments, policy or sockets. +"; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Args { + pub policy: PathBuf, + pub secrets_dir: PathBuf, + pub listen: Option, + pub session_socket: PathBuf, + pub session_socket_mode: u32, + pub admin_socket: PathBuf, + pub state_dir: PathBuf, + pub max_body_bytes: u64, + pub ca_file: Option, + pub authority_lease_secs: u64, + pub session_lease_secs: u64, + pub absolute_ttl_secs: u64, + pub max_sessions: usize, +} + +pub enum Parsed { + Run(Box), + Help, +} + +type Env<'a> = &'a dyn Fn(&str) -> Option; + +struct Opt { + flag: &'static str, + env: &'static str, +} + +const OPTS: &[Opt] = &[ + Opt { + flag: "--policy", + env: "AP_POLICY", + }, + Opt { + flag: "--secrets-dir", + env: "AP_SECRETS_DIR", + }, + Opt { + flag: "--listen", + env: "AP_LISTEN", + }, + Opt { + flag: "--session-socket", + env: "AP_SESSION_SOCKET", + }, + Opt { + flag: "--session-socket-mode", + env: "AP_SESSION_SOCKET_MODE", + }, + Opt { + flag: "--admin-socket", + env: "AP_ADMIN_SOCKET", + }, + Opt { + flag: "--state-dir", + env: "AP_STATE_DIR", + }, + Opt { + flag: "--max-body-bytes", + env: "AP_MAX_BODY_BYTES", + }, + Opt { + flag: "--ca-file", + env: "AP_CA_FILE", + }, + Opt { + flag: "--authority-lease-secs", + env: "AP_AUTHORITY_LEASE_SECS", + }, + Opt { + flag: "--session-lease-secs", + env: "AP_SESSION_LEASE_SECS", + }, + Opt { + flag: "--absolute-ttl-secs", + env: "AP_ABSOLUTE_TTL_SECS", + }, + Opt { + flag: "--max-sessions", + env: "AP_MAX_SESSIONS", + }, +]; + +pub fn parse(argv: impl IntoIterator, env: Env<'_>) -> Result { + let mut given: Vec> = vec![None; OPTS.len()]; + let mut it = argv.into_iter(); + while let Some(a) = it.next() { + if a == "--help" || a == "-h" { + return Ok(Parsed::Help); + } + let (flag, inline) = match a.split_once('=') { + Some((f, v)) => (f.to_string(), Some(v.to_string())), + None => (a.clone(), None), + }; + let i = OPTS + .iter() + .position(|o| o.flag == flag) + .ok_or_else(|| format!("unknown argument {flag:?} (see --help)"))?; + let v = match inline { + Some(v) => v, + None => it.next().ok_or_else(|| format!("{flag} needs a value"))?, + }; + if given[i].replace(v).is_some() { + return Err(format!("{flag} given twice")); + } + } + let get = |flag: &str| -> Option { + let i = OPTS.iter().position(|o| o.flag == flag).unwrap(); + given[i] + .clone() + .or_else(|| env(OPTS[i].env).filter(|v| !v.is_empty())) + }; + let num = |flag: &str, default: u64, min: u64| -> Result { + match get(flag) { + None => Ok(default), + Some(v) => { + let n: u64 = v + .parse() + .map_err(|_| format!("{flag} must be a number, got {v:?}"))?; + if n < min { + return Err(format!("{flag} must be at least {min}")); + } + Ok(n) + } + } + }; + let path = |flag: &str, default: Option<&str>| -> Result, String> { + match get(flag).or_else(|| default.map(String::from)) { + None => Ok(None), + Some(p) if p.is_empty() || p.contains('\0') => Err(format!("{flag}: bad path")), + Some(p) => Ok(Some(PathBuf::from(p))), + } + }; + + let policy = path("--policy", None)?.ok_or("--policy (or AP_POLICY) is required")?; + let listen = match get("--listen") { + None => None, + Some(v) => Some( + v.parse::() + .map_err(|_| format!("--listen must be ip:port, got {v:?}"))?, + ), + }; + let mode = match get("--session-socket-mode") { + None => 0o660, + Some(v) => u32::from_str_radix(&v, 8) + .ok() + .filter(|m| *m <= 0o777 && m & 0o600 == 0o600) + .ok_or("--session-socket-mode must be octal with owner read/write, e.g. 660")?, + }; + Ok(Parsed::Run(Box::new(Args { + policy, + secrets_dir: path("--secrets-dir", Some("/run/secrets/auth-proxy"))?.unwrap(), + listen, + session_socket: path("--session-socket", Some("/run/auth-proxy/session.sock"))?.unwrap(), + session_socket_mode: mode, + admin_socket: path("--admin-socket", Some("/run/auth-proxy-admin/admin.sock"))?.unwrap(), + state_dir: path("--state-dir", Some("/var/lib/auth-proxy"))?.unwrap(), + max_body_bytes: num("--max-body-bytes", 32 * 1024 * 1024, 1)?, + ca_file: path("--ca-file", None)?, + authority_lease_secs: num( + "--authority-lease-secs", + ap_broker::DEFAULT_AUTHORITY_LEASE_SECS, + ap_broker::MIN_AUTHORITY_LEASE_SECS, + )?, + session_lease_secs: num( + "--session-lease-secs", + ap_broker::DEFAULT_SESSION_LEASE_SECS, + 1, + )?, + absolute_ttl_secs: num( + "--absolute-ttl-secs", + ap_broker::DEFAULT_ABSOLUTE_TTL_SECS, + 1, + )?, + max_sessions: num("--max-sessions", ap_broker::DEFAULT_MAX_SESSIONS as u64, 1)? as usize, + }))) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn run(args: &[&str], env: &[(&str, &str)]) -> Result { + let env: Vec<(String, String)> = env + .iter() + .map(|(k, v)| (k.to_string(), v.to_string())) + .collect(); + let lookup = move |k: &str| env.iter().find(|(n, _)| n == k).map(|(_, v)| v.clone()); + match parse(args.iter().map(|s| s.to_string()), &lookup)? { + Parsed::Run(a) => Ok(*a), + Parsed::Help => Err("help".into()), + } + } + + #[test] + fn defaults_match_the_design() { + let a = run(&["--policy", "/p.toml"], &[]).unwrap(); + assert_eq!(a.authority_lease_secs, 90); + assert_eq!(a.session_lease_secs, 900); + assert_eq!(a.absolute_ttl_secs, 43_200); + assert_eq!(a.max_body_bytes, 32 * 1024 * 1024); + assert_eq!(a.session_socket_mode, 0o660); + assert_eq!(a.max_sessions, 256); + assert!(a.listen.is_none()); + } + + #[test] + fn command_line_beats_environment() { + let a = run( + &["--policy", "/a", "--listen=127.0.0.1:1"], + &[("AP_POLICY", "/b"), ("AP_LISTEN", "127.0.0.1:2")], + ) + .unwrap(); + assert_eq!(a.policy, PathBuf::from("/a")); + assert_eq!(a.listen.unwrap().port(), 1); + let a = run(&[], &[("AP_POLICY", "/b")]).unwrap(); + assert_eq!(a.policy, PathBuf::from("/b")); + } + + #[test] + fn bad_input_is_an_error() { + for (args, env) in [ + (vec![], vec![]), + (vec!["--policy"], vec![]), + (vec!["--policy", "/p", "--nope", "1"], vec![]), + (vec!["--policy", "/p", "--policy", "/q"], vec![]), + (vec!["--policy", "/p", "--listen", "localhost"], vec![]), + ( + vec!["--policy", "/p", "--authority-lease-secs", "2"], + vec![], + ), + (vec!["--policy", "/p", "--max-sessions", "0"], vec![]), + (vec!["--policy", "/p", "--max-body-bytes", "x"], vec![]), + ( + vec!["--policy", "/p", "--session-socket-mode", "999"], + vec![], + ), + ( + vec!["--policy", "/p", "--session-socket-mode", "060"], + vec![], + ), + ] { + assert!(run(&args, &env).is_err(), "{args:?}"); + } + } +} diff --git a/crates/ap-proxy/src/audit.rs b/crates/ap-proxy/src/audit.rs new file mode 100644 index 0000000..8e59856 --- /dev/null +++ b/crates/ap-proxy/src/audit.rs @@ -0,0 +1,136 @@ +//! The audit sink: one JSON line per decision on stdout. +//! +//! Request lines come from `ap_core::AuditRec`, which cannot hold the +//! `/ap/` prefix, a surrogate, a token or a credential. Session- +//! plane and admin lines are built here from fixed labels, counts, and ids that +//! passed `safe_field`. A failed write is counted and never refuses a request +//! (durable, fail-closed audit belongs to RFC Q5). + +use ap_core::canon::safe_field; +use ap_core::AuditRec; +use std::io::Write; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::time::{SystemTime, UNIX_EPOCH}; + +#[derive(Default)] +pub struct Audit { + write_failures: AtomicU64, +} + +pub fn now_ms() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_millis() as u64) + .unwrap_or(0) +} + +/// First 8 hex characters of a well-formed `surrogate_sha256`, else `None`. +/// The hash prefix identifies a registration in the log; it is not the +/// surrogate and cannot be turned into one. +pub fn hash8(h: &str) -> Option { + let ok = h.len() == 64 + && h.bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)); + ok.then(|| h[..8].to_string()) +} + +/// What a session-plane or admin call tells the log. +#[derive(Default)] +pub struct PlaneEvent<'a> { + /// Fixed label: `hello`, `register`, `renew`, `revoke`, `resync`, `revoke-all`, `status`. + pub call: &'static str, + pub session: Option<&'a str>, + pub generation: Option, + pub hash8: Option<&'a str>, + /// Entries in a renew or resync list. + pub count: Option, + pub status: u16, + /// `ok` or a fixed error code. + pub result: &'a str, +} + +impl PlaneEvent<'_> { + pub fn to_line(&self, t_ms: u64) -> String { + serde_json::json!({ + "t": t_ms, + "plane": self.call, + "session": self.session.map(safe_field).unwrap_or_else(|| "-".into()), + "generation": self.generation, + "hash8": self.hash8.unwrap_or("-"), + "count": self.count, + "status": self.status, + "result": safe_field(self.result), + }) + .to_string() + } +} + +impl Audit { + fn write_line(&self, line: &str) { + let mut out = std::io::stdout().lock(); + if writeln!(out, "{line}").is_err() { + self.write_failures.fetch_add(1, Ordering::Relaxed); + } + } + + pub fn request(&self, rec: &AuditRec) { + self.write_line(&rec.to_line(now_ms())); + } + + pub fn plane(&self, ev: &PlaneEvent<'_>) { + self.write_line(&ev.to_line(now_ms())); + } + + #[allow(dead_code)] + pub fn write_failures(&self) -> u64 { + self.write_failures.load(Ordering::Relaxed) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn plane_line_has_ids_and_no_free_text() { + let line = PlaneEvent { + call: "register", + session: Some("sess-1"), + generation: Some(4), + hash8: Some("deadbeef"), + count: None, + status: 201, + result: "ok", + } + .to_line(7); + let v: serde_json::Value = serde_json::from_str(&line).unwrap(); + assert_eq!(v["plane"], "register"); + assert_eq!(v["session"], "sess-1"); + assert_eq!(v["hash8"], "deadbeef"); + assert_eq!(v["generation"], 4); + assert_eq!(v["status"], 201); + } + + #[test] + fn key_looking_ids_are_masked() { + let bad = format!("aps_{}", "0".repeat(64)); + let line = PlaneEvent { + call: "revoke", + session: Some(&bad), + result: "ok", + ..Default::default() + } + .to_line(1); + assert!(!line.contains("aps_"), "{line}"); + let v: serde_json::Value = serde_json::from_str(&line).unwrap(); + assert_eq!(v["session"], "-"); + } + + #[test] + fn hash8_only_for_well_formed_hashes() { + assert_eq!(hash8(&"ab".repeat(32)).as_deref(), Some("abababab")); + assert_eq!(hash8("abc"), None); + assert_eq!(hash8(&"AB".repeat(32)), None); + assert_eq!(hash8(&format!("{}g", "a".repeat(63))), None); + } +} diff --git a/crates/ap-proxy/src/main.rs b/crates/ap-proxy/src/main.rs new file mode 100644 index 0000000..cc1c9c5 --- /dev/null +++ b/crates/ap-proxy/src/main.rs @@ -0,0 +1,245 @@ +//! `auth-proxy`: the Phase 1 credential-swapping reverse proxy (Kubernetes). +//! +//! One process: the agent listener (the only TCP listener, loopback only), the +//! session-plane Unix socket, the admin Unix socket, the in-process broker and +//! the S1 file store. A startup problem is exit code 2 with the reason on +//! stderr, so a bad config is CrashLoopBackOff and never a half-working proxy. + +mod admin; +mod agent; +mod app; +mod args; +mod audit; +mod plane_http; +mod sock; + +use ap_broker::{FileStore, LocalBroker, PlaneConfig, RegistryConfig, SessionPlane, SystemClock}; +use ap_core::PolicyStore; +use app::App; +use args::{Args, Parsed}; +use axum::serve::ListenerExt; +use std::net::SocketAddr; +use std::sync::Arc; +use std::time::Duration; + +fn main() { + // A panic message can embed the value that caused it. Print a fixed line. + std::panic::set_hook(Box::new(|_| { + eprintln!("auth-proxy: internal error (panic); details withheld"); + })); + let rt = tokio::runtime::Builder::new_multi_thread() + .enable_all() + .build() + .expect("tokio runtime"); + let code = rt.block_on(real_main()); + std::process::exit(code); +} + +async fn real_main() -> i32 { + let args = match args::parse(std::env::args().skip(1), &|k| std::env::var(k).ok()) { + Ok(Parsed::Run(a)) => *a, + Ok(Parsed::Help) => { + print!("{}", args::USAGE); + return 0; + } + Err(e) => { + eprintln!("auth-proxy: {e}"); + return 2; + } + }; + match run(args).await { + Ok(()) => 0, + Err(e) => { + eprintln!("auth-proxy: {e}"); + 2 + } + } +} + +fn router(h: H, app: Arc) -> axum::Router +where + H: axum::handler::Handler>, + T: 'static, +{ + axum::Router::new().fallback(h).with_state(app) +} + +fn default_authorities(listen: SocketAddr) -> Vec { + let host = if listen.is_ipv4() { + "127.0.0.1" + } else { + "[::1]" + }; + vec![ + format!("{host}:{}", listen.port()), + format!("localhost:{}", listen.port()), + ] +} + +fn build_client(args: &Args, policy: &ap_core::Policy) -> Result { + let mut b = reqwest::Client::builder() + .use_rustls_tls() + .https_only(true) + // Never follow redirects: the client gets the 3xx and the credential + // stays with this process. + .redirect(reqwest::redirect::Policy::none()) + .tcp_nodelay(true) + .connect_timeout(Duration::from_secs(10)) + .pool_idle_timeout(Duration::from_secs(60)); + if let Some(ca) = &args.ca_file { + let pem = std::fs::read(ca).map_err(|e| format!("read --ca-file: {}", e.kind()))?; + let cert = reqwest::Certificate::from_pem(&pem) + .map_err(|_| "--ca-file is not a PEM certificate".to_string())?; + b = b.tls_built_in_root_certs(false).add_root_certificate(cert); + } + // Test-only resolver override from the policy (like curl --resolve). The + // destination identity (SNI, Host, certificate name) stays the route host. + // It is read at startup; a reload that adds one has no effect. + for r in &policy.config().routes { + if let Some(a) = r.connect_to { + b = b.resolve(&r.host, a); + } + } + b.build() + .map_err(|_| "cannot build the upstream client".to_string()) +} + +async fn run(args: Args) -> Result<(), String> { + // Policy: the whole file is validated, or the proxy does not start. + let store = PolicyStore::open(&args.policy).map_err(|e| format!("policy rejected: {e}"))?; + let snap = store.current().map_err(|_| { + format!( + "policy rejected: {}", + store.last_error().unwrap_or_else(|| "unavailable".into()) + ) + })?; + + // Exactly one TCP listener, on loopback. + let policy_listener = snap.config().listener.as_ref(); + let listen = match (args.listen, policy_listener.map(|l| l.listen)) { + (Some(a), Some(b)) if a != b => { + return Err("--listen differs from the policy's [listener].listen".into()) + } + (Some(a), _) | (None, Some(a)) => a, + (None, None) => { + return Err("no listener: pass --listen or set [listener] in the policy".into()) + } + }; + if !listen.ip().is_loopback() || listen.port() == 0 { + return Err("the agent listener must be a loopback address with a non-zero port".into()); + } + let authorities = match policy_listener { + Some(l) => l.effective_authorities(), + None => default_authorities(listen), + }; + + for c in &snap.config().credentials { + if !FileStore::supports(&c.source) { + return Err(format!( + "credential {}: this source kind is not supported in Phase 1 (use k8s: or file:)", + c.id + )); + } + } + + // State and the in-process broker. + std::fs::create_dir_all(&args.state_dir) + .map_err(|e| format!("create --state-dir: {}", e.kind()))?; + let plane = Arc::new(SessionPlane::new( + PlaneConfig { + registry: RegistryConfig { + lease: Duration::from_secs(args.session_lease_secs), + absolute_ttl: Duration::from_secs(args.absolute_ttl_secs), + max_sessions: args.max_sessions, + }, + authority_lease_secs: args.authority_lease_secs, + authority_state: Some(args.state_dir.join("authority.json")), + }, + Arc::new(SystemClock::new()), + )?); + let broker = LocalBroker::new(plane, Arc::new(FileStore::new(&args.secrets_dir))); + let client = build_client(&args, &snap)?; + drop(snap); + let app = Arc::new(App::new( + store, + broker, + client, + authorities, + args.max_body_bytes, + )); + + // The Unix sockets first, the TCP listener last: once the port answers, + // everything is up. + let session_l = sock::bind_unix(&args.session_socket, args.session_socket_mode) + .await + .map_err(|e| format!("session socket: {e}"))?; + if let Some(dir) = args.admin_socket.parent() { + if !dir.exists() { + use std::os::unix::fs::DirBuilderExt; + std::fs::DirBuilder::new() + .recursive(true) + .mode(0o700) + .create(dir) + .map_err(|e| format!("create admin socket dir: {}", e.kind()))?; + } + } + let admin_l = sock::bind_unix(&args.admin_socket, 0o600) + .await + .map_err(|e| format!("admin socket: {e}"))?; + let tcp = tokio::net::TcpListener::bind(listen) + .await + .map_err(|e| format!("bind listener: {}", e.kind()))? + // axum does not set TCP_NODELAY on accepted sockets; without it a + // streamed response meets the client's delayed ACK (+40 ms p99 measured). + .tap_io(|t| { + let _ = t.set_nodelay(true); + }); + + let mut tasks = tokio::task::JoinSet::new(); + tasks.spawn({ + let r = router(agent::handler, app.clone()); + async move { axum::serve(tcp, r).await.map_err(|e| e.kind()) } + }); + tasks.spawn({ + let r = router(plane_http::handler, app.clone()); + async move { axum::serve(session_l, r).await.map_err(|e| e.kind()) } + }); + tasks.spawn({ + let r = router(admin::handler, app.clone()); + async move { axum::serve(admin_l, r).await.map_err(|e| e.kind()) } + }); + + // Lease sweeper. Lookups also check expiry inline, so a lapsed lease is + // refused even before this runs; the sweeper frees memory and fires the + // authority-lapse revoke-all promptly. + let sweeper = app.plane.clone(); + tokio::spawn(async move { + let mut t = tokio::time::interval(Duration::from_secs(1)); + loop { + t.tick().await; + sweeper.session_count(); + } + }); + + eprintln!("auth-proxy: ready, agent listener on {listen}"); + + use tokio::signal::unix::{signal, SignalKind}; + let mut term = signal(SignalKind::terminate()).map_err(|e| format!("signal: {}", e.kind()))?; + let mut int = signal(SignalKind::interrupt()).map_err(|e| format!("signal: {}", e.kind()))?; + let outcome = tokio::select! { + _ = term.recv() => Ok(()), + _ = int.recv() => Ok(()), + r = tasks.join_next() => { + let kind = match r { + Some(Ok(Err(k))) => format!("{k:?}"), + Some(Err(_)) => "task failed".to_string(), + _ => "stopped".to_string(), + }; + Err(format!("a server stopped unexpectedly: {kind}")) + } + }; + for p in [&args.session_socket, &args.admin_socket] { + let _ = std::fs::remove_file(p); + } + outcome +} diff --git a/crates/ap-proxy/src/plane_http.rs b/crates/ap-proxy/src/plane_http.rs new file mode 100644 index 0000000..87f41da --- /dev/null +++ b/crates/ap-proxy/src/plane_http.rs @@ -0,0 +1,386 @@ +//! The session plane over the Unix socket: five calls, HTTP/1.1 and JSON, the +//! statuses of the design doc table. The socket is the only way in, so there +//! is no Host or path-prefix handling here. +//! +//! Every call is audited with the session id, generation, an 8-hex hash prefix +//! and the result. The surrogate never reaches this process (only its hash), +//! and the authority token is never logged or echoed except in the one +//! `hello` answer. + +use crate::agent::fixed_json; +use crate::app::App; +use crate::audit::{hash8, PlaneEvent}; +use ap_broker::{PlaneError, RegisterReq, SessionRef}; +use axum::body::Body; +use axum::extract::{Request, State}; +use axum::response::Response; +use futures_util::FutureExt; +use http::{header, HeaderMap, Method}; +use serde::{Deserialize, Serialize}; +use std::panic::AssertUnwindSafe; +use std::sync::Arc; + +const MAX_BODY: usize = 1024 * 1024; + +pub async fn handler(State(app): State>, req: Request) -> Response { + match AssertUnwindSafe(handle(app, req)).catch_unwind().await { + Ok(r) => r, + Err(_) => fixed_json( + 500, + r#"{"error":"internal_error","message":"auth-proxy: internal error"}"#, + ), + } +} + +fn json(status: u16, v: &T) -> Response { + Response::builder() + .status(status) + .header(header::CONTENT_TYPE, "application/json") + .body(Body::from(serde_json::to_vec(v).unwrap_or_default())) + .unwrap() +} + +fn error(status: u16, code: &str, message: &str) -> Response { + json( + status, + &serde_json::json!({"error": code, "message": message}), + ) +} + +fn plane_error(e: &PlaneError) -> Response { + error(e.status(), e.code(), &e.to_string()) +} + +fn no_content() -> Response { + Response::builder().status(204).body(Body::empty()).unwrap() +} + +/// `Authorization: Bearer `, exactly one header. +fn bearer(h: &HeaderMap) -> Option { + let mut it = h.get_all(header::AUTHORIZATION).iter(); + let v = it.next()?; + if it.next().is_some() { + return None; + } + let s = v.to_str().ok()?; + let (scheme, tok) = s.split_once(' ')?; + (scheme.eq_ignore_ascii_case("bearer") && !tok.is_empty()).then(|| tok.to_string()) +} + +enum Call { + Hello, + Register, + Renew, + Revoke(String, u64), + Resync, +} + +fn session_ok(s: &str) -> bool { + !s.is_empty() + && s.len() <= 128 + && s.bytes() + .all(|b| b.is_ascii_alphanumeric() || b"._:-".contains(&b)) +} + +enum Routed { + Found(Call), + BadPath(&'static str), + WrongMethod, + Unknown, +} + +fn route(method: &Method, path: &str) -> Routed { + use Routed::*; + match path { + "/v1/hello" => match *method { + Method::POST => Found(Call::Hello), + _ => WrongMethod, + }, + "/v1/renew" => match *method { + Method::POST => Found(Call::Renew), + _ => WrongMethod, + }, + "/v1/sessions" => match *method { + Method::POST => Found(Call::Register), + Method::PUT => Found(Call::Resync), + _ => WrongMethod, + }, + _ => match path.strip_prefix("/v1/sessions/") { + Some(rest) => { + if *method != Method::DELETE { + return WrongMethod; + } + let mut it = rest.split('/'); + match (it.next(), it.next(), it.next()) { + (Some(s), Some(g), None) if session_ok(s) => match g.parse::() { + Ok(g) => Found(Call::Revoke(s.to_string(), g)), + Err(_) => BadPath("generation must be an unsigned integer"), + }, + (Some(_), Some(_), None) => { + BadPath("session must be 1-128 characters of [A-Za-z0-9._:-]") + } + _ => Unknown, + } + } + None => Unknown, + }, + } +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct RenewBody { + sessions: Vec, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct ResyncBody { + sessions: Vec, +} + +fn too_big() -> Response { + error(413, "body_too_large", "request body over 1 MiB") +} + +/// `Err(())` means over the 1 MiB cap (or unreadable): the caller answers 413. +async fn read_body(headers: &HeaderMap, body: Body) -> Result, ()> { + let declared: Option = headers + .get(header::CONTENT_LENGTH) + .and_then(|v| v.to_str().ok()) + .and_then(|v| v.parse().ok()); + if declared.is_some_and(|n| n > MAX_BODY) { + crate::agent::drain(body, 4 * MAX_BODY as u64).await; + return Err(()); + } + axum::body::to_bytes(body, MAX_BODY) + .await + .map(|b| b.to_vec()) + .map_err(|_| ()) +} + +fn bad_json() -> PlaneError { + PlaneError::Invalid("request body is not the expected JSON".into()) +} + +async fn handle(app: Arc, req: Request) -> Response { + let (parts, body) = req.into_parts(); + let call = match route(&parts.method, parts.uri.path()) { + Routed::Found(c) => c, + Routed::BadPath(m) => return error(400, "invalid_request", m), + Routed::WrongMethod => return error(405, "method_not_allowed", "method not allowed"), + Routed::Unknown => return error(404, "not_found", "unknown session-plane call"), + }; + let token = bearer(&parts.headers); + let reply = |ev: PlaneEvent<'_>, r: Response| { + app.audit.plane(&PlaneEvent { + status: r.status().as_u16(), + ..ev + }); + r + }; + let fail = |ev: PlaneEvent<'_>, e: &PlaneError| { + reply( + PlaneEvent { + result: e.code(), + ..ev + }, + plane_error(e), + ) + }; + + if let Call::Hello = call { + let ev = PlaneEvent { + call: "hello", + result: "ok", + ..Default::default() + }; + // The body is `{}`; it is read (and bounded) but not interpreted. + if read_body(&parts.headers, body).await.is_err() { + return reply( + PlaneEvent { + result: "body_too_large", + ..ev + }, + too_big(), + ); + } + return match app.plane.hello() { + Ok(h) => reply(ev, json(201, &h)), + Err(e) => fail(ev, &e), + }; + } + + // Every other call carries the authority token. + let label = match &call { + Call::Register => "register", + Call::Renew => "renew", + Call::Revoke(..) => "revoke", + Call::Resync => "resync", + Call::Hello => unreachable!(), + }; + let ev0 = PlaneEvent { + call: label, + result: "ok", + ..Default::default() + }; + let Some(token) = token else { + return fail(ev0, &PlaneError::Unauthorized); + }; + let bytes = match read_body(&parts.headers, body).await { + Ok(b) => b, + Err(()) => { + return reply( + PlaneEvent { + result: "body_too_large", + ..ev0 + }, + too_big(), + ) + } + }; + + match call { + Call::Hello => unreachable!(), + Call::Revoke(session, generation) => { + let ev = PlaneEvent { + session: Some(&session), + generation: Some(generation), + ..ev0 + }; + match app.plane.revoke(&token, &session, generation) { + Ok(()) => reply(ev, no_content()), + Err(e) => fail(ev, &e), + } + } + Call::Renew => { + let Ok(b) = serde_json::from_slice::(&bytes) else { + return fail(ev0, &bad_json()); + }; + let ev = PlaneEvent { + count: Some(b.sessions.len()), + ..ev0 + }; + match app.plane.renew(&token, &b.sessions) { + Ok(ok) => reply(ev, json(200, &ok)), + Err(e) => fail(ev, &e), + } + } + Call::Register => { + let Ok(req) = serde_json::from_slice::(&bytes) else { + return fail(ev0, &bad_json()); + }; + let h8 = hash8(&req.surrogate_sha256); + let ev = PlaneEvent { + session: Some(&req.session), + generation: Some(req.generation), + hash8: h8.as_deref(), + ..ev0 + }; + let policy = match app.policy.current() { + Ok(p) => p, + Err(_) => { + return reply( + PlaneEvent { + result: "policy_unavailable", + ..ev + }, + policy_unavailable(), + ) + } + }; + match app.plane.register(&token, &policy, &req) { + Ok(ok) => reply(ev, json(201, &ok)), + Err(e) => fail(ev, &e), + } + } + Call::Resync => { + let Ok(b) = serde_json::from_slice::(&bytes) else { + return fail(ev0, &bad_json()); + }; + let ev = PlaneEvent { + count: Some(b.sessions.len()), + ..ev0 + }; + let policy = match app.policy.current() { + Ok(p) => p, + Err(_) => { + return reply( + PlaneEvent { + result: "policy_unavailable", + ..ev + }, + policy_unavailable(), + ) + } + }; + match app.plane.resync(&token, &policy, &b.sessions) { + Ok(ok) => reply(ev, json(200, &ok)), + Err(e) => fail(ev, &e), + } + } + } +} + +fn policy_unavailable() -> Response { + error(503, "policy_unavailable", "policy unavailable; refusing") +} + +#[cfg(test)] +mod tests { + use super::*; + use http::HeaderValue; + + #[test] + fn routing_table() { + let k = |m: &Method, p: &str| match route(m, p) { + Routed::Found(Call::Hello) => "hello".to_string(), + Routed::Found(Call::Register) => "register".into(), + Routed::Found(Call::Renew) => "renew".into(), + Routed::Found(Call::Resync) => "resync".into(), + Routed::Found(Call::Revoke(s, g)) => format!("revoke {s} {g}"), + Routed::BadPath(_) => "bad".into(), + Routed::WrongMethod => "405".into(), + Routed::Unknown => "404".into(), + }; + assert_eq!(k(&Method::POST, "/v1/hello"), "hello"); + assert_eq!(k(&Method::GET, "/v1/hello"), "405"); + assert_eq!(k(&Method::POST, "/v1/sessions"), "register"); + assert_eq!(k(&Method::PUT, "/v1/sessions"), "resync"); + assert_eq!(k(&Method::DELETE, "/v1/sessions"), "405"); + assert_eq!(k(&Method::POST, "/v1/renew"), "renew"); + assert_eq!( + k(&Method::DELETE, "/v1/sessions/a.b:c-d/7"), + "revoke a.b:c-d 7" + ); + assert_eq!(k(&Method::DELETE, "/v1/sessions/a/x"), "bad"); + assert_eq!(k(&Method::DELETE, "/v1/sessions/a%2f/1"), "bad"); + assert_eq!(k(&Method::DELETE, "/v1/sessions/a"), "404"); + assert_eq!(k(&Method::DELETE, "/v1/sessions/a/1/2"), "404"); + assert_eq!(k(&Method::POST, "/v1/sessions/a/1"), "405"); + assert_eq!(k(&Method::POST, "/v2/hello"), "404"); + assert_eq!(k(&Method::POST, "/"), "404"); + } + + #[test] + fn bearer_parsing() { + let mut h = HeaderMap::new(); + assert_eq!(bearer(&h), None); + h.append( + header::AUTHORIZATION, + HeaderValue::from_static("Bearer abc"), + ); + assert_eq!(bearer(&h).as_deref(), Some("abc")); + h.append( + header::AUTHORIZATION, + HeaderValue::from_static("Bearer abc"), + ); + assert_eq!(bearer(&h), None, "two headers"); + let mut h = HeaderMap::new(); + h.append(header::AUTHORIZATION, HeaderValue::from_static("Basic abc")); + assert_eq!(bearer(&h), None); + let mut h = HeaderMap::new(); + h.append(header::AUTHORIZATION, HeaderValue::from_static("Bearer ")); + assert_eq!(bearer(&h), None); + } +} diff --git a/crates/ap-proxy/src/sock.rs b/crates/ap-proxy/src/sock.rs new file mode 100644 index 0000000..03d848a --- /dev/null +++ b/crates/ap-proxy/src/sock.rs @@ -0,0 +1,107 @@ +//! Unix socket binding with the stale-socket rule from the design doc: a +//! socket file left by a dead proxy is replaced only after a connect probe gets +//! no answer. File identity (device and inode) is not used, because ext4 can +//! hand a successor the predecessor's inode number. A live socket, or a path +//! that is not a socket, is a startup failure. + +use std::os::unix::fs::{FileTypeExt, PermissionsExt}; +use std::path::{Path, PathBuf}; +use std::time::Duration; +use tokio::net::{UnixListener, UnixStream}; + +fn sibling(path: &Path, suffix: &str) -> PathBuf { + let mut s = path.as_os_str().to_os_string(); + s.push(suffix); + PathBuf::from(s) +} + +/// Bind `path` with `mode`. The socket is bound under a temporary name, +/// chmod-ed, then renamed into place, so it is never reachable with the wrong +/// mode. +pub async fn bind_unix(path: &Path, mode: u32) -> Result { + if let Some(dir) = path.parent() { + if !dir.as_os_str().is_empty() && !dir.exists() { + std::fs::create_dir_all(dir).map_err(|e| format!("create socket dir: {}", e.kind()))?; + } + } + match std::fs::symlink_metadata(path) { + Ok(md) if md.file_type().is_socket() => { + match tokio::time::timeout(Duration::from_secs(2), UnixStream::connect(path)).await { + Ok(Ok(_)) => { + return Err("socket is live: another auth-proxy is already running".into()) + } + Ok(Err(e)) + if matches!( + e.kind(), + std::io::ErrorKind::ConnectionRefused | std::io::ErrorKind::NotFound + ) => + { + std::fs::remove_file(path) + .map_err(|e| format!("remove stale socket: {}", e.kind()))?; + } + Ok(Err(e)) => return Err(format!("probe existing socket: {}", e.kind())), + Err(_) => return Err("probe existing socket: timed out".into()), + } + } + Ok(_) => return Err("path exists and is not a socket".into()), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} + Err(e) => return Err(format!("inspect socket path: {}", e.kind())), + } + let tmp = sibling(path, ".new"); + let _ = std::fs::remove_file(&tmp); + let l = UnixListener::bind(&tmp).map_err(|e| format!("bind socket: {}", e.kind()))?; + let finish = || -> std::io::Result<()> { + std::fs::set_permissions(&tmp, std::fs::Permissions::from_mode(mode))?; + std::fs::rename(&tmp, path) + }; + if let Err(e) = finish() { + let _ = std::fs::remove_file(&tmp); + return Err(format!("install socket: {}", e.kind())); + } + Ok(l) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn dir(tag: &str) -> PathBuf { + let d = PathBuf::from(format!("/tmp/apx-sock-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d + } + + #[tokio::test] + async fn binds_with_the_requested_mode_and_replaces_a_dead_socket() { + let d = dir("a"); + let p = d.join("s.sock"); + let l = bind_unix(&p, 0o660).await.unwrap(); + let mode = std::fs::metadata(&p).unwrap().permissions().mode() & 0o777; + assert_eq!(mode, 0o660); + // Live: refused. + let e = bind_unix(&p, 0o660).await.unwrap_err(); + assert!(e.contains("live"), "{e}"); + // Dead: the file stays behind, the probe gets no answer, it is replaced. + drop(l); + assert!(p.exists()); + let l2 = bind_unix(&p, 0o600).await.unwrap(); + assert_eq!( + std::fs::metadata(&p).unwrap().permissions().mode() & 0o777, + 0o600 + ); + drop(l2); + let _ = std::fs::remove_dir_all(&d); + } + + #[tokio::test] + async fn refuses_a_regular_file() { + let d = dir("b"); + let p = d.join("s.sock"); + std::fs::write(&p, b"keep me").unwrap(); + let e = bind_unix(&p, 0o660).await.unwrap_err(); + assert!(e.contains("not a socket"), "{e}"); + assert_eq!(std::fs::read(&p).unwrap(), b"keep me"); + let _ = std::fs::remove_dir_all(&d); + } +} diff --git a/crates/ap-proxy/tests/hello_race.rs b/crates/ap-proxy/tests/hello_race.rs new file mode 100644 index 0000000..6654007 --- /dev/null +++ b/crates/ap-proxy/tests/hello_race.rs @@ -0,0 +1,254 @@ +//! Owner condition (a): the `hello` race after an authority container restart. +//! +//! In a real pod the authority is the runtime container's PID 1: when it dies, +//! every process in the container (every agent-UID shell, any orphan) dies with +//! it, and the next `hello` can only come from the restarted PID 1, which sends +//! it before any session exists. The proxy's part of that is the 90 s lock: +//! while the dead authority's lease is live, nobody can take it; when it lapses, +//! the sessions of the dead authority are revoked and the first `hello` wins. +//! +//! These tests run the real binary with the authority lease shortened to 3 s +//! (the minimum; the defaults 90/30 s are pinned by a constants test in +//! ap-broker). "Authority dies" is simulated by the client going silent. +//! +//! The real-pod version (kill the runtime container with the proxy up, confirm +//! no orphan survives, fresh PID 1 wins after 90 s) is in the pre-release +//! checklist: it needs a cluster. + +mod support; + +use ap_client::{Backoff, Client, ClientError, Registration, SessionRef, Surrogate}; +use std::time::{Duration, Instant}; +use support::*; + +const LEASE: u64 = 3; + +fn opts() -> Opts { + Opts { + authority_lease_secs: Some(LEASE), + ..Default::default() + } +} + +fn backoff() -> Backoff { + Backoff { + initial: Duration::from_millis(100), + max: Duration::from_millis(200), + deadline: Some(Duration::from_secs(10)), + } +} + +fn sref(session: &str, generation: u64) -> SessionRef { + SessionRef { + session: session.into(), + generation, + } +} + +fn assert_surrogate_gone(fx: &Fixture, s: &Surrogate) { + let before = fx.upstream_count(); + let r = fx.get("up", "/v1/echo", s.expose()); + assert_eq!(r.status, 403, "{}", r.text()); + assert!( + matches!( + r.code(), + Some("surrogate_revoked" | "surrogate_unknown" | "surrogate_expired") + ), + "{:?}", + r.code() + ); + assert_eq!( + fx.upstream_count(), + before, + "a refused request reached the upstream" + ); +} + +/// Two clients race for the lock with retry and backoff. Exactly one wins; the +/// loser keeps getting 409. Returns (winner client, loser client, instant won). +async fn race(a: Client, b: Client) -> (Client, Client, Instant) { + let (ca, cb) = (a.clone(), b.clone()); + let mut ha = tokio::spawn(async move { ca.hello_retry(backoff()).await }); + let mut hb = tokio::spawn(async move { cb.hello_retry(backoff()).await }); + let which = tokio::select! { + r = &mut ha => { r.unwrap().expect("client a won"); 0 } + r = &mut hb => { r.unwrap().expect("client b won"); 1 } + }; + let (winner, loser, mut loser_task) = if which == 0 { (a, b, hb) } else { (b, a, ha) }; + let won_at = Instant::now(); + // The loser is still retrying: it cannot also win. + let still = tokio::time::timeout(Duration::from_millis(800), &mut loser_task).await; + match still { + Err(_) => loser_task.abort(), + Ok(r) => assert!( + r.unwrap().is_err(), + "both clients won the authority lock (two tokens)" + ), + } + assert!(loser.token().is_none(), "the loser must not hold a token"); + (winner, loser, won_at) +} + +#[tokio::test(flavor = "multi_thread")] +async fn hello_race_after_authority_restart() { + let mut fx = Fixture::new(opts()); + fx.start_proxy(); + + // Authority A, the runtime's PID 1: hello, one session, one renew. + let a = fx.client(); + assert_eq!(a.hello().await.unwrap(), LEASE); + let a_token = a.token().unwrap(); + let s1 = register(&a, "sess-1", 1, &["c-up"]).await; + assert_eq!(fx.get("up", "/v1/echo", s1.expose()).status, 200); + a.renew(&[sref("sess-1", 1)]).await.unwrap(); + let last_renew = Instant::now(); + // ... and A dies: from here on it sends nothing. + + // An orphan (agent-UID process that survived; no token) tries to take the + // lock, and to act on the plane: all refused while A's lease is live. + let orphan = fx.client(); + let e = orphan.hello().await.unwrap_err(); + assert!(e.is_authority_active(), "orphan hello: {e}"); + assert_eq!(e.status(), Some(409)); + let reg = Registration::new("evil", 1, &Surrogate::generate().unwrap(), &["c-up"]); + orphan.set_token(Some(format!("apt_{}", "0".repeat(64)))); + assert!(orphan.register(®).await.unwrap_err().is_unauthorized()); + assert!(orphan.renew(&[]).await.unwrap_err().is_unauthorized()); + assert!(orphan + .revoke("sess-1", 1) + .await + .unwrap_err() + .is_unauthorized()); + assert!(orphan.resync(&[]).await.unwrap_err().is_unauthorized()); + orphan.set_token(None); + let raw = orphan + .raw("POST", "/v1/sessions", None, Some(b"{}")) + .await + .unwrap(); + assert_eq!(raw.status, 401, "no token at all"); + // A's own session keeps working until the lease lapses. + assert_eq!(fx.get("up", "/v1/echo", s1.expose()).status, 200); + assert_eq!(fx.upstream_count(), 2); + + // The fresh runtime (PID 1 of the restarted container) and a second + // would-be authority race with retry and backoff. + let fresh = fx.client(); + let rival = fx.client(); + let (winner, loser, won_at) = race(fresh, rival).await; + let waited = won_at.duration_since(last_renew); + assert!( + waited >= Duration::from_millis(2900), + "the lock was taken {waited:?} after the last renew; it must hold for the {LEASE} s lease" + ); + assert!(waited < Duration::from_secs(6), "took {waited:?}"); + + // The lock is taken again: a further hello is refused, A's token is dead. + assert!(loser.hello().await.unwrap_err().is_authority_active()); + assert!(a + .renew(&[sref("sess-1", 1)]) + .await + .unwrap_err() + .is_unauthorized()); + assert!(a.register(®).await.unwrap_err().is_unauthorized()); + assert!(a.revoke("sess-1", 1).await.unwrap_err().is_unauthorized()); + assert_ne!(winner.token().unwrap(), a_token); + + // A's session died with A, with nothing sent upstream. + assert_surrogate_gone(&fx, &s1); + + // The new authority works. + let s2 = register(&winner, "sess-2", 1, &["c-up"]).await; + assert_eq!(fx.get("up", "/v1/echo", s2.expose()).status, 200); +} + +#[tokio::test(flavor = "multi_thread")] +async fn hello_race_with_a_proxy_restart_in_the_middle() { + let mut fx = Fixture::new(opts()); + fx.start_proxy(); + let a = fx.client(); + a.hello().await.unwrap(); + let a_token = a.token().unwrap(); + let reg_surrogate = Surrogate::generate().unwrap(); + let reg = Registration::new("sess-1", 1, ®_surrogate, &["c-up"]); + a.register(®).await.unwrap(); + assert_eq!(fx.get("up", "/v1/echo", reg_surrogate.expose()).status, 200); + + // The proxy is killed and restarted; only the authority token's hash was + // persisted (proxy-private state dir). + fx.kill_proxy(); + fx.start_proxy(); + let state = std::fs::read_to_string(fx.state_dir().join("authority.json")).unwrap(); + assert!(state.contains("token_sha256") && !state.contains(&a_token)); + + // The lock is live for one authority lease from the restart: an orphan's + // hello is refused although the proxy has no sessions at all. + let orphan = fx.client(); + assert!(orphan.hello().await.unwrap_err().is_authority_active()); + // The proxy forgot the sessions: requests in the gap are refused. + assert_eq!( + fx.get("up", "/v1/echo", reg_surrogate.expose()).code(), + Some("surrogate_unknown") + ); + + // A's token is still good: its renew lists the session as unknown, and the + // full-list resync brings the same surrogate back. + let r = a.renew(&[sref("sess-1", 1)]).await.unwrap(); + let last_renew = Instant::now(); + assert_eq!(r.unknown, vec![sref("sess-1", 1)]); + assert_eq!( + a.resync(std::slice::from_ref(®)) + .await + .unwrap() + .registered, + 1 + ); + assert_eq!(fx.get("up", "/v1/echo", reg_surrogate.expose()).status, 200); + + // A dies after the restart. The lock still holds for the lease, then the + // fresh runtime wins and A's session is revoked. + let e = orphan.hello().await.unwrap_err(); + assert!(e.is_authority_active(), "{e}"); + let fresh = fx.client(); + fresh.hello_retry(backoff()).await.unwrap(); + let waited = Instant::now().duration_since(last_renew); + assert!( + waited >= Duration::from_millis(2900), + "lock lapsed after {waited:?}" + ); + assert!(a.renew(&[]).await.unwrap_err().is_unauthorized()); + assert_surrogate_gone(&fx, ®_surrogate); + assert!( + fresh.register(®).await.is_ok(), + "new authority can register" + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn lock_after_a_proxy_restart_lapses_one_lease_after_the_restart() { + let mut fx = Fixture::new(opts()); + fx.start_proxy(); + let a = fx.client(); + a.hello().await.unwrap(); + fx.kill_proxy(); + fx.start_proxy(); + let restarted = Instant::now(); + + // A is silent: the persisted lock holds for one lease from the restart, + // not from the (unknown) last renew. + let orphan = fx.client(); + tokio::time::sleep(Duration::from_millis(400)).await; + assert!(orphan.hello().await.unwrap_err().is_authority_active()); + let fresh = fx.client(); + fresh.hello_retry(backoff()).await.unwrap(); + let waited = Instant::now().duration_since(restarted); + assert!( + waited >= Duration::from_millis(2300) && waited < Duration::from_secs(7), + "lock lapsed {waited:?} after the restart" + ); + // A's old token is dead; the persisted hash was replaced by the new one. + assert!(a.renew(&[]).await.unwrap_err().is_unauthorized()); + assert!(fresh.renew(&[]).await.is_ok()); + let again = fx.client(); + let e: ClientError = again.hello().await.unwrap_err(); + assert!(e.is_authority_active()); +} diff --git a/crates/ap-proxy/tests/no_caller_key_in_logs.rs b/crates/ap-proxy/tests/no_caller_key_in_logs.rs new file mode 100644 index 0000000..b04bddc --- /dev/null +++ b/crates/ap-proxy/tests/no_caller_key_in_logs.rs @@ -0,0 +1,345 @@ +//! Owner condition (b): no audit or access log contains the +//! `/ap/` prefix. +//! +//! The real binary runs with stdout and stderr captured to files. The test +//! drives a success, every one of the 21 refusal codes, a wrong caller key, odd +//! paths, an upstream failure and session-plane errors (including ids that look +//! like keys), then stops the proxy cleanly and searches everything it wrote. +//! +//! Design guards this test backs up: no tracing or access-log layer exists in +//! the process; `ApPath::verify` is the one place the prefix is taken apart and +//! hands on only the route-relative path; pre-verification refusals log path +//! `-`; upstream error text (which embeds the URL) is never printed; the panic +//! hook prints a fixed line. + +mod support; + +use ap_client::Surrogate; +use ap_core::Code; +use std::collections::BTreeSet; +use std::time::Duration; +use support::*; + +fn sref(session: &str) -> ap_client::SessionRef { + ap_client::SessionRef { + session: session.into(), + generation: 1, + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn no_caller_key_prefix_in_any_log() { + let mut fx = Fixture::new(Opts { + session_lease_secs: Some(2), + max_body_bytes: Some(1000), + ..Default::default() + }); + fx.start_proxy(); + let key = fx.caller_key.clone(); + let a = fx.client(); + a.hello().await.unwrap(); + let token = a.token().unwrap(); + + let mut used: Vec = vec![token.clone()]; + let mut codes: BTreeSet = BTreeSet::new(); + let mut note = |r: &Resp, want_status: u16, want_code: &str| { + assert_eq!(r.status, want_status, "{want_code}: {}", r.text()); + assert_eq!(r.code(), Some(want_code), "{}", r.text()); + codes.insert(want_code.to_string()); + }; + let mut reg = |s: Surrogate| { + used.push(s.expose().to_string()); + s + }; + + // The long-lived sessions are renewed in the background (the session lease + // is 2 s); `s-exp`, registered later, is deliberately not. + let renewer = { + let a = a.clone(); + tokio::spawn(async move { + let live = [sref("s-ok"), sref("s-wr"), sref("s-wc"), sref("s-dead")]; + loop { + let _ = a.renew(&live).await; + tokio::time::sleep(Duration::from_millis(400)).await; + } + }) + }; + + // ---- a success, with a query string that must not be logged either + let ok = reg(register(&a, "s-ok", 1, &["c-up"]).await); + let ok_val = format!("Bearer {}", ok.expose()); + let ok_h = [("Authorization", ok_val.as_str())]; + let q = format!("/v1/echo?q=SECRETQUERY&k={key}"); + let r = fx.request("GET", "up", &q, &ok_h, b""); + assert_eq!(r.status, 200, "{}", r.text()); + assert_eq!(fx.upstream_count(), 1); + + // ---- refusals before the caller key is verified (audit path is `-`) + let port = fx.port; + let raw = |req: String| raw_http(port, req.as_bytes()); + let r = raw(format!( + "GET http://evil.example/ap/{key}/up/v1/echo HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nConnection: close\r\n\r\n" + )); + note(&r, 400, "absolute_form"); + let r = raw(format!( + "GET /ap/{key}/up/v1/echo HTTP/1.1\r\nHost: evil.example\r\nConnection: close\r\n\r\n" + )); + note(&r, 400, "host_rejected"); + let r = fx.request("GET", "up", "/v1/../etc/passwd", &ok_h, b""); + note(&r, 400, "path_ambiguous"); + let r = fx.request_with_key( + &format!("apk_{}", "0".repeat(64)), + "GET", + "up", + "/v1/echo", + &ok_h, + b"", + ); + note(&r, 403, "caller_rejected"); + let r = raw( + "CONNECT api.up.test:443 HTTP/1.1\r\nHost: api.up.test:443\r\nConnection: close\r\n\r\n" + .to_string(), + ); + note(&r, 405, "connect_refused"); + let r = fx.request( + "GET", + "up", + "/v1/ws", + &[("Connection", "Upgrade"), ("Upgrade", "websocket")], + b"", + ); + note(&r, 501, "websocket_unsupported"); + // A path that is not /ap///...: the shape itself is wrong. + let r = raw(format!( + "GET /not-ap/{key} HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nConnection: close\r\n\r\n" + )); + assert_eq!(r.status, 404); + assert_eq!(r.code(), Some("route_unknown")); + + // ---- refusals after verification + let r = fx.request("GET", "nope", "/v1/echo", &ok_h, b""); + note(&r, 404, "route_unknown"); + let r = fx.request("GET", "up", "/v1/echo", &[], b""); + note(&r, 403, "surrogate_missing"); + let r = fx.request( + "GET", + "up", + "/v1/echo", + &[("Authorization", "Bearer not-a-surrogate")], + b"", + ); + note(&r, 403, "surrogate_malformed"); + let two = format!("Bearer {}", ok.expose()); + let r = fx.request( + "GET", + "up", + "/v1/echo", + &[("Authorization", &two), ("Authorization", &two)], + b"", + ); + note(&r, 400, "surrogate_ambiguous"); + let unknown = reg(Surrogate::generate().unwrap()); + let r = fx.get("up", "/v1/echo", unknown.expose()); + note(&r, 403, "surrogate_unknown"); + let rev = reg(register(&a, "s-rev", 1, &["c-up"]).await); + a.revoke("s-rev", 1).await.unwrap(); + let r = fx.get("up", "/v1/echo", rev.expose()); + note(&r, 403, "surrogate_revoked"); + let wr = reg(register(&a, "s-wr", 1, &["c-other"]).await); + let r = fx.get("up", "/v1/echo", wr.expose()); + note(&r, 403, "surrogate_wrong_route"); + let wc = reg(register(&a, "s-wc", 1, &["c-up"]).await); + fx.set_policy("someone-else", &default_grants()); + let r = fx.get("up", "/v1/echo", wc.expose()); + note(&r, 403, "surrogate_wrong_caller"); + fx.set_policy("agent-1", &default_grants()); + fx.set_policy("agent-1", ""); + let r = fx.get("up", "/v1/echo", ok.expose()); + note(&r, 403, "policy_empty"); + fx.set_policy("agent-1", &grant("c-up", "up", &["POST"], &["/v2/"], &[])); + let r = fx.get("up", "/v1/echo", ok.expose()); + note(&r, 403, "policy_denied"); + fx.set_policy_raw("version = 1\n[[route\n"); + let r = fx.get("up", "/v1/echo", ok.expose()); + note(&r, 503, "policy_unavailable"); + fx.set_policy("agent-1", &default_grants()); + fx.remove_secret("c-up"); + let r = fx.get("up", "/v1/echo", ok.expose()); + note(&r, 503, "broker_unavailable"); + fx.write_secret("c-up", &fx.secret_value("c-up")); + let r = fx.request("POST", "up", "/v1/echo", &ok_h, &[b'x'; 2000]); + note(&r, 413, "body_too_large"); + let dead = reg(register(&a, "s-dead", 1, &["c-up"]).await); + let r = fx.get("dead", "/v1/echo", dead.expose()); + note(&r, 502, "upstream_unavailable"); + let exp = reg(register(&a, "s-exp", 1, &["c-up"]).await); + tokio::time::sleep(Duration::from_millis(2600)).await; + let r = fx.get("up", "/v1/echo", exp.expose()); + note(&r, 403, "surrogate_expired"); + + // ---- session-plane errors, with ids that look like keys + let c = fx.client(); + let r = c + .raw("POST", "/v1/sessions", None, Some(b"{}")) + .await + .unwrap(); + assert_eq!(r.status, 401); + c.set_token(Some(format!("apt_{}", "0".repeat(64)))); + assert_eq!( + c.raw( + "POST", + "/v1/renew", + c.token().as_deref(), + Some(br#"{"sessions":[]}"#) + ) + .await + .unwrap() + .status, + 401 + ); + let e = c.hello().await.unwrap_err(); + assert!(e.is_authority_active()); + let good_hash = "ab".repeat(32); + let body_key_session = format!( + r#"{{"session":"{key}","generation":1,"surrogate_sha256":"{good_hash}","credentials":["c-up"]}}"# + ); + let r = a + .raw( + "POST", + "/v1/sessions", + Some(&token), + Some(body_key_session.as_bytes()), + ) + .await + .unwrap(); + assert_eq!( + r.status, 201, + "a session named like the key is allowed, and masked in the log" + ); + let bad_hash = format!( + r#"{{"session":"{key}","generation":2,"surrogate_sha256":"{key}","credentials":["c-up"]}}"# + ); + let r = a + .raw( + "POST", + "/v1/sessions", + Some(&token), + Some(bad_hash.as_bytes()), + ) + .await + .unwrap(); + assert_eq!(r.status, 400); + let not_granted = format!( + r#"{{"session":"s-ng","generation":1,"surrogate_sha256":"{good_hash}","credentials":["{key}"]}}"# + ); + let r = a + .raw( + "POST", + "/v1/sessions", + Some(&token), + Some(not_granted.as_bytes()), + ) + .await + .unwrap(); + assert_eq!(r.status, 403); + let renew = format!(r#"{{"sessions":[{{"session":"{key}","generation":1}}]}}"#); + let r = a + .raw("POST", "/v1/renew", Some(&token), Some(renew.as_bytes())) + .await + .unwrap(); + assert_eq!(r.status, 200); + let r = a + .raw( + "DELETE", + &format!("/v1/sessions/{key}/1"), + Some(&token), + None, + ) + .await + .unwrap(); + assert_eq!(r.status, 204); + let r = a + .raw( + "POST", + "/v1/sessions", + Some(&token), + Some(&vec![b'x'; 1024 * 1024 + 1]), + ) + .await + .unwrap(); + assert_eq!(r.status, 413); + let r = a + .raw("GET", "/v1/resolve", Some(&token), None) + .await + .unwrap(); + assert_eq!(r.status, 404); + let r = a + .raw("POST", "/v1/sessions", Some(&token), Some(b"not json")) + .await + .unwrap(); + assert_eq!(r.status, 400); + + renewer.abort(); + + // ---- every refusal code has been exercised + let want: BTreeSet = Code::ALL.iter().map(|c| c.as_str().to_string()).collect(); + let missing: Vec<_> = want.difference(&codes).collect(); + assert!(missing.is_empty(), "codes not exercised: {missing:?}"); + + // ---- stop cleanly, then search everything the proxy wrote + assert_eq!(fx.stop_proxy(), Some(0), "SIGTERM is a clean stop"); + let (out, err) = fx.read_logs(); + assert!( + out.lines().count() > 40, + "audit log looks empty: {} lines", + out.lines().count() + ); + assert!(err.contains("ready"), "stderr: {err}"); + let mut forbidden: Vec = vec![ + key.clone(), + "apk_".into(), + "aps_".into(), + "apt_".into(), + "/ap/".into(), + "SECRETQUERY".into(), + fx.secret_value("c-up"), + fx.secret_value("c-other"), + ]; + forbidden.extend(used.iter().cloned()); + for (name, text) in [("stdout", &out), ("stderr", &err)] { + for f in &forbidden { + assert!(!text.contains(f.as_str()), "{name} contains {f:?}"); + } + } + + // Audit lines: pre-verification refusals have no path; the rest have only + // the route-relative one. + let lines = fx.audit_lines(); + assert!(lines.iter().filter(|l| l["decision"] == "deny").count() >= 21); + let pre = [ + "absolute_form", + "host_rejected", + "path_ambiguous", + "caller_rejected", + "connect_refused", + "websocket_unsupported", + "policy_unavailable", + ]; + for l in &lines { + let path = l["path"].as_str().unwrap(); + assert!( + path == "-" || (path.starts_with('/') && !path.contains("/ap/") && !path.contains('?')), + "{l}" + ); + if pre.contains(&l["code"].as_str().unwrap()) { + assert_eq!(path, "-", "{l}"); + } + } + let ok_line = lines + .iter() + .find(|l| l["decision"] == "allow") + .expect("an allow line"); + assert_eq!(ok_line["path"], "/v1/echo"); + assert_eq!(ok_line["identity"], "agent-1"); + assert_eq!(ok_line["session"], "s-ok"); +} diff --git a/crates/ap-proxy/tests/policy.rs b/crates/ap-proxy/tests/policy.rs new file mode 100644 index 0000000..9cdb3b0 --- /dev/null +++ b/crates/ap-proxy/tests/policy.rs @@ -0,0 +1,422 @@ +//! Q3-A behavior: the policy file is validated as a whole at startup (exit 2) +//! and at every reload (503 `policy_unavailable`), swaps are atomic, a bad file +//! never leaves a half-applied or stale policy, and `aws_targets` is enforced. + +mod support; + +use ap_client::ClientError; +use std::collections::HashMap; +use std::process::{Command, Stdio}; +use std::time::{Duration, Instant}; +use support::*; + +type Breakage = Box; +type State<'a> = (&'a str, Vec<(&'a str, String)>, &'a str); + +fn run_proxy(fx: &Fixture) -> std::process::Output { + fx.proxy_command().output().unwrap() +} + +#[test] +fn a_policy_that_fails_validation_stops_the_proxy_with_exit_code_2() { + let fx = Fixture::new(Opts::default()); + let good = fx.policy_toml("agent-1", &default_grants()); + let other_port = free_port(); + let bad: Vec<(&str, String)> = vec![ + ("version 2", good.replace("version = 1", "version = 2")), + ( + "unknown key", + good.replace("version = 1", "version = 1\nbogus = true"), + ), + ( + "IP literal route host", + good.replacen("api.up.test", "127.0.0.1", 1), + ), + ( + "uppercase route host", + good.replacen("api.up.test", "API.up.test", 1), + ), + ( + "userinfo route host", + good.replacen("api.up.test", "u@api.up.test", 1), + ), + ( + "grant names an unknown credential", + fx.policy_toml("agent-1", &grant("nope", "up", &["GET"], &["/"], &[])), + ), + ( + "grant path without a trailing slash", + fx.policy_toml("agent-1", &grant("c-up", "up", &["GET"], &["/v1"], &[])), + ), + ( + "aws: source (deferred)", + good.replace("k8s:c-up:api_key", "aws:secretsmanager:x"), + ), + ( + "env: source (not resolved in Phase 1)", + good.replace("k8s:c-up:api_key", "env:FOO"), + ), + ( + "bad caller hash", + good.replace("caller_key_sha256 = \"", "caller_key_sha256 = \"zz"), + ), + ("empty file", String::new()), + ("not TOML", "[[route".into()), + ( + "listener differs from --listen", + format!("{good}\n[listener]\nlisten = \"127.0.0.1:{other_port}\"\n"), + ), + ( + "non-loopback policy listener", + format!("{good}\n[listener]\nlisten = \"0.0.0.0:{other_port}\"\n"), + ), + ]; + for (label, content) in bad { + fx.set_policy_raw(&content); + let out = run_proxy(&fx); + let err = String::from_utf8_lossy(&out.stderr); + assert_eq!(out.status.code(), Some(2), "{label}: stderr: {err}"); + assert!(err.starts_with("auth-proxy: "), "{label}: {err}"); + assert!( + !err.contains("panicked") && !err.contains("RUST_BACKTRACE"), + "{label}: {err}" + ); + assert!( + !fx.session_sock().exists(), + "{label}: a socket was bound before the policy passed" + ); + } + // A missing file too. + std::fs::remove_file(fx.policy_path()).unwrap(); + assert_eq!(run_proxy(&fx).status.code(), Some(2)); + // And the good file starts. + fx.set_policy_raw(&good); + let mut fx = fx; + fx.start_proxy(); +} + +#[test] +fn the_listener_can_be_configured_in_the_policy() { + let fx = Fixture::new(Opts::default()); + let toml = format!( + "{}\n[listener]\nlisten = \"127.0.0.1:{}\"\n", + fx.policy_toml("agent-1", &default_grants()), + fx.port + ); + fx.set_policy_raw(&toml); + let mut cmd = Command::new(env!("CARGO_BIN_EXE_auth-proxy")); + cmd.args(["--policy", &fx.policy_path().to_string_lossy()]) + .args(["--secrets-dir", &fx.secrets_dir().to_string_lossy()]) + .args(["--session-socket", &fx.session_sock().to_string_lossy()]) + .args(["--admin-socket", &fx.admin_sock().to_string_lossy()]) + .args(["--state-dir", &fx.state_dir().to_string_lossy()]) + .stdout(Stdio::null()) + .stderr(Stdio::null()); + let mut child = cmd.spawn().unwrap(); + let end = Instant::now() + Duration::from_secs(10); + while std::net::TcpStream::connect(("127.0.0.1", fx.port)).is_err() { + assert!(Instant::now() < end, "proxy did not start"); + std::thread::sleep(Duration::from_millis(30)); + } + // Both default authorities are accepted, others are not. + let ask = |host: String| { + raw_http( + fx.port, + format!( + "GET /ap/apk_{}/up/v1/echo HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n\r\n", + "0".repeat(64) + ) + .as_bytes(), + ) + }; + assert_eq!( + ask(format!("127.0.0.1:{}", fx.port)).code(), + Some("caller_rejected") + ); + assert_eq!( + ask(format!("localhost:{}", fx.port)).code(), + Some("caller_rejected") + ); + assert_eq!(ask("evil.example".into()).code(), Some("host_rejected")); + let _ = child.kill(); + let _ = child.wait(); +} + +#[tokio::test(flavor = "multi_thread")] +async fn unreadable_policy_refuses_everything_and_recovers_when_restored() { + let mut fx = Fixture::new(Opts::default()); + fx.start_proxy(); + let a = fx.client(); + a.hello().await.unwrap(); + let s = register(&a, "s1", 1, &["c-up"]).await; + let good = fx.policy_toml("agent-1", &default_grants()); + let ask = |fx: &Fixture| fx.get("up", "/v1/echo", s.expose()); + + let r = ask(&fx); + assert_eq!(r.status, 200, "{}", r.text()); + let mut forwarded = 1; + assert_eq!(fx.upstream_count(), forwarded); + + let breakages: Vec<(&str, Breakage)> = vec![ + ("0 bytes", Box::new(|fx: &Fixture| fx.set_policy_raw(""))), + ( + "corrupt", + Box::new(|fx: &Fixture| fx.set_policy_raw("version = 1\n[[route\nname")), + ), + ( + "valid TOML, whole-file validation fails", + Box::new(|fx: &Fixture| { + fx.set_policy("agent-1", &grant("c-up", "nowhere", &["GET"], &["/"], &[])) + }), + ), + ( + "deleted", + Box::new(|fx: &Fixture| std::fs::remove_file(fx.policy_path()).unwrap()), + ), + ]; + for (label, breakage) in breakages { + breakage(&fx); + let r = ask(&fx); + assert_eq!( + (r.status, r.code()), + (503, Some("policy_unavailable")), + "{label}: {}", + r.text() + ); + // The last good snapshot is not kept: every route, including ones that + // did not change, is refused. + assert_eq!( + fx.get("upaws", "/v1/echo", s.expose()).code(), + Some("policy_unavailable"), + "{label}" + ); + // Session registration needs the policy too. + let e = a + .register(&ap_client::Registration::new( + "x", + 1, + &ap_client::Surrogate::generate().unwrap(), + &["c-up"], + )) + .await + .unwrap_err(); + assert!( + matches!(e, ClientError::Api { status: 503, .. }), + "{label}: {e}" + ); + assert_eq!( + fx.upstream_count(), + forwarded, + "{label}: a refused request reached the upstream" + ); + // Restore: back to normal at once, no restart. + fx.set_policy_raw(&good); + let r = ask(&fx); + assert_eq!(r.status, 200, "{label}: {}", r.text()); + forwarded += 1; + assert_eq!(fx.upstream_count(), forwarded); + } + let (_, err) = fx.read_logs(); + assert!( + err.contains("policy unavailable"), + "the operator is told on stderr: {err}" + ); +} + +#[test] +fn a_policy_swap_is_atomic_under_concurrent_requests() { + let mut fx = Fixture::new(Opts::default()); + fx.start_proxy(); + // Policy A names identity ident-a (the session is registered under it), + // policy B names ident-b and has no /v1/ grant. A request judged against a + // half-applied swap would show ident-a with a deny, or ident-b with an allow. + let pa = fx.policy_toml("ident-a", &default_grants()); + let pb = fx.policy_toml("ident-b", &grant("c-up", "up", &["POST"], &["/v9/"], &[])); + fx.set_policy_raw(&pa); + let rt = tokio::runtime::Runtime::new().unwrap(); + let s = rt.block_on(async { + let a = fx.client(); + a.hello().await.unwrap(); + register(&a, "s1", 1, &["c-up"]).await + }); + let reg_ok = fx.get("up", "/v1/echo", s.expose()); + assert_eq!(reg_ok.status, 200, "{}", reg_ok.text()); + fx.reset_upstream(); + + let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + let swapper = { + let (dir, path, stop) = (fx.dir.clone(), fx.policy_path(), stop.clone()); + std::thread::spawn(move || { + let tmp = dir.join("swap.tmp"); + let mut flip = false; + while !stop.load(std::sync::atomic::Ordering::Relaxed) { + std::fs::write(&tmp, if flip { &pb } else { &pa }).unwrap(); + std::fs::rename(&tmp, &path).unwrap(); + flip = !flip; + std::thread::sleep(Duration::from_millis(4)); + } + }) + }; + let req = format!( + "GET /ap/{}/up/v1/echo HTTP/1.1\r\nHost: 127.0.0.1:{}\r\nAuthorization: Bearer {}\r\nConnection: close\r\n\r\n", + fx.caller_key, + fx.port, + s.expose() + ); + let port = fx.port; + let workers: Vec<_> = (0..4) + .map(|_| { + let req = req.clone(); + std::thread::spawn(move || { + let mut seen: Vec<(u16, Option)> = Vec::new(); + let end = Instant::now() + Duration::from_millis(2500); + while Instant::now() < end { + let r = raw_http(port, req.as_bytes()); + seen.push((r.status, r.code().map(String::from))); + } + seen + }) + }) + .collect(); + let mut tally: HashMap<(u16, Option), usize> = HashMap::new(); + for w in workers { + for k in w.join().unwrap() { + *tally.entry(k).or_default() += 1; + } + } + stop.store(true, std::sync::atomic::Ordering::Relaxed); + swapper.join().unwrap(); + + let allowed = tally.get(&(200, None)).copied().unwrap_or(0); + let denied = tally + .get(&(403, Some("surrogate_wrong_caller".into()))) + .copied() + .unwrap_or(0); + assert_eq!( + allowed + denied, + tally.values().sum::(), + "unexpected outcomes during swaps: {tally:?}" + ); + assert!( + allowed > 10 && denied > 10, + "both policies must have been seen: {tally:?}" + ); + assert_eq!( + fx.upstream_count(), + allowed, + "only allowed requests reach the upstream" + ); + for l in fx.audit_lines() { + let pair = (l["identity"].as_str().unwrap(), l["code"].as_str().unwrap()); + if l["session"] == "s1" || l["identity"] != "-" { + assert!( + pair == ("ident-a", "ok") || pair == ("ident-b", "surrogate_wrong_caller"), + "half-applied policy: {l}" + ); + } + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn aws_targets_deny_zero_and_two_headers_and_every_refusal_is_aws_shaped() { + let mut fx = Fixture::new(Opts::default()); + fx.start_proxy(); + let a = fx.client(); + a.hello().await.unwrap(); + let s = register(&a, "s1", 1, &["c-up"]).await; + fx.set_policy( + "agent-1", + &[ + grant("c-up", "upaws", &["POST"], &["/v1/"], &["Svc.Allowed"]), + grant("c-up", "up", &["POST"], &["/v1/"], &[]), + ] + .join("\n"), + ); + let auth = format!("Bearer {}", s.expose()); + let post = |route: &str, targets: &[&str]| { + let mut h: Vec<(&str, &str)> = vec![("Authorization", auth.as_str())]; + for t in targets { + h.push(("X-Amz-Target", *t)); + } + fx.request("POST", route, "/v1/echo", &h, b"{}") + }; + + let r = post("upaws", &["Svc.Allowed"]); + assert_eq!(r.status, 200, "{}", r.text()); + let log = fx.upstream_log(); + assert_eq!(log.len(), 1); + let targets: Vec<_> = log[0]["headers"] + .as_array() + .unwrap() + .iter() + .filter(|h| h[0] == "x-amz-target") + .collect(); + assert_eq!( + targets.len(), + 1, + "the one allowed target is forwarded as is" + ); + + for (label, t) in [ + ("none", vec![]), + ("two equal", vec!["Svc.Allowed", "Svc.Allowed"]), + ("two different", vec!["Svc.Allowed", "Svc.Other"]), + ("wrong", vec!["Svc.Other"]), + ("wrong case", vec!["svc.allowed"]), + ("comma list", vec!["Svc.Allowed, Svc.Other"]), + ] { + let r = post("upaws", &t); + assert_eq!( + (r.status, r.code()), + (403, Some("policy_denied")), + "{label}" + ); + let j = r.json(); + assert_eq!(j["__type"], "AccessDeniedException", "{label}: {j}"); + assert_eq!( + r.header("x-amzn-errortype"), + Some("AccessDeniedException"), + "{label}" + ); + } + // The route without aws_targets takes any number of them. + assert_eq!(post("up", &["X.A", "X.B"]).status, 200); + assert_eq!( + fx.upstream_count(), + 2, + "denied requests reached the upstream" + ); + + // Every surrogate state is a 403 with the AWS-shaped body on an aws route, + // and the JSON dialect elsewhere. + a.revoke("s1", 1).await.unwrap(); + let unknown = ap_client::Surrogate::generate().unwrap(); + let states: Vec = vec![ + ( + "revoked", + vec![("Authorization", auth.clone())], + "surrogate_revoked", + ), + ( + "unknown", + vec![("Authorization", format!("Bearer {}", unknown.expose()))], + "surrogate_unknown", + ), + ( + "malformed", + vec![("Authorization", "Bearer nope".into())], + "surrogate_malformed", + ), + ("missing", vec![], "surrogate_missing"), + ]; + for (label, headers, code) in states { + let h: Vec<(&str, &str)> = headers.iter().map(|(k, v)| (*k, v.as_str())).collect(); + let r = fx.request("POST", "upaws", "/v1/echo", &h, b"{}"); + assert_eq!((r.status, r.code()), (403, Some(code)), "{label}"); + assert_eq!(r.json()["__type"], "AccessDeniedException", "{label}"); + let r = fx.request("POST", "up", "/v1/echo", &h, b"{}"); + assert_eq!((r.status, r.code()), (403, Some(code)), "{label} (json)"); + assert_eq!(r.json()["error"]["type"], code, "{label} (json)"); + } + assert_eq!(fx.upstream_count(), 2); +} diff --git a/crates/ap-proxy/tests/session_plane.rs b/crates/ap-proxy/tests/session_plane.rs new file mode 100644 index 0000000..edf6ebe --- /dev/null +++ b/crates/ap-proxy/tests/session_plane.rs @@ -0,0 +1,566 @@ +//! Q1-B behavior of the session plane, against the real binary: leases, +//! synchronous revocation, resync after a proxy restart, the statuses of the +//! design doc's table, the socket modes, and what the process listens on. + +mod support; + +use ap_client::{ + Authority, AuthorityConfig, Backoff, Client, ClientError, Registration, RenewOutcome, + SessionRef, Surrogate, +}; +use std::os::unix::fs::PermissionsExt; +use std::sync::Arc; +use std::time::{Duration, Instant}; +use support::*; + +fn sref(session: &str, generation: u64) -> SessionRef { + SessionRef { + session: session.into(), + generation, + } +} + +fn reg(session: &str, generation: u64, s: &Surrogate) -> Registration { + Registration::new(session, generation, s, &["c-up"]) +} + +fn api_status(e: ClientError) -> (u16, String) { + match e { + ClientError::Api { status, code, .. } => (status, code), + other => panic!("expected an API error, got {other}"), + } +} + +async fn status_json(fx: &Fixture) -> serde_json::Value { + let r = fx + .admin() + .raw("GET", "/admin/status", None, None) + .await + .unwrap(); + assert_eq!(r.status, 200); + serde_json::from_slice(&r.body).unwrap() +} + +async fn post(a: &Client, body: &str) -> (u16, serde_json::Value) { + let tok = a.token(); + let r = a + .raw( + "POST", + "/v1/sessions", + tok.as_deref(), + Some(body.as_bytes()), + ) + .await + .unwrap(); + ( + r.status, + serde_json::from_slice(&r.body).unwrap_or_default(), + ) +} + +#[tokio::test(flavor = "multi_thread")] +async fn revocation_is_synchronous_and_idempotent() { + let mut fx = Fixture::new(Opts::default()); + fx.start_proxy(); + let a = fx.client(); + assert_eq!(a.hello().await.unwrap(), 90); + let s = register(&a, "s1", 1, &["c-up"]).await; + let r = fx.get("up", "/v1/echo", s.expose()); + assert_eq!(r.status, 200, "{}", r.text()); + assert_eq!(fx.upstream_count(), 1); + + a.revoke("s1", 1).await.unwrap(); + let r = fx.get("up", "/v1/echo", s.expose()); + assert_eq!((r.status, r.code()), (403, Some("surrogate_revoked"))); + assert_eq!( + fx.upstream_count(), + 1, + "nothing reached the upstream after revoke" + ); + // 204 also when the session is unknown, and on a repeat. + a.revoke("s1", 1).await.unwrap(); + a.revoke("never-registered", 7).await.unwrap(); + + // The same session and generation can be registered again with a new surrogate. + let s2 = register(&a, "s1", 1, &["c-up"]).await; + assert_eq!(fx.get("up", "/v1/echo", s2.expose()).status, 200); + assert_eq!( + fx.get("up", "/v1/echo", s.expose()).code(), + Some("surrogate_revoked") + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn renewal_is_capped_at_the_absolute_ttl() { + let mut fx = Fixture::new(Opts { + absolute_ttl_secs: Some(3), + session_lease_secs: Some(2), + ..Default::default() + }); + fx.start_proxy(); + let a = fx.client(); + a.hello().await.unwrap(); + let t0 = Instant::now(); + let s = register(&a, "s1", 1, &["c-up"]).await; + + // Renewing keeps it alive past the 2 s lease... + while t0.elapsed() < Duration::from_millis(2500) { + let r = a.renew(&[sref("s1", 1)]).await.unwrap(); + assert!(r.unknown.is_empty()); + assert_eq!(r.lease_secs, 2); + tokio::time::sleep(Duration::from_millis(400)).await; + } + assert_eq!(fx.get("up", "/v1/echo", s.expose()).status, 200); + + // ... but never past the 3 s absolute TTL. + tokio::time::sleep(Duration::from_millis(3300).saturating_sub(t0.elapsed())).await; + let r = a.renew(&[sref("s1", 1)]).await.unwrap(); + assert_eq!( + r.unknown, + vec![sref("s1", 1)], + "renew must not revive a session past its TTL" + ); + let r = fx.get("up", "/v1/echo", s.expose()); + assert_eq!((r.status, r.code()), (403, Some("surrogate_expired"))); +} + +#[tokio::test(flavor = "multi_thread")] +async fn proxy_restart_then_resync_keeps_the_same_surrogate_and_dropped_stay_dropped() { + let mut fx = Fixture::new(Opts::default()); + fx.start_proxy(); + let cfg = AuthorityConfig { + renew_every: Duration::from_millis(200), + backoff: Backoff { + initial: Duration::from_millis(100), + max: Duration::from_millis(200), + deadline: Some(Duration::from_secs(10)), + }, + }; + let auth = Authority::connect(fx.session_sock(), cfg).await.unwrap(); + let keep = auth.register("keep", 1, &["c-up"]).await.unwrap(); + let dropped = auth.register("dropped", 1, &["c-up"]).await.unwrap(); + auth.revoke("dropped", 1).await.unwrap(); + assert_eq!(fx.get("up", "/v1/echo", keep.expose()).status, 200); + assert_eq!(fx.get("up", "/v1/echo", dropped.expose()).status, 403); + assert_eq!(auth.live_sessions(), vec![sref("keep", 1)]); + + // A crashed proxy leaves its socket files behind; the new one replaces them. + fx.kill_proxy(); + fx.start_proxy(); + let before = fx.upstream_count(); + // In the gap every surrogate is unknown, the CLI's included. + let r = fx.get("up", "/v1/echo", keep.expose()); + assert_eq!((r.status, r.code()), (403, Some("surrogate_unknown"))); + + // The authority's next renew sees the session listed as unknown and resends the full list. + assert_eq!(auth.renew_once().await.unwrap(), RenewOutcome::Resynced); + let r = fx.get("up", "/v1/echo", keep.expose()); + assert_eq!(r.status, 200, "{}", r.text()); + assert_eq!(fx.upstream_count(), before + 1); + // The revoked session was not in the list, so it stays dropped. + let r = fx.get("up", "/v1/echo", dropped.expose()); + assert_eq!((r.status, r.code()), (403, Some("surrogate_unknown"))); + assert_eq!(status_json(&fx).await["sessions"], 1); + + // With the renew loop running, a second restart heals itself within a few intervals. + let auth = Arc::new(auth); + let task = tokio::spawn(auth.clone().run_renew_loop()); + fx.kill_proxy(); + fx.start_proxy(); + let end = Instant::now() + Duration::from_secs(8); + loop { + if fx.get("up", "/v1/echo", keep.expose()).status == 200 { + break; + } + assert!( + Instant::now() < end, + "the renew loop did not resync after a restart" + ); + tokio::time::sleep(Duration::from_millis(100)).await; + } + task.abort(); + assert_eq!(fx.get("up", "/v1/echo", dropped.expose()).status, 403); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_lapsed_authority_that_comes_back_wins_hello_again_and_resyncs() { + let mut fx = Fixture::new(Opts { + authority_lease_secs: Some(3), + ..Default::default() + }); + fx.start_proxy(); + let cfg = AuthorityConfig { + renew_every: Duration::from_secs(30), + backoff: Backoff { + initial: Duration::from_millis(100), + max: Duration::from_millis(200), + deadline: Some(Duration::from_secs(10)), + }, + }; + let auth = Authority::connect(fx.session_sock(), cfg).await.unwrap(); + let s = auth.register("s1", 1, &["c-up"]).await.unwrap(); + // The authority was stalled past its lease (nobody else took the lock). + tokio::time::sleep(Duration::from_millis(3400)).await; + assert_eq!(fx.get("up", "/v1/echo", s.expose()).status, 403); + assert_eq!(auth.renew_once().await.unwrap(), RenewOutcome::Reacquired); + assert_eq!(fx.get("up", "/v1/echo", s.expose()).status, 200); +} + +#[tokio::test(flavor = "multi_thread")] +async fn max_sessions_is_429_and_a_repeat_registration_is_idempotent() { + let mut fx = Fixture::new(Opts { + max_sessions: Some(2), + ..Default::default() + }); + fx.start_proxy(); + let a = fx.client(); + a.hello().await.unwrap(); + let (s1, s2, s3) = ( + Surrogate::generate().unwrap(), + Surrogate::generate().unwrap(), + Surrogate::generate().unwrap(), + ); + a.register(®("a", 1, &s1)).await.unwrap(); + a.register(®("b", 1, &s2)).await.unwrap(); + let e = a.register(®("c", 1, &s3)).await.unwrap_err(); + assert_eq!(api_status(e), (429, "too_many_sessions".into())); + // The same registration again is a renewal, not a new session. + a.register(®("a", 1, &s1)).await.unwrap(); + assert_eq!(status_json(&fx).await["sessions"], 2); + // A slot frees up on revoke. + a.revoke("a", 1).await.unwrap(); + a.register(®("c", 1, &s3)).await.unwrap(); +} + +#[tokio::test(flavor = "multi_thread")] +async fn same_session_with_another_hash_is_409() { + let mut fx = Fixture::new(Opts::default()); + fx.start_proxy(); + let a = fx.client(); + a.hello().await.unwrap(); + let (s1, s2) = ( + Surrogate::generate().unwrap(), + Surrogate::generate().unwrap(), + ); + a.register(®("s", 1, &s1)).await.unwrap(); + a.register(®("s", 1, &s1)).await.unwrap(); + let e = a.register(®("s", 1, &s2)).await.unwrap_err(); + assert_eq!(api_status(e), (409, "session_conflict".into())); + // Another generation is another session. + a.register(®("s", 2, &s2)).await.unwrap(); + // A hash cannot be bound twice. + let e = a.register(®("t", 1, &s1)).await.unwrap_err(); + assert_eq!(api_status(e).0, 409); + // The refused registrations changed nothing: s1 still works, s2 is the generation-2 one. + assert_eq!(fx.get("up", "/v1/echo", s1.expose()).status, 200); + assert_eq!(fx.get("up", "/v1/echo", s2.expose()).status, 200); + assert_eq!(status_json(&fx).await["sessions"], 2); +} + +#[tokio::test(flavor = "multi_thread")] +async fn invalid_registrations_are_400_and_change_nothing() { + let mut fx = Fixture::new(Opts::default()); + fx.start_proxy(); + let a = fx.client(); + a.hello().await.unwrap(); + let h = "ab".repeat(32); + let body = |session: &str, gen: &str, hash: &str, creds: &str| { + format!( + r#"{{"session":"{session}","generation":{gen},"surrogate_sha256":"{hash}","credentials":{creds}}}"# + ) + }; + let too_many: Vec = (0..17).map(|i| format!("\"c{i}\"")).collect(); + let cases: Vec<(&str, String, u16)> = vec![ + ( + "space in session", + body("bad session", "1", &h, r#"["c-up"]"#), + 400, + ), + ("empty session", body("", "1", &h, r#"["c-up"]"#), 400), + ( + "129-char session", + body(&"s".repeat(129), "1", &h, r#"["c-up"]"#), + 400, + ), + ("slash in session", body("a/b", "1", &h, r#"["c-up"]"#), 400), + ( + "negative generation", + body("s", "-1", &h, r#"["c-up"]"#), + 400, + ), + ( + "fractional generation", + body("s", "1.5", &h, r#"["c-up"]"#), + 400, + ), + ( + "uppercase hash", + body("s", "1", &h.to_uppercase(), r#"["c-up"]"#), + 400, + ), + ("63-char hash", body("s", "1", &h[..63], r#"["c-up"]"#), 400), + ("no credentials", body("s", "1", &h, "[]"), 400), + ( + "17 credentials", + body("s", "1", &h, &format!("[{}]", too_many.join(","))), + 400, + ), + ( + "duplicate credential", + body("s", "1", &h, r#"["c-up","c-up"]"#), + 400, + ), + ( + "unknown field", + format!( + r#"{{"session":"s","generation":1,"surrogate_sha256":"{h}","credentials":["c-up"],"x":1}}"# + ), + 400, + ), + ( + "missing field", + r#"{"session":"s","generation":1,"credentials":["c-up"]}"#.to_string(), + 400, + ), + ("not JSON", "not json".into(), 400), + ( + "credential not defined", + body("s", "1", &h, r#"["nope"]"#), + 403, + ), + ]; + for (label, b, want) in cases { + let (st, j) = post(&a, &b).await; + assert_eq!(st, want, "{label}: {j}"); + assert!(j["error"].is_string(), "{label}: {j}"); + } + assert_eq!( + status_json(&fx).await["sessions"], + 0, + "a refused registration registered something" + ); + + // A resync list is validated whole: one bad entry applies nothing, and the + // answer names the entry. + let s_keep = Surrogate::generate().unwrap(); + a.register(®("keep", 1, &s_keep)).await.unwrap(); + let good_new = reg("new", 1, &Surrogate::generate().unwrap()); + let bad = Registration { + credentials: vec!["nope".into()], + ..reg("bad", 1, &Surrogate::generate().unwrap()) + }; + let keep_reg = reg("keep", 1, &s_keep); + let e = a.resync(&[good_new.clone(), bad]).await.unwrap_err(); + let ClientError::Api { + status, message, .. + } = &e + else { + panic!("{e}") + }; + assert_eq!(*status, 403); + assert!(message.contains("entry 1"), "{message}"); + assert_eq!( + status_json(&fx).await["sessions"], + 1, + "a partly bad resync applied something" + ); + assert_eq!(fx.get("up", "/v1/echo", s_keep.expose()).status, 200); + // Duplicate entries are rejected too. + let e = a + .resync(&[keep_reg.clone(), keep_reg.clone()]) + .await + .unwrap_err(); + assert_eq!(e.status(), Some(400), "{e}"); + // A good list replaces the registry: `keep` stays, `new` is added. + let ok = a.resync(&[keep_reg, good_new]).await.unwrap(); + assert_eq!((ok.registered, ok.dropped), (2, 0)); + // And an empty list drops everything. + let ok = a.resync(&[]).await.unwrap(); + assert_eq!((ok.registered, ok.dropped), (0, 2)); + assert_eq!(fx.get("up", "/v1/echo", s_keep.expose()).status, 403); +} + +#[tokio::test(flavor = "multi_thread")] +async fn bodies_over_1_mib_are_413_and_register_nothing() { + let mut fx = Fixture::new(Opts::default()); + fx.start_proxy(); + let a = fx.client(); + a.hello().await.unwrap(); + let tok = a.token(); + let big = vec![b' '; 1024 * 1024 + 1]; + for (m, p) in [ + ("POST", "/v1/sessions"), + ("PUT", "/v1/sessions"), + ("POST", "/v1/renew"), + ] { + let r = a.raw(m, p, tok.as_deref(), Some(&big)).await.unwrap(); + assert_eq!(r.status, 413, "{m} {p}"); + } + assert_eq!(status_json(&fx).await["sessions"], 0); + // The authority is still usable on a new connection. + register(&a, "s", 1, &["c-up"]).await; +} + +#[tokio::test(flavor = "multi_thread")] +async fn admin_socket_status_and_revoke_all() { + let mut fx = Fixture::new(Opts::default()); + fx.start_proxy(); + let a = fx.client(); + a.hello().await.unwrap(); + let s1 = register(&a, "s1", 1, &["c-up"]).await; + let s2 = register(&a, "s2", 1, &["c-up"]).await; + let j = status_json(&fx).await; + assert_eq!(j["sessions"], 2); + assert_eq!(j["authority_live"], true); + assert_eq!(j["policy"], "ok"); + assert_eq!(j["identity"], "agent-1"); + + let r = fx + .admin() + .raw("POST", "/admin/revoke-all", None, None) + .await + .unwrap(); + assert_eq!(r.status, 200); + assert_eq!( + serde_json::from_slice::(&r.body).unwrap()["revoked"], + 2 + ); + for s in [&s1, &s2] { + assert_eq!( + fx.get("up", "/v1/echo", s.expose()).code(), + Some("surrogate_revoked") + ); + } + assert_eq!(status_json(&fx).await["sessions"], 0); + // No admin call returns a credential or a token. + let text = String::from_utf8_lossy( + &fx.admin() + .raw("GET", "/admin/status", None, None) + .await + .unwrap() + .body, + ) + .into_owned(); + assert!(!text.contains("apt_") && !text.contains(&fx.secret_value("c-up"))); + assert_eq!( + fx.admin() + .raw("GET", "/admin/revoke-all", None, None) + .await + .unwrap() + .status, + 405 + ); + assert_eq!( + fx.admin() + .raw("GET", "/admin/credentials", None, None) + .await + .unwrap() + .status, + 404 + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn the_session_socket_has_exactly_the_five_calls_and_nothing_else() { + let mut fx = Fixture::new(Opts::default()); + fx.start_proxy(); + let a = fx.client(); + a.hello().await.unwrap(); + let tok = a.token(); + let t = tok.as_deref(); + // F1: there is no resolve endpoint, and the admin calls are not on this socket. + for (m, p, want) in [ + ("POST", "/v1/resolve", 404), + ("GET", "/v1/resolve", 404), + ("GET", "/admin/status", 404), + ("POST", "/admin/revoke-all", 404), + ("GET", "/v1/sessions", 405), + ("DELETE", "/v1/sessions", 405), + ("GET", "/v1/hello", 405), + ("DELETE", "/v1/sessions/a/not-a-number", 400), + ("DELETE", "/v1/sessions/a", 404), + ("GET", "/", 404), + ] { + let r = a.raw(m, p, t, None).await.unwrap(); + assert_eq!(r.status, want, "{m} {p}"); + } + // And the admin socket does not serve the session plane. + let r = fx + .admin() + .raw("POST", "/v1/hello", None, Some(b"{}")) + .await + .unwrap(); + assert_eq!(r.status, 404); +} + +#[tokio::test(flavor = "multi_thread")] +async fn socket_modes_and_a_second_proxy_on_a_live_socket() { + let mut fx = Fixture::new(Opts::default()); + fx.start_proxy(); + let mode = |p: std::path::PathBuf| std::fs::metadata(p).unwrap().permissions().mode() & 0o777; + assert_eq!(mode(fx.session_sock()), 0o660); + assert_eq!(mode(fx.admin_sock()), 0o600); + + // A second proxy over the same sockets: exit code 2, and the first is untouched. + let out = fx.proxy_command().output().unwrap(); + assert_eq!(out.status.code(), Some(2)); + let err = String::from_utf8_lossy(&out.stderr); + assert!(err.contains("live"), "{err}"); + assert!(fx.proxy_alive()); + fx.client().hello().await.unwrap(); +} + +/// "Proxy binds no TCP port other than the one loopback listener." +#[tokio::test(flavor = "multi_thread")] +async fn exactly_one_tcp_listener_on_loopback() { + let mut fx = Fixture::new(Opts::default()); + fx.start_proxy(); + let a = fx.client(); + a.hello().await.unwrap(); + register(&a, "s", 1, &["c-up"]).await; + let pid = fx.proxy_pid().to_string(); + let out = std::process::Command::new("lsof") + .args(["-nP", "-a", "-p", &pid, "-iTCP", "-sTCP:LISTEN", "-Fn"]) + .output(); + let Ok(out) = out else { + eprintln!("lsof is not installed: listener check skipped"); + return; + }; + let names: Vec = String::from_utf8_lossy(&out.stdout) + .lines() + .filter_map(|l| l.strip_prefix('n')) + .map(String::from) + .collect(); + assert_eq!( + names, + vec![format!("127.0.0.1:{}", fx.port)], + "TCP listeners of the proxy" + ); +} + +#[test] +fn startup_refuses_a_non_loopback_listener() { + let fx = Fixture::new(Opts::default()); + for listen in [ + "0.0.0.0:18999", + "192.168.1.5:18999", + "[::]:18999", + "127.0.0.1:0", + ] { + let mut cmd = std::process::Command::new(env!("CARGO_BIN_EXE_auth-proxy")); + cmd.args(["--policy", &fx.policy_path().to_string_lossy()]) + .args(["--secrets-dir", &fx.secrets_dir().to_string_lossy()]) + .args(["--listen", listen]) + .args(["--session-socket", &fx.session_sock().to_string_lossy()]) + .args(["--admin-socket", &fx.admin_sock().to_string_lossy()]) + .args(["--state-dir", &fx.state_dir().to_string_lossy()]); + let out = cmd.output().unwrap(); + assert_eq!(out.status.code(), Some(2), "{listen}"); + let err = String::from_utf8_lossy(&out.stderr); + assert!(err.contains("loopback"), "{listen}: {err}"); + assert!( + !fx.session_sock().exists(), + "no socket may be bound before the listener check" + ); + } +} diff --git a/crates/ap-proxy/tests/support/mod.rs b/crates/ap-proxy/tests/support/mod.rs new file mode 100644 index 0000000..32adec2 --- /dev/null +++ b/crates/ap-proxy/tests/support/mod.rs @@ -0,0 +1,678 @@ +//! Fixtures for the integration tests: the real `auth-proxy` binary, a mock TLS +//! upstream (tests/matrix/upstream.py, the same one the matrix uses), a policy +//! file, Secret files, and blocking HTTP helpers. +//! +//! Unix socket paths stay short (macOS limit: 104 bytes). +#![allow(dead_code)] + +use ap_client::Client; +use std::collections::HashSet; +use std::io::{Read, Write}; +use std::net::{TcpListener, TcpStream}; +use std::path::{Path, PathBuf}; +use std::process::{Child, Command, Stdio}; +use std::sync::atomic::{AtomicU32, Ordering}; +use std::sync::{Mutex, OnceLock}; +use std::time::{Duration, Instant}; + +// ---------------------------------------------------------------- ports, certs + +pub fn free_port() -> u16 { + static USED: OnceLock>> = OnceLock::new(); + let used = USED.get_or_init(|| Mutex::new(HashSet::new())); + loop { + let p = TcpListener::bind("127.0.0.1:0") + .unwrap() + .local_addr() + .unwrap() + .port(); + if used.lock().unwrap().insert(p) { + return p; + } + } +} + +fn sh(cmd: &str, args: &[&str]) { + let st = Command::new(cmd) + .args(args) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status() + .unwrap_or_else(|e| panic!("cannot run {cmd}: {e}")); + assert!(st.success(), "{cmd} {args:?} failed"); +} + +/// A throwaway CA and one server certificate for `api.up.test`, made once per +/// test binary. `ecparam` writes a named-curve key; `req -newkey ec` on +/// LibreSSL (macOS) writes explicit parameters that no TLS stack accepts. +pub fn pki() -> &'static Path { + static P: OnceLock = OnceLock::new(); + P.get_or_init(|| { + let d = PathBuf::from(format!("/tmp/apx-pki-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + let p = |f: &str| d.join(f).to_string_lossy().into_owned(); + sh( + "openssl", + &[ + "ecparam", + "-name", + "prime256v1", + "-genkey", + "-noout", + "-out", + &p("ca.key"), + ], + ); + sh( + "openssl", + &[ + "req", + "-x509", + "-new", + "-key", + &p("ca.key"), + "-out", + &p("ca.pem"), + "-days", + "2", + "-sha256", + "-subj", + "/CN=ap-test-ca", + ], + ); + sh( + "openssl", + &[ + "ecparam", + "-name", + "prime256v1", + "-genkey", + "-noout", + "-out", + &p("api.key"), + ], + ); + sh( + "openssl", + &[ + "req", + "-new", + "-key", + &p("api.key"), + "-out", + &p("api.csr"), + "-subj", + "/CN=api.up.test", + ], + ); + std::fs::write( + d.join("api.ext"), + "subjectAltName=DNS:api.up.test\nextendedKeyUsage=serverAuth\n", + ) + .unwrap(); + sh( + "openssl", + &[ + "x509", + "-req", + "-in", + &p("api.csr"), + "-CA", + &p("ca.pem"), + "-CAkey", + &p("ca.key"), + "-CAcreateserial", + "-out", + &p("api.pem"), + "-days", + "2", + "-sha256", + "-extfile", + &p("api.ext"), + ], + ); + d + }) +} + +// ---------------------------------------------------------------- HTTP (blocking) + +#[derive(Debug, Clone)] +pub struct Resp { + pub status: u16, + pub headers: Vec<(String, String)>, + pub body: Vec, +} + +impl Resp { + pub fn header(&self, name: &str) -> Option<&str> { + self.headers + .iter() + .find(|(k, _)| k.eq_ignore_ascii_case(name)) + .map(|(_, v)| v.as_str()) + } + + /// The proxy's refusal code. + pub fn code(&self) -> Option<&str> { + self.header("x-auth-proxy-error") + } + + pub fn text(&self) -> String { + String::from_utf8_lossy(&self.body).into_owned() + } + + pub fn json(&self) -> serde_json::Value { + serde_json::from_slice(&self.body).unwrap_or(serde_json::Value::Null) + } +} + +fn parse_resp(raw: &[u8]) -> Resp { + let split = raw + .windows(4) + .position(|w| w == b"\r\n\r\n") + .unwrap_or_else(|| panic!("no response head in {:?}", String::from_utf8_lossy(raw))); + let head = String::from_utf8_lossy(&raw[..split]).into_owned(); + let mut lines = head.split("\r\n"); + let status: u16 = lines + .next() + .unwrap() + .split(' ') + .nth(1) + .and_then(|s| s.parse().ok()) + .unwrap_or_else(|| panic!("bad status line in {head:?}")); + let headers = lines + .filter_map(|l| l.split_once(':')) + .map(|(k, v)| (k.trim().to_string(), v.trim().to_string())) + .collect(); + let mut body = raw[split + 4..].to_vec(); + let chunked = head + .to_ascii_lowercase() + .contains("transfer-encoding: chunked"); + if chunked { + let mut out = Vec::new(); + let mut rest = &body[..]; + while let Some(eol) = rest.windows(2).position(|w| w == b"\r\n") { + let n = usize::from_str_radix( + std::str::from_utf8(&rest[..eol]) + .unwrap() + .split(';') + .next() + .unwrap() + .trim(), + 16, + ) + .unwrap_or(0); + if n == 0 || rest.len() < eol + 2 + n { + break; + } + out.extend_from_slice(&rest[eol + 2..eol + 2 + n]); + rest = &rest[(eol + 2 + n + 2).min(rest.len())..]; + } + body = out; + } + Resp { + status, + headers, + body, + } +} + +/// Send `req` and read to EOF (requests carry `Connection: close`). A write +/// error (the proxy refused early and closed) does not stop the read. +pub fn raw_http(port: u16, req: &[u8]) -> Resp { + let mut s = TcpStream::connect(("127.0.0.1", port)).unwrap(); + s.set_read_timeout(Some(Duration::from_secs(15))).unwrap(); + let _ = s.write_all(req); + let mut out = Vec::new(); + let mut buf = [0u8; 16384]; + loop { + match s.read(&mut buf) { + Ok(0) => break, + Ok(n) => out.extend_from_slice(&buf[..n]), + Err(e) if !out.is_empty() && e.kind() == std::io::ErrorKind::ConnectionReset => break, + Err(e) => panic!("read response: {e}"), + } + } + parse_resp(&out) +} + +// ---------------------------------------------------------------- the fixture + +#[derive(Clone, Default)] +pub struct Opts { + pub authority_lease_secs: Option, + pub session_lease_secs: Option, + pub absolute_ttl_secs: Option, + pub max_sessions: Option, + pub max_body_bytes: Option, +} + +pub fn grant(cred: &str, route: &str, methods: &[&str], paths: &[&str], aws: &[&str]) -> String { + let q = |v: &[&str]| serde_json::to_string(v).unwrap(); + let mut s = format!( + "[[grant]]\ncredential = \"{cred}\"\nroute = \"{route}\"\nmethods = {}\npaths = {}\n", + q(methods), + q(paths) + ); + if !aws.is_empty() { + s.push_str(&format!("aws_targets = {}\n", q(aws))); + } + s +} + +/// Grants on every route of the default policy. +pub fn default_grants() -> String { + [ + grant("c-up", "up", &["GET", "POST"], &["/v1/"], &[]), + grant("c-up", "upaws", &["GET", "POST"], &["/v1/"], &[]), + grant("c-up", "dead", &["GET", "POST"], &["/v1/"], &[]), + grant("c-other", "other", &["GET", "POST"], &["/v1/"], &[]), + ] + .join("\n") +} + +static COUNTER: AtomicU32 = AtomicU32::new(0); + +pub struct Fixture { + pub dir: PathBuf, + /// The agent listener. + pub port: u16, + pub up_port: u16, + pub up_ctl: u16, + pub dead_port: u16, + pub caller_key: String, + pub creds: Vec<(String, String)>, + pub opts: Opts, + upstream: Option, + proxy: Option, +} + +impl Fixture { + /// A fixture with the mock upstream running and the policy and Secrets + /// written. The proxy is not started. + pub fn new(opts: Opts) -> Fixture { + let n = COUNTER.fetch_add(1, Ordering::SeqCst); + let dir = PathBuf::from(format!("/tmp/apx-{}-{n}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let key = ap_client::Surrogate::generate().unwrap().into_string(); + let caller_key = format!("apk_{}", &key[4..]); + let nanos = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos(); + let creds = vec![ + ("c-up".to_string(), format!("real-up-{nanos:x}-{n}")), + ("c-other".to_string(), format!("real-other-{nanos:x}-{n}")), + ]; + let mut f = Fixture { + dir, + port: free_port(), + up_port: free_port(), + up_ctl: free_port(), + dead_port: free_port(), + caller_key, + creds, + opts, + upstream: None, + proxy: None, + }; + for (id, v) in f.creds.clone() { + f.write_secret(&id, &v); + } + f.set_policy("agent-1", &default_grants()); + f.start_upstream(); + f + } + + // ---- paths + pub fn policy_path(&self) -> PathBuf { + self.dir.join("policy.toml") + } + pub fn secrets_dir(&self) -> PathBuf { + self.dir.join("secrets") + } + pub fn state_dir(&self) -> PathBuf { + self.dir.join("state") + } + pub fn session_sock(&self) -> PathBuf { + self.dir.join("s").join("s.sock") + } + pub fn admin_sock(&self) -> PathBuf { + self.dir.join("a").join("a.sock") + } + pub fn stdout_log(&self) -> PathBuf { + self.dir.join("stdout.log") + } + pub fn stderr_log(&self) -> PathBuf { + self.dir.join("stderr.log") + } + + // ---- policy and secrets + pub fn policy_toml(&self, identity: &str, grants: &str) -> String { + use sha2::{Digest, Sha256}; + let hash = hex::encode(Sha256::digest(self.caller_key.as_bytes())); + let up = self.up_port; + let dead = self.dead_port; + format!( + r#"version = 1 +identity = "{identity}" +caller_key_sha256 = "{hash}" + +[[route]] +name = "up" +host = "api.up.test" +port = {up} +connect_to = "127.0.0.1:{up}" +pass_headers = ["tokentype"] + +[[route]] +name = "upaws" +host = "api.up.test" +port = {up} +connect_to = "127.0.0.1:{up}" +error_shape = "aws" + +[[route]] +name = "other" +host = "api.up.test" +port = {up} +connect_to = "127.0.0.1:{up}" + +[[route]] +name = "dead" +host = "dead.up.test" +port = {dead} +connect_to = "127.0.0.1:{dead}" + +[[credential]] +id = "c-up" +source = "k8s:c-up:api_key" +routes = ["up", "upaws", "dead"] + +[[credential]] +id = "c-other" +source = "k8s:c-other:api_key" +routes = ["other"] + +{grants} +"# + ) + } + + /// Replace the policy file in one rename, as kubelet does. + pub fn set_policy(&self, identity: &str, grants: &str) { + self.set_policy_raw(&self.policy_toml(identity, grants)); + } + + pub fn set_policy_raw(&self, content: &str) { + let tmp = self.dir.join("policy.toml.tmp"); + std::fs::write(&tmp, content).unwrap(); + std::fs::rename(&tmp, self.policy_path()).unwrap(); + } + + pub fn write_secret(&self, id: &str, value: &str) { + let d = self.secrets_dir().join(id); + std::fs::create_dir_all(&d).unwrap(); + std::fs::write(d.join("api_key"), value).unwrap(); + } + + pub fn remove_secret(&self, id: &str) { + std::fs::remove_file(self.secrets_dir().join(id).join("api_key")).unwrap(); + } + + pub fn secret_value(&self, id: &str) -> String { + self.creds.iter().find(|(i, _)| i == id).unwrap().1.clone() + } + + // ---- processes + fn start_upstream(&mut self) { + let script = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/matrix/upstream.py"); + let pki = pki(); + let listen = format!( + "good={}:{}:{}", + self.up_port, + pki.join("api.pem").display(), + pki.join("api.key").display() + ); + let child = Command::new("python3") + .arg(&script) + .args(["--control", &self.up_ctl.to_string(), "--listen", &listen]) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn() + .expect("python3 is needed for the mock upstream"); + self.upstream = Some(child); + wait_port(self.up_ctl, "mock upstream"); + wait_port(self.up_port, "mock upstream listener"); + } + + pub fn proxy_command(&self) -> Command { + let mut c = Command::new(env!("CARGO_BIN_EXE_auth-proxy")); + c.args(["--policy", &self.policy_path().to_string_lossy()]) + .args(["--secrets-dir", &self.secrets_dir().to_string_lossy()]) + .args(["--listen", &format!("127.0.0.1:{}", self.port)]) + .args(["--session-socket", &self.session_sock().to_string_lossy()]) + .args(["--admin-socket", &self.admin_sock().to_string_lossy()]) + .args(["--state-dir", &self.state_dir().to_string_lossy()]) + .args(["--ca-file", &pki().join("ca.pem").to_string_lossy()]); + let o = &self.opts; + for (flag, v) in [ + ("--authority-lease-secs", o.authority_lease_secs), + ("--session-lease-secs", o.session_lease_secs), + ("--absolute-ttl-secs", o.absolute_ttl_secs), + ("--max-sessions", o.max_sessions), + ("--max-body-bytes", o.max_body_bytes), + ] { + if let Some(v) = v { + c.args([flag, &v.to_string()]); + } + } + c.env_clear().env("PATH", "/usr/bin:/bin"); + c + } + + fn log_file(&self, p: PathBuf) -> Stdio { + Stdio::from( + std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(p) + .unwrap(), + ) + } + + /// Start the proxy with stdout and stderr captured to files (appended, so a + /// restart keeps the history), and wait until it answers. + pub fn start_proxy(&mut self) { + assert!(self.proxy.is_none(), "proxy already running"); + let mut cmd = self.proxy_command(); + cmd.stdout(self.log_file(self.stdout_log())) + .stderr(self.log_file(self.stderr_log())); + let mut child = cmd.spawn().expect("spawn auth-proxy"); + let end = Instant::now() + Duration::from_secs(15); + loop { + if let Some(st) = child.try_wait().unwrap() { + panic!( + "auth-proxy exited early ({st}); stderr:\n{}", + std::fs::read_to_string(self.stderr_log()).unwrap_or_default() + ); + } + if TcpStream::connect(("127.0.0.1", self.port)).is_ok() + && self.session_sock().exists() + && self.admin_sock().exists() + { + break; + } + assert!(Instant::now() < end, "auth-proxy did not start in 15 s"); + std::thread::sleep(Duration::from_millis(20)); + } + self.proxy = Some(child); + } + + pub fn proxy_pid(&self) -> u32 { + self.proxy.as_ref().expect("proxy running").id() + } + + /// SIGKILL: the socket files stay behind, like after a crash. + pub fn kill_proxy(&mut self) { + if let Some(mut c) = self.proxy.take() { + let _ = c.kill(); + let _ = c.wait(); + } + } + + /// SIGTERM, then wait: returns the exit code. + pub fn stop_proxy(&mut self) -> Option { + let mut c = self.proxy.take()?; + let _ = Command::new("kill") + .args(["-TERM", &c.id().to_string()]) + .status(); + c.wait().ok().and_then(|s| s.code()) + } + + pub fn proxy_alive(&mut self) -> bool { + self.proxy + .as_mut() + .is_some_and(|c| c.try_wait().unwrap().is_none()) + } + + // ---- session plane and admin + pub fn client(&self) -> Client { + Client::new(self.session_sock()) + } + + pub fn admin(&self) -> Client { + Client::new(self.admin_sock()) + } + + // ---- agent requests + pub fn request( + &self, + method: &str, + route: &str, + rest: &str, + headers: &[(&str, &str)], + body: &[u8], + ) -> Resp { + self.request_with_key(&self.caller_key, method, route, rest, headers, body) + } + + pub fn request_with_key( + &self, + key: &str, + method: &str, + route: &str, + rest: &str, + headers: &[(&str, &str)], + body: &[u8], + ) -> Resp { + let mut req = format!( + "{method} /ap/{key}/{route}{rest} HTTP/1.1\r\nHost: 127.0.0.1:{}\r\nConnection: close\r\n", + self.port + ); + for (k, v) in headers { + req.push_str(&format!("{k}: {v}\r\n")); + } + if !body.is_empty() || method == "POST" { + req.push_str(&format!("Content-Length: {}\r\n", body.len())); + } + req.push_str("\r\n"); + let mut bytes = req.into_bytes(); + bytes.extend_from_slice(body); + raw_http(self.port, &bytes) + } + + /// `GET /ap//` with the surrogate as a Bearer token. + pub fn get(&self, route: &str, rest: &str, surrogate: &str) -> Resp { + self.request( + "GET", + route, + rest, + &[("Authorization", &format!("Bearer {surrogate}"))], + b"", + ) + } + + // ---- mock upstream + fn control(&self, method: &str) -> Vec { + let mut s = TcpStream::connect(("127.0.0.1", self.up_ctl)).unwrap(); + s.set_read_timeout(Some(Duration::from_secs(10))).unwrap(); + write!( + s, + "{method} / HTTP/1.1\r\nHost: x\r\nConnection: close\r\nContent-Length: 0\r\n\r\n" + ) + .unwrap(); + let mut out = Vec::new(); + let _ = s.read_to_end(&mut out); + out + } + + /// Requests the mock upstream has received. + pub fn upstream_log(&self) -> Vec { + let r = parse_resp(&self.control("GET")); + r.json()["log"].as_array().cloned().unwrap_or_default() + } + + pub fn upstream_count(&self) -> usize { + self.upstream_log().len() + } + + pub fn reset_upstream(&self) { + self.control("POST"); + } + + // ---- logs + pub fn read_logs(&self) -> (String, String) { + ( + std::fs::read_to_string(self.stdout_log()).unwrap_or_default(), + std::fs::read_to_string(self.stderr_log()).unwrap_or_default(), + ) + } + + /// Request audit lines (those with a `decision`). + pub fn audit_lines(&self) -> Vec { + self.read_logs() + .0 + .lines() + .filter_map(|l| serde_json::from_str::(l).ok()) + .filter(|v| v.get("decision").is_some()) + .collect() + } +} + +impl Drop for Fixture { + fn drop(&mut self) { + self.kill_proxy(); + if let Some(mut u) = self.upstream.take() { + let _ = u.kill(); + let _ = u.wait(); + } + let _ = std::fs::remove_dir_all(&self.dir); + } +} + +fn wait_port(port: u16, what: &str) { + let end = Instant::now() + Duration::from_secs(15); + while Instant::now() < end { + if TcpStream::connect(("127.0.0.1", port)).is_ok() { + return; + } + std::thread::sleep(Duration::from_millis(30)); + } + panic!("{what} did not come up on {port}"); +} + +/// Register a session through a fresh surrogate, returning it. +pub async fn register( + client: &Client, + session: &str, + generation: u64, + creds: &[&str], +) -> ap_client::Surrogate { + let s = ap_client::Surrogate::generate().unwrap(); + let reg = ap_client::Registration::new(session, generation, &s, creds); + client.register(®).await.expect("register"); + s +} diff --git a/tests/matrix/harness.py b/tests/matrix/harness.py new file mode 100644 index 0000000..3123080 --- /dev/null +++ b/tests/matrix/harness.py @@ -0,0 +1,382 @@ +"""Shared setup for the fail-closed matrix (ported from spike/exp2/test/harness.py). + +Brings up, on loopback only: a throwaway CA pair, mock TLS upstreams +(upstream.py) and the real `auth-proxy` binary. The mock broker of the spike is +gone: sessions are registered through the real session plane, over the Unix +socket, by an authority this harness plays (hello, register, renew, revoke, +resync). All credentials are random per run; nothing real is involved. + +Work files live under a short /tmp path because a Unix socket path is limited +to 104 bytes on macOS. +""" +import hashlib +import http.client +import json +import os +import secrets +import shutil +import socket +import ssl +import subprocess +import tempfile +import threading +import time +import urllib.request + +P = dict(listen=18100, ctl=18199, good=18443, evil=18444, badca=18445, wrongname=18446) +AUTHORITY = f"127.0.0.1:{P['listen']}" +MAX_BODY = 2 * 1024 * 1024 +SESSION_LEASE_SECS = 2 + + +def sh(*cmd, **kw): + subprocess.run(cmd, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, **kw) + + +def wait_port(port, timeout=15.0, proc=None): + end = time.time() + timeout + while time.time() < end: + if proc is not None and proc.poll() is not None: + return False + try: + socket.create_connection(("127.0.0.1", port), 0.2).close() + return True + except OSError: + time.sleep(0.05) + return False + + +class UnixHTTPConnection(http.client.HTTPConnection): + def __init__(self, path, timeout=10): + super().__init__("localhost", timeout=timeout) + self._path = path + + def connect(self): + self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + self.sock.settimeout(self.timeout) + self.sock.connect(self._path) + + +def sha256_hex(s): + return hashlib.sha256(s.encode()).hexdigest() + + +class Env: + def __init__(self, work, bindir): + self.work, self.bindir = work, bindir + os.makedirs(work, exist_ok=True) + self.procs = {} + self.caller_key = "apk_" + secrets.token_hex(32) + self.creds = {"c-up": "real-" + secrets.token_hex(24), "c-key": "real-" + secrets.token_hex(24)} + self.minted = [] # surrogates, for the secret scan + self.sessions = {} # surrogate -> registration dict (what the authority would resync) + self.token = None # authority token, never written to disk + self.policy_file = os.path.join(work, "policy.toml") + self.audit_file = os.path.join(work, "audit.jsonl") + self.err_file = os.path.join(work, "proxy.err") + self.secrets_dir = os.path.join(work, "secrets") + self.state_dir = os.path.join(work, "state") + self.session_sock = os.path.join(work, "sess", "s.sock") + self.admin_sock = os.path.join(work, "adm", "a.sock") + self._stop_renew = threading.Event() + self._renewer = None + self._certs() + for cid, v in self.creds.items(): + self.write_secret(cid, v) + + # ------------------------------------------------------------ certs + def _certs(self): + d = os.path.join(self.work, "pki") + os.makedirs(d, exist_ok=True) + self.pki = d + # ecparam writes a named-curve key. `req -newkey ec` on LibreSSL (the macOS system openssl) + # writes explicit curve parameters, which no TLS stack accepts. + for ca in ("ca", "evilca"): + sh("openssl", "ecparam", "-name", "prime256v1", "-genkey", "-noout", "-out", f"{d}/{ca}.key") + sh("openssl", "req", "-x509", "-new", "-key", f"{d}/{ca}.key", "-out", f"{d}/{ca}.pem", + "-days", "2", "-sha256", "-subj", f"/CN=ap-test-{ca}") + for name, ca in (("api.up.test", "ca"), ("evil.up.test", "ca"), ("badca.up.test", "evilca"), + ("other.up.test", "ca")): + sh("openssl", "ecparam", "-name", "prime256v1", "-genkey", "-noout", "-out", f"{d}/{name}.key") + sh("openssl", "req", "-new", "-key", f"{d}/{name}.key", "-out", f"{d}/{name}.csr", "-subj", + f"/CN={name}") + ext = f"{d}/{name}.ext" + with open(ext, "w") as f: + f.write(f"subjectAltName=DNS:{name}\nextendedKeyUsage=serverAuth\n") + sh("openssl", "x509", "-req", "-in", f"{d}/{name}.csr", "-CA", f"{d}/{ca}.pem", "-CAkey", f"{d}/{ca}.key", + "-CAcreateserial", "-out", f"{d}/{name}.pem", "-days", "2", "-sha256", "-extfile", ext) + + # ------------------------------------------------------------ policy (Q3-A TOML) + def routes(self): + lo = "127.0.0.1" + return [ + {"name": "up", "host": "api.up.test", "port": P["good"], "connect_to": f"{lo}:{P['good']}"}, + {"name": "upaws", "host": "api.up.test", "port": P["good"], "connect_to": f"{lo}:{P['good']}", + "error_shape": "aws"}, + {"name": "upkey", "host": "api.up.test", "port": P["good"], "connect_to": f"{lo}:{P['good']}", + "surrogate_header": "x-api-key", "surrogate_scheme": "", + "credential_header": "x-api-key", "credential_scheme": ""}, + {"name": "badca", "host": "badca.up.test", "port": P["badca"], "connect_to": f"{lo}:{P['badca']}"}, + {"name": "wrongname", "host": "wrongname.up.test", "port": P["wrongname"], + "connect_to": f"{lo}:{P['wrongname']}"}, + ] + + # credential id -> routes it may be applied to + CREDENTIALS = {"c-up": ["up", "upaws", "badca", "wrongname"], "c-key": ["upkey"]} + + def default_grants(self): + return [{"credential": c, "route": r, "methods": ["GET", "POST"], "paths": ["/v1/"]} + for c, rs in self.CREDENTIALS.items() for r in rs] + + @staticmethod + def _q(v): + return json.dumps(v) # a TOML basic string / array of strings has JSON syntax + + def policy_toml(self, identity="agent-1", grants=None, routes=None, credentials=True): + lines = ["version = 1", f"identity = {self._q(identity)}", + f"caller_key_sha256 = {self._q(sha256_hex(self.caller_key))}", ""] + for r in (routes if routes is not None else self.routes()): + lines.append("[[route]]") + for k, v in r.items(): + lines.append(f"{k} = {self._q(v)}") + lines.append("") + if credentials: + for cid, rs in self.CREDENTIALS.items(): + lines += ["[[credential]]", f"id = {self._q(cid)}", f"source = {self._q(f'k8s:{cid}:api_key')}", + f"routes = {self._q(rs)}", ""] + for g in (grants if grants is not None else self.default_grants()): + lines.append("[[grant]]") + for k, v in g.items(): + lines.append(f"{k} = {self._q(v)}") + lines.append("") + return "\n".join(lines) + + def set_policy(self, raw=None, delete=False, **kw): + if delete: + if os.path.exists(self.policy_file): + os.remove(self.policy_file) + return + data = raw if raw is not None else self.policy_toml(**kw) + tmp = self.policy_file + ".tmp" + with open(tmp, "w") as f: + f.write(data) + os.replace(tmp, self.policy_file) # new inode, like kubelet's symlink swap + time.sleep(0.02) + + def write_secret(self, cid, value=None): + d = os.path.join(self.secrets_dir, cid) + os.makedirs(d, exist_ok=True) + with open(os.path.join(d, "api_key"), "w") as f: + f.write(value if value is not None else self.creds[cid]) + + def remove_secret(self, cid): + os.remove(os.path.join(self.secrets_dir, cid, "api_key")) + + # ------------------------------------------------------------ processes + def _spawn(self, name, cmd, env=None, port=None, stdout=None, stderr=None): + out = stdout or open(os.path.join(self.work, f"{name}.log"), "ab") + p = subprocess.Popen(cmd, stdout=out, stderr=stderr or out, env=env) + self.procs[name] = p + if port and not wait_port(port, proc=p): + raise RuntimeError(f"{name} did not start; see {name}.log") + return p + + def stop(self, name, kill=False): + p = self.procs.pop(name, None) + if p: + p.kill() if kill else p.terminate() + try: + p.wait(5) + except subprocess.TimeoutExpired: + p.kill() + + def start_upstream(self): + here = os.path.dirname(os.path.abspath(__file__)) + L = [] + for nm, host in (("good", "api.up.test"), ("evil", "evil.up.test"), ("badca", "badca.up.test"), + ("wrongname", "other.up.test")): + L += ["--listen", f"{nm}={P[nm]}:{self.pki}/{host}.pem:{self.pki}/{host}.key"] + self._spawn("upstream", ["python3", f"{here}/upstream.py", "--control", str(P["ctl"])] + L, port=P["ctl"]) + + def proxy_cmd(self, policy=None): + return [f"{self.bindir}/auth-proxy", "--policy", policy or self.policy_file, + "--secrets-dir", self.secrets_dir, "--listen", AUTHORITY, + "--session-socket", self.session_sock, "--admin-socket", self.admin_sock, + "--state-dir", self.state_dir, "--ca-file", f"{self.pki}/ca.pem", + "--max-body-bytes", str(MAX_BODY), "--session-lease-secs", str(SESSION_LEASE_SECS)] + + def clean_env(self): + return {"PATH": os.environ.get("PATH", "/usr/bin:/bin"), "HOME": self.work} + + def start_impl(self): + """Audit lines (stdout) and operator messages (stderr) go to files the X5 scan reads.""" + out = open(self.audit_file, "ab") + err = open(self.err_file, "ab") + self._spawn("auth-proxy", self.proxy_cmd(), env=self.clean_env(), port=P["listen"], stdout=out, stderr=err) + end = time.time() + 5 + while time.time() < end and not (os.path.exists(self.session_sock) and os.path.exists(self.admin_sock)): + time.sleep(0.02) + + def run_startup_check(self, policy_path): + """Run the proxy against another policy file and return its exit code (it must not start).""" + r = subprocess.run(self.proxy_cmd(policy_path), capture_output=True, timeout=15, env=self.clean_env()) + return r.returncode, r.stdout + r.stderr + + def close(self): + self._stop_renew.set() + for n in list(self.procs): + self.stop(n) + + # ------------------------------------------------------------ session plane (the authority's side) + def plane(self, method, path, obj=None, token="auto", raw=None): + c = UnixHTTPConnection(self.session_sock) + hs = {} + tok = self.token if token == "auto" else token + if tok: + hs["Authorization"] = f"Bearer {tok}" + body = raw if raw is not None else (json.dumps(obj).encode() if obj is not None else None) + if body is not None: + hs["Content-Type"] = "application/json" + try: + c.request(method, path, body=body, headers=hs) + except (BrokenPipeError, ConnectionResetError): + pass # an early refusal (413) may close before the body is sent; the answer is still readable + r = c.getresponse() + data = r.read() + c.close() + try: + j = json.loads(data) if data else None + except ValueError: + j = None + return r.status, j + + def hello(self): + st, j = self.plane("POST", "/v1/hello", {}, token=None) + assert st == 201, f"hello failed: {st} {j}" + self.token = j["authority_token"] + self._renewer = threading.Thread(target=self._renew_loop, daemon=True) + self._renewer.start() + + def _renew_loop(self): + """Keeps the authority's own lease alive (an empty session list), like a live runtime. + Sessions are deliberately not renewed here, so their 2 s lease can lapse in R3.""" + while not self._stop_renew.wait(1.0): + try: + self.plane("POST", "/v1/renew", {"sessions": []}) + except OSError: + pass + + def mint(self, cred="c-up", session=None, generation=1): + """Generate a surrogate and register its hash, as the runtime does at session spawn.""" + s = "aps_" + secrets.token_hex(32) + sid = session or f"m{len(self.minted)}" + reg = {"session": sid, "generation": generation, "surrogate_sha256": sha256_hex(s), "credentials": [cred]} + st, j = self.plane("POST", "/v1/sessions", reg) + assert st == 201, f"register failed: {st} {j}" + self.minted.append(s) + self.sessions[s] = reg + return s + + def revoke(self, s): + reg = self.sessions[s] + st, _ = self.plane("DELETE", f"/v1/sessions/{reg['session']}/{reg['generation']}") + assert st == 204, f"revoke failed: {st}" + + # ------------------------------------------------------------ upstream control + def ulog(self): + with urllib.request.urlopen(f"http://127.0.0.1:{P['ctl']}/", timeout=5) as r: + return json.loads(r.read()) + + def ureset(self): + urllib.request.urlopen(urllib.request.Request(f"http://127.0.0.1:{P['ctl']}/", data=b"", method="POST"), + timeout=5).read() + + # ------------------------------------------------------------ client side + def url(self, route, rest, key=None): + return f"/ap/{key or self.caller_key}/{route}{rest}" + + def req(self, method, path, headers=(), body=None, conn=None): + c = conn or http.client.HTTPConnection("127.0.0.1", P["listen"], timeout=10) + c.putrequest(method, path, skip_host=True, skip_accept_encoding=True) + hs = list(headers) + if not any(k.lower() == "host" for k, _ in hs): + hs.insert(0, ("Host", AUTHORITY)) + for k, v in hs: + c.putheader(k, v) + if body is not None: + c.putheader("Content-Length", str(len(body))) + c.endheaders(body) + r = c.getresponse() + data = r.read() + if conn is None: + c.close() + return r.status, {k.lower(): v for k, v in r.getheaders()}, data + + def raw(self, data, port=None): + s = socket.create_connection(("127.0.0.1", port or P["listen"]), 5) + s.sendall(data) + out = b"" + s.settimeout(5) + try: + while True: + b = s.recv(65536) + if not b: + break + out += b + if b"\r\n\r\n" in out: + head, _, rest = out.partition(b"\r\n\r\n") + cl = [l for l in head.split(b"\r\n") if l.lower().startswith(b"content-length:")] + if cl and len(rest) >= int(cl[0].split(b":")[1]): + break + except socket.timeout: + pass + s.close() + line = out.split(b"\r\n", 1)[0].decode(errors="replace") + parts = line.split(" ") + return int(parts[1]) if len(parts) > 1 and parts[1].isdigit() else 0, out + + def direct_tls(self, port, sni, path, headers): + """A naive client following a redirect itself (carries whatever it holds: the surrogate).""" + ctx = ssl.create_default_context(cafile=f"{self.pki}/ca.pem") + c = http.client.HTTPSConnection("127.0.0.1", port, context=ctx, timeout=5) + c._tunnel_host = None + sock = socket.create_connection(("127.0.0.1", port), 5) + c.sock = ctx.wrap_socket(sock, server_hostname=sni) + c.putrequest("GET", path, skip_host=True) + c.putheader("Host", f"{sni}:{port}") + for k, v in headers: + c.putheader(k, v) + c.endheaders() + r = c.getresponse() + r.read() + c.close() + return r.status + + def secrets_in_files(self): + """Work-dir files that contain a real test credential, surrogate, caller key or the + authority token. The throwaway CA and the credential Secret files are exempt: they are + meant to hold key material.""" + needles = [v.encode() for v in self.creds.values()] + [s.encode() for s in self.minted] + \ + [self.caller_key.encode()] + ([self.token.encode()] if self.token else []) + hits = [] + for root, _, files in os.walk(self.work): + if root.startswith(self.pki) or root.startswith(self.secrets_dir): + continue + for fn in files: + p = os.path.join(root, fn) + try: + data = open(p, "rb").read() + except OSError: + continue + for n in needles: + if n in data: + hits.append(fn) + break + return hits + + def cleanup(self): + shutil.rmtree(self.work, ignore_errors=True) + + +def short_workdir(): + return tempfile.mkdtemp(prefix="apm-", dir="/tmp") diff --git a/tests/matrix/matrix.py b/tests/matrix/matrix.py new file mode 100644 index 0000000..cc33545 --- /dev/null +++ b/tests/matrix/matrix.py @@ -0,0 +1,571 @@ +#!/usr/bin/env python3 +"""The fail-closed matrix (design doc section 7), run against the real `auth-proxy`. + + matrix.py --bin DIR [--work DIR] [--json OUT] + +Ported from spike/exp2/test/matrix.py. The 25 Phase 0 rows are kept (Phase 1 +expectations: 403 for every surrogate state, the mock broker replaced by the +real session plane, X4 now "credential store unreadable"), and rows are added +for the session plane, resync after a proxy restart, aws_targets, request +bodies and WebSocket upgrades. A row is never removed or loosened without the +reason in the PR's review contract. + +Each case asserts the client-visible outcome AND what the mock upstreams +actually received, so "refused" means "nothing reached upstream", not just +"the client saw a 4xx". + +Exit code 0 only if no row FAILs. The lease-lapse, authority-restart and +`hello`-race rows need a shortened authority lease and live in the Rust +integration tests (crates/ap-proxy/tests/hello_race.rs). +""" +import argparse +import json +import os +import sys +import tempfile +import time +import traceback + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from harness import AUTHORITY, MAX_BODY, SESSION_LEASE_SECS, P, Env, short_workdir # noqa: E402 + +CASES = [] + + +def case(row, name, phase0=True): + def deco(f): + CASES.append((row, name, f, phase0)) + return f + return deco + + +AUTH = ("authorization", "proxy-authorization", "x-api-key", "x-goog-api-key", "api-key", "cookie", + "x-amz-security-token") + + +def n_req(e, listener=None): + lg = e.ulog()["log"] + return len([r for r in lg if listener is None or r["listener"] == listener]) + + +def bearer(s): + return [("Authorization", f"Bearer {s}")] + + +def refused(e, st, hdr, want_status=None, want_code=None): + """Refused = expected status/code and zero requests at any upstream.""" + n = n_req(e) + ok = n == 0 and 400 <= st < 600 + code = hdr.get("x-auth-proxy-error") + match = (want_status is None or st == want_status) and (want_code is None or code == want_code) + return ok and match, f"status={st} code={code} upstream_requests={n}" + + +def raw_req(e, line, headers): + data = (line + "\r\n" + "".join(f"{k}: {v}\r\n" for k, v in headers) + "\r\n").encode() + return e.raw(data) + + +# ---------------------------------------------------------------- R1 policy +@case("R1 policy empty or unavailable → refuse", "policy has no grants") +def _(e): + s = e.mint() + e.set_policy(grants=[]) + st, h, _ = e.req("GET", e.url("up", "/v1/echo"), bearer(s)) + return refused(e, st, h, 403, "policy_empty") + + +@case("R1 policy empty or unavailable → refuse", "policy file is 0 bytes") +def _(e): + s = e.mint() + e.set_policy(raw="") + st, h, _ = e.req("GET", e.url("up", "/v1/echo"), bearer(s)) + return refused(e, st, h, 503, "policy_unavailable") + + +@case("R1 policy empty or unavailable → refuse", "policy file deleted after a good load") +def _(e): + s = e.mint() + st0, _, _ = e.req("GET", e.url("up", "/v1/echo"), bearer(s)) + e.ureset() + e.set_policy(delete=True) + st, h, _ = e.req("GET", e.url("up", "/v1/echo"), bearer(s)) + ok, d = refused(e, st, h, 503, "policy_unavailable") + return ok and st0 == 200, f"before={st0} after: {d}" + + +@case("R1 policy empty or unavailable → refuse", "policy file corrupt TOML") +def _(e): + s = e.mint() + e.set_policy(raw='version = 1\n[[route\nname = "x"') + st, h, _ = e.req("GET", e.url("up", "/v1/echo"), bearer(s)) + return refused(e, st, h, 503, "policy_unavailable") + + +@case("R1 policy empty or unavailable → refuse", "policy allows other path/method only") +def _(e): + s = e.mint() + e.set_policy(grants=[{"credential": "c-up", "route": "up", "methods": ["POST"], "paths": ["/v2/"]}]) + st, h, _ = e.req("GET", e.url("up", "/v1/echo"), bearer(s)) + return refused(e, st, h, 403, "policy_denied") + + +# ---------------------------------------------------------------- R2 broker +@case("R2 broker unreachable → refuse, no stale cache", + "success, then session revoked through the session plane, same surrogate") +def _(e): + s = e.mint() + st0, _, _ = e.req("GET", e.url("up", "/v1/echo"), bearer(s)) + e.ureset() + e.revoke(s) + st, h, _ = e.req("GET", e.url("up", "/v1/echo"), bearer(s)) + ok, d = refused(e, st, h, 403, "surrogate_revoked") + return ok and st0 == 200, f"before={st0} after: {d}" + + +# ---------------------------------------------------------------- R3 surrogate state +@case("R3 surrogate expired or revoked → explicit 4xx", f"expired (session lease {SESSION_LEASE_SECS} s, not renewed)") +def _(e): + s = e.mint() + time.sleep(SESSION_LEASE_SECS + 0.7) + st, h, _ = e.req("GET", e.url("up", "/v1/echo"), bearer(s)) + return refused(e, st, h, 403, "surrogate_expired") + + +@case("R3 surrogate expired or revoked → explicit 4xx", "revoked after one good use") +def _(e): + s = e.mint() + st0, _, _ = e.req("GET", e.url("up", "/v1/echo"), bearer(s)) + e.ureset() + e.revoke(s) + st, h, _ = e.req("GET", e.url("up", "/v1/echo"), bearer(s)) + ok, d = refused(e, st, h, 403, "surrogate_revoked") + return ok and st0 == 200, f"before={st0} after: {d}" + + +@case("R3 surrogate expired or revoked → explicit 4xx", "unknown / malformed / missing surrogate") +def _(e): + out = [] + for label, hs, code in (("unknown", bearer("aps_" + "0" * 64), "surrogate_unknown"), + ("malformed", bearer("sk-not-a-surrogate"), "surrogate_malformed"), + ("missing", [], "surrogate_missing")): + st, h, _ = e.req("GET", e.url("up", "/v1/echo"), hs) + out.append((label, refused(e, st, h, 403, code))) + return all(o[1][0] for o in out), "; ".join(f"{l}: {d}" for l, (_, d) in out) + + +@case("R3 surrogate expired or revoked → explicit 4xx", "aws-dialect route: refusal body has __type") +def _(e): + s = e.mint() + e.revoke(s) + st, h, b = e.req("POST", e.url("upaws", "/v1/echo"), bearer(s), body=b"{}") + ok, d = refused(e, st, h, 403, "surrogate_revoked") + try: + j = json.loads(b) + except ValueError: + j = {} + ok = ok and j.get("__type") == "AccessDeniedException" and "auth-proxy" in j.get("message", "") + return ok, f"{d} __type={j.get('__type')}" + + +# ---------------------------------------------------------------- caller binding (pipeline steps 3 to 5) +@case("X1 caller key and surrogate binding", "wrong caller key / surrogate of another identity / other route's surrogate") +def _(e): + out = [] + st, h, _ = e.req("GET", f"/ap/apk_{'f' * 64}/up/v1/echo", bearer(e.mint())) + out.append(("bad key", refused(e, st, h, 403, "caller_rejected"))) + # A surrogate registered under identity agent-1; the policy now names agent-2. + s = e.mint() + e.set_policy(identity="agent-2") + st, h, _ = e.req("GET", e.url("up", "/v1/echo"), bearer(s)) + out.append(("other identity", refused(e, st, h, 403, "surrogate_wrong_caller"))) + e.set_policy() + # c-key is granted on route upkey only. + st, h, _ = e.req("GET", e.url("up", "/v1/echo"), bearer(e.mint(cred="c-key"))) + out.append(("other route", refused(e, st, h, 403, "surrogate_wrong_route"))) + return all(o[1][0] for o in out), "; ".join(f"{l}: {d}" for l, (_, d) in out) + + +# ---------------------------------------------------------------- R4 redirects +@case("R4 cross-host/port/scheme redirect → credential never forwarded", "302 to other host, other port, http://") +def _(e): + s = e.mint() + out = [] + for label, to in (("host", f"https://evil.up.test:{P['evil']}/v1/echo"), + ("port", f"https://api.up.test:{P['evil']}/v1/echo"), + ("scheme", f"http://api.up.test:{P['good']}/v1/echo")): + e.ureset() + st, h, _ = e.req("GET", e.url("up", f"/v1/redirect?to={to}"), bearer(s)) + lg = e.ulog()["log"] + good = [r for r in lg if r["listener"] == "good"] + evil = [r for r in lg if r["listener"] != "good"] + ok = st == 302 and h.get("location") == to and len(good) == 1 and not evil + out.append((label, ok, f"status={st} location_unchanged={h.get('location') == to} " + f"good={len(good)} other={len(evil)}")) + # A naive client that follows the redirect itself only holds the surrogate. + e.ureset() + e.direct_tls(P["evil"], "evil.up.test", "/v1/echo", bearer(s)) + lg = e.ulog()["log"] + vals = [v for r in lg for k, v in r["headers"] if k in AUTH] + leaked = any(c in v for v in vals for c in e.creds.values()) + out.append(("client follows", not leaked, f"evil got real credential={leaked}")) + return all(o[1] for o in out), "; ".join(f"{l}: {d}" for l, _, d in out) + + +# ---------------------------------------------------------------- R5 host canonicalization +@case("R5 userinfo, IP literal or ambiguous host → reject", "client Host / request-target variants (raw)") +def _(e): + s = e.mint() + path = e.url("up", "/v1/echo") + au = [("Authorization", f"Bearer {s}")] + variants = [ + ("Host userinfo", f"GET {path} HTTP/1.1", [("Host", f"user@{AUTHORITY}")] + au), + ("Host foreign name", f"GET {path} HTTP/1.1", [("Host", "evil.up.test")] + au), + ("Host IPv4 short form", f"GET {path} HTTP/1.1", [("Host", f"127.1:{P['listen']}")] + au), + ("Host trailing dot", f"GET {path} HTTP/1.1", [("Host", f"127.0.0.1.:{P['listen']}")] + au), + ("Host IPv6-mapped", f"GET {path} HTTP/1.1", [("Host", f"[::ffff:127.0.0.1]:{P['listen']}")] + au), + ("two Host headers", f"GET {path} HTTP/1.1", [("Host", AUTHORITY), ("Host", "evil.up.test")] + au), + ("no Host (HTTP/1.0)", f"GET {path} HTTP/1.0", au), + ("absolute-form foreign", f"GET http://evil.up.test{path} HTTP/1.1", [("Host", AUTHORITY)] + au), + ("absolute-form userinfo", f"GET http://u:p@{AUTHORITY}{path} HTTP/1.1", [("Host", AUTHORITY)] + au), + ] + out = [] + for label, line, hs in variants: + e.ureset() + st, _ = raw_req(e, line, hs) + n = n_req(e) + out.append((label, 400 <= st < 500 and n == 0, f"{st}/{n}")) + bad = [l for l, ok, _ in out if not ok] + return not bad, " ".join(f"[{l}: {d}]" for l, _, d in out) + (f" FAILED: {bad}" if bad else "") + + +@case("R5 userinfo, IP literal or ambiguous host → reject", "upstream route host is IP literal / userinfo / trailing dot") +def _(e): + out = [] + for label, host in (("IPv4", "127.0.0.1"), ("IPv6", "::1"), ("userinfo", "u@api.up.test"), + ("trailing dot", "api.up.test."), ("IPv4 short", "127.1"), ("uppercase", "API.up.test")): + p = os.path.join(e.work, "policy-bad.toml") + with open(p, "w") as f: + f.write(e.policy_toml(routes=[{"name": "x", "host": host}], credentials=False)) + rc, _ = e.run_startup_check(p) + out.append((label, rc == 2, f"exit={rc}")) + return all(o[1] for o in out), " ".join(f"[{l}: {d}]" for l, _, d in out) + + +@case("X2 path canonicalization", "dot-segments, encoded dots/slashes, empty segments (raw)") +def _(e): + s = e.mint() + k = e.caller_key + au = [("Host", AUTHORITY), ("Authorization", f"Bearer {s}")] + out = [] + for label, path in (("..", f"/ap/{k}/up/v1/../v1/echo"), ("%2e%2e", f"/ap/{k}/up/v1/%2e%2e/v1/echo"), + ("%2f", f"/ap/{k}/up/v1%2fecho"), ("//", f"/ap/{k}/up//v1/echo"), + ("route hop", f"/ap/{k}/badca/../up/v1/echo"), ("%252e", f"/ap/{k}/up/v1/%252e%252e/echo")): + e.ureset() + open(e.audit_file, "a").close() + before = sum(1 for _ in open(e.audit_file)) + st, _ = raw_req(e, f"GET {path} HTTP/1.1", au) + lg = e.ulog()["log"] + new = [json.loads(l) for l in list(open(e.audit_file))[before:]] + if not lg: + ok, d = 400 <= st < 500, f"refused {st}" + else: + # Forwarded: only acceptable if what policy saw is exactly what upstream got. + seen = [a.get("path") for a in new if a.get("decision") == "allow"] + got = lg[0]["path"].split("?")[0] + ok = seen == [got] and ".." not in got and "%" not in got + d = f"forwarded {st}, policy saw {seen} upstream got {got!r} ({lg[0]['listener']})" + out.append((label, ok, d)) + return all(o[1] for o in out), " ".join(f"[{l}: {d}]" for l, _, d in out) + + +@case("X3 CONNECT refused", "CONNECT api.up.test:443") +def _(e): + st, _ = raw_req(e, f"CONNECT api.up.test:{P['good']} HTTP/1.1", [("Host", f"api.up.test:{P['good']}")]) + n = n_req(e) + return st == 405 and n == 0, f"status={st} upstream_requests={n}" + + +# ---------------------------------------------------------------- R6 SNI / Host +@case("R6 SNI/Host mismatch → reject", "upstream sees SNI == Host == route host; client X-Forwarded-Host ignored") +def _(e): + s = e.mint() + st, _, _ = e.req("GET", e.url("up", "/v1/echo"), bearer(s) + [("X-Forwarded-Host", "evil.up.test")]) + lg = e.ulog()["log"] + if len(lg) != 1: + return False, f"status={st} upstream_requests={len(lg)}" + r = lg[0] + hosts = [v for k, v in r["headers"] if k == "host"] + ok = st == 200 and r["sni"] == "api.up.test" and hosts == [f"api.up.test:{P['good']}"] and r["listener"] == "good" + return ok, f"status={st} sni={r['sni']} host={hosts}" + + +@case("R6 SNI/Host mismatch → reject", "cert name ≠ route host (SNI wrongname.up.test, cert other.up.test)") +def _(e): + st, h, _ = e.req("GET", e.url("wrongname", "/v1/echo"), bearer(e.mint())) + ok, d = refused(e, st, h, 502, "upstream_unavailable") + hf = e.ulog()["handshake_fail"] + return ok, f"{d} handshake_fail={hf}" + + +# ---------------------------------------------------------------- R7 upstream TLS +@case("R7 upstream TLS verification failure → refuse", "cert from an untrusted CA") +def _(e): + st, h, _ = e.req("GET", e.url("badca", "/v1/echo"), bearer(e.mint())) + ok, d = refused(e, st, h, 502, "upstream_unavailable") + hf = e.ulog()["handshake_fail"] + return ok, f"{d} handshake_fail={hf}" + + +# ---------------------------------------------------------------- R8 header hygiene +@case("R8 client auth stripped, exactly one upstream credential", "bearer route + 6 junk auth headers + TokenType") +def _(e): + s = e.mint() + hs = bearer(s) + [("X-Api-Key", "junk-1"), ("Proxy-Authorization", "Basic junk-2"), ("Cookie", "a=junk-3"), + ("X-Goog-Api-Key", "junk-4"), ("X-Amz-Security-Token", "junk-5"), ("Api-Key", "junk-6"), + ("TokenType", "API_KEY")] + st, _, _ = e.req("POST", e.url("up", "/v1/echo"), hs, body=b"{}") + lg = e.ulog()["log"] + if len(lg) != 1: + return False, f"status={st} upstream_requests={len(lg)}" + hd = lg[0]["headers"] + auth = [(k, v) for k, v in hd if k in AUTH] + allv = " ".join(v for _, v in hd) + ok = (st == 200 and auth == [("authorization", f"Bearer {e.creds['c-up']}")] and s not in allv + and "junk-" not in allv and ("tokentype", "API_KEY") in [(k, v) for k, v in hd] + and e.caller_key not in allv and e.caller_key not in lg[0]["path"]) + return ok, (f"status={st} auth_headers_upstream={[k for k, _ in auth]} real={auth[:1] and auth[0][1].endswith(e.creds['c-up'])} " + f"surrogate_seen={s in allv} junk_seen={'junk-' in allv} tokentype_kept={'API_KEY' in allv} " + f"caller_key_seen={e.caller_key in allv + lg[0]['path']}") + + +@case("R8 client auth stripped, exactly one upstream credential", "x-api-key route + junk Authorization") +def _(e): + s = e.mint(cred="c-key") + st, _, _ = e.req("POST", e.url("upkey", "/v1/echo"), [("x-api-key", s), ("Authorization", "Bearer junk-7")], + body=b"{}") + lg = e.ulog()["log"] + if len(lg) != 1: + return False, f"status={st} upstream_requests={len(lg)}" + auth = [(k, v) for k, v in lg[0]["headers"] if k in AUTH] + return st == 200 and auth == [("x-api-key", e.creds["c-key"])], f"status={st} auth_headers_upstream={[k for k, _ in auth]}" + + +@case("R8 client auth stripped, exactly one upstream credential", "two surrogate headers → reject") +def _(e): + s = e.mint() + st, _ = raw_req(e, f"GET {e.url('up', '/v1/echo')} HTTP/1.1", + [("Host", AUTHORITY), ("Authorization", f"Bearer {s}"), ("Authorization", f"Bearer {s}")]) + n = n_req(e) + return st == 400 and n == 0, f"status={st} upstream_requests={n}" + + +# ---------------------------------------------------------------- X4 enforcement point down +@case("X4 enforcement point down → refuse", "credential store unreadable after a good request (S1 file removed)") +def _(e): + s = e.mint() + st0, _, _ = e.req("GET", e.url("up", "/v1/echo"), bearer(s)) + e.ureset() + e.remove_secret("c-up") + try: + st, h, _ = e.req("GET", e.url("up", "/v1/echo"), bearer(s)) + ok, d = refused(e, st, h, 503, "broker_unavailable") + finally: + e.write_secret("c-up") + return ok and st0 == 200, f"before={st0} after: {d}" + + +# ---------------------------------------------------------------- streaming +@case("X6 SSE streaming through the proxy (mock)", "20 events × 50 ms: not buffered") +def _(e): + import http.client + s = e.mint() + c = http.client.HTTPConnection("127.0.0.1", P["listen"], timeout=10) + t0 = time.time() + c.putrequest("GET", e.url("up", "/v1/sse"), skip_host=True, skip_accept_encoding=True) + c.putheader("Host", AUTHORITY) + c.putheader("Authorization", f"Bearer {s}") + c.endheaders() + r = c.getresponse() + ts = [] + while True: + line = r.fp.readline() + if not line: + break + if line.startswith(b"data:"): + ts.append(time.time() - t0) + if len(ts) == 20: + break + c.close() + ok = r.status == 200 and len(ts) == 20 and ts[0] < 0.3 and ts[-1] - ts[0] > 0.8 + return ok, f"status={r.status} events={len(ts)} first={ts[0] if ts else -1:.3f}s spread={(ts[-1] - ts[0]) if ts else 0:.3f}s" + + +# ================================================================ rows added in Phase 1 +@case("P1 session plane authentication", "no token / wrong token / hello while an authority is live", phase0=False) +def _(e): + out = [] + st, j = e.plane("POST", "/v1/sessions", {"session": "x", "generation": 1, "surrogate_sha256": "0" * 64, + "credentials": ["c-up"]}, token=None) + out.append(("no token", st == 401, f"{st} {j and j.get('error')}")) + for label, call in (("renew", ("POST", "/v1/renew", {"sessions": []})), + ("revoke", ("DELETE", "/v1/sessions/x/1", None)), + ("resync", ("PUT", "/v1/sessions", {"sessions": []}))): + st, j = e.plane(*call, token="apt_" + "0" * 64) + out.append((f"wrong token {label}", st == 401, f"{st} {j and j.get('error')}")) + st, j = e.plane("POST", "/v1/hello", {}, token=None) + out.append(("hello while live", st == 409 and j.get("error") == "authority_active", f"{st} {j and j.get('error')}")) + st, j = e.plane("POST", "/v1/sessions", {"session": "x", "generation": 1, "surrogate_sha256": "XYZ", + "credentials": ["c-up"]}) + out.append(("bad field", st == 400, f"{st}")) + st, j = e.plane("POST", "/v1/sessions", {"session": "x", "generation": 1, "surrogate_sha256": "0" * 64, + "credentials": ["nope"]}) + out.append(("credential not granted", st == 403, f"{st}")) + st, j = e.plane("POST", "/v1/sessions", raw=b"x" * (1024 * 1024 + 1)) + out.append(("body over 1 MiB", st == 413, f"{st}")) + return all(o[1] for o in out), " ".join(f"[{l}: {d}]" for l, _, d in out) + + +@case("P2 resync after a proxy restart", "same surrogate works again, dropped sessions stay dropped", phase0=False) +def _(e): + keep, drop = e.mint(session="keep"), e.mint(session="drop") + st0, _, _ = e.req("GET", e.url("up", "/v1/echo"), bearer(keep)) + e.stop("auth-proxy", kill=True) # SIGKILL: the socket files stay behind and must be replaced + e.start_impl() + e.ureset() + st1, h1, _ = e.req("GET", e.url("up", "/v1/echo"), bearer(keep)) + gap_ok, gap = refused(e, st1, h1, 403, "surrogate_unknown") + sk, sd = e.sessions[keep], e.sessions[drop] + st, j = e.plane("POST", "/v1/renew", {"sessions": [{"session": s["session"], "generation": s["generation"]} + for s in (sk, sd)]}) + unknown = sorted(u["session"] for u in (j or {}).get("unknown", [])) + st2, j2 = e.plane("PUT", "/v1/sessions", {"sessions": [sk]}) + e.ureset() + st3, _, _ = e.req("GET", e.url("up", "/v1/echo"), bearer(keep)) + st4, h4, _ = e.req("GET", e.url("up", "/v1/echo"), bearer(drop)) + n_drop_gap = n_req(e) + ok = (st0 == 200 and gap_ok and st == 200 and unknown == ["drop", "keep"] and st2 == 200 + and j2 == {"registered": 1, "dropped": 0} and st3 == 200 and st4 == 403 and n_drop_gap == 1) + return ok, (f"before={st0} gap: {gap}; renew unknown={unknown}; resync={st2} {j2}; " + f"after keep={st3} drop={st4}/{h4.get('x-auth-proxy-error')} upstream_requests={n_drop_gap}") + + +@case("P3 aws_targets", "one X-Amz-Target allowed; none, two and a wrong one denied", phase0=False) +def _(e): + s = e.mint() + e.set_policy(grants=[{"credential": "c-up", "route": "upaws", "methods": ["POST"], "paths": ["/v1/"], + "aws_targets": ["Svc.Allowed"]}]) + url = e.url("upaws", "/v1/echo") + out = [] + st, _, _ = e.req("POST", url, bearer(s) + [("X-Amz-Target", "Svc.Allowed")], body=b"{}") + out.append(("allowed", st == 200 and n_req(e) == 1, f"{st}")) + e.ureset() + for label, extra in (("none", []), ("wrong", [("X-Amz-Target", "Svc.Other")]), + ("two", [("X-Amz-Target", "Svc.Allowed"), ("X-Amz-Target", "Svc.Allowed")])): + st, h, b = e.req("POST", url, bearer(s) + extra, body=b"{}") + ok, d = refused(e, st, h, 403, "policy_denied") + out.append((label, ok and b"AccessDeniedException" in b, d)) + return all(o[1] for o in out), " ".join(f"[{l}: {d}]" for l, _, d in out) + + +@case("P4 request body cap", f"1.5 MiB streams through; over the {MAX_BODY >> 20} MiB cap is 413 with nothing sent upstream", + phase0=False) +def _(e): + s = e.mint() + big = b"a" * (3 * 1024 * 1024 // 2) + st, _, _ = e.req("POST", e.url("up", "/v1/echo"), bearer(s), body=big) + lg = e.ulog()["log"] + ok1 = st == 200 and len(lg) == 1 and lg[0]["body_len"] == len(big) + e.ureset() + st2, h2, _ = e.req("POST", e.url("up", "/v1/echo"), bearer(s), body=b"b" * (MAX_BODY + 1)) + ok2, d2 = refused(e, st2, h2, 413, "body_too_large") + return ok1 and ok2, f"1.5MiB: status={st} upstream_body={lg[0]['body_len'] if lg else None}; over cap: {d2}" + + +@case("P5 slow request body", "1000 bytes over 1.2 s is forwarded whole", phase0=False) +def _(e): + import socket + s = e.mint() + sock = socket.create_connection(("127.0.0.1", P["listen"]), 5) + head = (f"POST {e.url('up', '/v1/echo')} HTTP/1.1\r\nHost: {AUTHORITY}\r\nAuthorization: Bearer {s}\r\n" + f"Content-Length: 1000\r\n\r\n").encode() + sock.sendall(head) + for _ in range(10): + sock.sendall(b"x" * 100) + time.sleep(0.12) + sock.settimeout(5) + out = b"" + while b"\r\n\r\n" not in out: + b = sock.recv(65536) + if not b: + break + out += b + sock.close() + lg = e.ulog()["log"] + status = out.split(b" ", 2)[1] if out else b"?" + ok = status == b"200" and len(lg) == 1 and lg[0]["body_len"] == 1000 + return ok, f"status={status.decode()} upstream_requests={len(lg)} upstream_body={lg[0]['body_len'] if lg else None}" + + +@case("P6 WebSocket upgrade refused", "GET with Upgrade: websocket → 501, nothing upstream", phase0=False) +def _(e): + s = e.mint() + st, h, _ = e.req("GET", e.url("up", "/v1/ws"), bearer(s) + [("Connection", "Upgrade"), ("Upgrade", "websocket")]) + return refused(e, st, h, 501, "websocket_unsupported") + + +# ---------------------------------------------------------------- log hygiene (last) +@case("X5 no secret in any log", "real test credentials, surrogates, caller key, authority token vs every work-dir file") +def _(e): + hits = e.secrets_in_files() + prefix = [] + for fn in (e.audit_file, e.err_file): + data = open(fn, "rb").read() + if b"/ap/" in data: + prefix.append(os.path.basename(fn)) + files = sorted(os.listdir(e.work)) + return not hits and not prefix, (f"files_with_secret={hits} files_with_/ap/_prefix={prefix} " + f"scanned={[f for f in files if f not in ('pki', 'secrets')]}") + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--bin", required=True) + ap.add_argument("--work") + ap.add_argument("--json") + a = ap.parse_args() + work = a.work or short_workdir() + e = Env(work, os.path.abspath(a.bin)) + results = [] + try: + e.start_upstream() + e.set_policy() + e.start_impl() + e.hello() + for row, name, f, phase0 in CASES: + e.set_policy() + e.ureset() + try: + ok, detail = f(e) + except Exception as ex: # a crash is a failure, with the traceback + ok, detail = False, f"EXCEPTION {ex!r} {traceback.format_exc(limit=2)}" + verdict = "n/a" if ok is None else ("PASS" if ok else "FAIL") + results.append({"row": row, "case": name, "verdict": verdict, "detail": detail, "phase0": phase0}) + print(f"{verdict:4} | {row} | {name} | {detail}", flush=True) + finally: + e.close() + if a.json: + with open(a.json, "w") as f: + json.dump({"results": results}, f, indent=1) + base = [r for r in results if r["phase0"]] + added = [r for r in results if not r["phase0"]] + fails = [r for r in results if r["verdict"] != "PASS"] + bp = sum(r["verdict"] == "PASS" for r in base) + ap_ = sum(r["verdict"] == "PASS" for r in added) + print(f"\nPhase 0 rows: {bp}/{len(base)} PASS; added session-plane/body rows: {ap_}/{len(added)} PASS; " + f"total {len(results) - len(fails)}/{len(results)} PASS; work dir {work}") + return 1 if fails or len(base) != 25 else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/matrix/upstream.py b/tests/matrix/upstream.py new file mode 100644 index 0000000..e8b8f18 --- /dev/null +++ b/tests/matrix/upstream.py @@ -0,0 +1,150 @@ +#!/usr/bin/env python3 +"""Mock TLS upstreams for the fail-closed matrix and the Rust integration tests +(test credentials only). Ported from spike/exp2/test/upstream.py. + + upstream.py --control PORT --listen NAME=PORT:CERT:KEY [--listen ...] + +Every listener records each request it receives: SNI, method, path, and all +headers. The harness reads the record from the plain-HTTP control port +(GET /log, POST /reset). The values recorded are random per-run test +credentials, never real ones. + +Paths: /v1/echo (200 JSON), /v1/small (tiny body, for latency runs), +/v1/sse (20 SSE events, 50 ms apart, chunked), /v1/redirect?to=URL (302). +""" +import argparse +import json +import ssl +import sys +import threading +import time +import urllib.parse +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +LOG = [] +HANDSHAKE_FAIL = {} +LOCK = threading.Lock() + + +class TLSServer(ThreadingHTTPServer): + daemon_threads = True + request_queue_size = 256 + + def __init__(self, addr, handler, ctx, name): + super().__init__(addr, handler) + self.ctx, self.name = ctx, name + + def finish_request(self, request, client_address): + # Handshake in the worker thread, so a failing client cannot stall accept(). + try: + tls = self.ctx.wrap_socket(request, server_side=True) + except (ssl.SSLError, OSError): + with LOCK: + HANDSHAKE_FAIL[self.name] = HANDSHAKE_FAIL.get(self.name, 0) + 1 + return + self.RequestHandlerClass(tls, client_address, self) + + +class H(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + disable_nagle_algorithm = True # else Nagle + delayed ACK adds 40 ms per response + + def log_message(self, *a): + pass + + def _record(self): + n = int(self.headers.get("content-length") or 0) + got = 0 + while got < n: + chunk = self.rfile.read(min(65536, n - got)) + if not chunk: + break + got += len(chunk) + with LOCK: + LOG.append({ + "listener": self.server.name, + "sni": getattr(self.connection, "ap_sni", None), + "method": self.command, + "path": self.path, + "body_len": got, + "headers": [[k.lower(), v] for k, v in self.headers.items()], + }) + + def _send(self, code, body=b"", ctype="application/json", extra=()): + self.send_response(code) + self.send_header("content-type", ctype) + self.send_header("content-length", str(len(body))) + for k, v in extra: + self.send_header(k, v) + self.end_headers() + self.wfile.write(body) + + def handle_any(self): + self._record() + u = urllib.parse.urlsplit(self.path) + if u.path == "/v1/sse": + self.send_response(200) + self.send_header("content-type", "text/event-stream") + self.send_header("transfer-encoding", "chunked") + self.end_headers() + for i in range(20): + chunk = f"event: delta\ndata: {{\"i\": {i}}}\n\n".encode() + self.wfile.write(b"%x\r\n%s\r\n" % (len(chunk), chunk)) + self.wfile.flush() + time.sleep(0.05) + self.wfile.write(b"0\r\n\r\n") + return + if u.path == "/v1/redirect": + to = urllib.parse.parse_qs(u.query).get("to", ["https://evil.up.test/"])[0] + return self._send(302, b"", extra=[("location", to)]) + if u.path == "/v1/small": + return self._send(200, b'{"ok":true}') + return self._send(200, json.dumps({"ok": True, "listener": self.server.name}).encode()) + + do_GET = do_POST = do_PUT = do_DELETE = do_PATCH = handle_any + + +class Ctl(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + disable_nagle_algorithm = True + + def log_message(self, *a): + pass + + def do_GET(self): + with LOCK: + b = json.dumps({"log": LOG, "handshake_fail": HANDSHAKE_FAIL}).encode() + self.send_response(200) + self.send_header("content-length", str(len(b))) + self.end_headers() + self.wfile.write(b) + + def do_POST(self): + with LOCK: + LOG.clear() + HANDSHAKE_FAIL.clear() + self.send_response(204) + self.send_header("content-length", "0") + self.end_headers() + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--control", type=int, required=True) + ap.add_argument("--listen", action="append", default=[]) + a = ap.parse_args() + for spec in a.listen: + name, rest = spec.split("=", 1) + port, cert, key = rest.split(":") + ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + ctx.load_cert_chain(cert, key) + ctx.sni_callback = lambda s, n, c: setattr(s, "ap_sni", n) + srv = TLSServer(("127.0.0.1", int(port)), H, ctx, name) + threading.Thread(target=srv.serve_forever, daemon=True).start() + ctl = ThreadingHTTPServer(("127.0.0.1", a.control), Ctl) + print("upstream ready", flush=True) + ctl.serve_forever() + + +if __name__ == "__main__": + sys.exit(main()) From 4b68058e6c998778c092b6779e095976f0b031e3 Mon Sep 17 00:00:00 2001 From: chaodu-agent <274062505+chaodu-agent@users.noreply.github.com> Date: Mon, 16 Nov 2026 07:41:26 -0500 Subject: [PATCH 03/18] feat: add ap-egress CONNECT-only allowlist proxy and dependency check (FEAT-003) Ran on macmini: cargo clippy -p ap-egress --all-targets -D warnings (clean), cargo test -p ap-egress (6 passed), cargo fmt --check (ok), scripts/check-egress-deps.sh (exit 0; exit 1 with ap-broker temporarily added, reverted). --- Cargo.lock | 8 + crates/ap-egress/Cargo.toml | 21 ++ crates/ap-egress/src/lib.rs | 367 ++++++++++++++++++++++++++++++ crates/ap-egress/src/main.rs | 80 +++++++ crates/ap-egress/tests/connect.rs | 323 ++++++++++++++++++++++++++ scripts/check-egress-deps.sh | 18 ++ 6 files changed, 817 insertions(+) create mode 100644 crates/ap-egress/Cargo.toml create mode 100644 crates/ap-egress/src/lib.rs create mode 100644 crates/ap-egress/src/main.rs create mode 100644 crates/ap-egress/tests/connect.rs create mode 100755 scripts/check-egress-deps.sh diff --git a/Cargo.lock b/Cargo.lock index 46a1802..c184fc2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -42,6 +42,14 @@ dependencies = [ "toml", ] +[[package]] +name = "ap-egress" +version = "0.1.0" +dependencies = [ + "ap-core", + "tokio", +] + [[package]] name = "ap-proxy" version = "0.1.0" 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