From aa483ecb9a72cbe056bc0f91a9cfbcbd55a744c2 Mon Sep 17 00:00:00 2001 From: Russell Bryant Date: Thu, 16 Jul 2026 16:28:01 -0400 Subject: [PATCH 1/5] feat(providers): AWS STS AssumeRole refresh strategy and aws-s3 profile (#1782) Add gateway-managed AWS STS credential refresh (provider-v2, #1576). The gateway calls sts:AssumeRole and writes three short-lived credentials (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_SESSION_TOKEN) to the provider record; the proxy re-signs requests with SigV4. Adds the aws and aws-s3 provider profiles and a declarative multi-output refresh model (additional_outputs) so one AssumeRole co-mints all three credentials. Signed-off-by: Russell Bryant --- Cargo.lock | 441 +++++- Cargo.toml | 4 + architecture/gateway.md | 5 +- architecture/security-policy.md | 11 +- crates/openshell-cli/src/main.rs | 2 + crates/openshell-cli/src/run.rs | 2 + crates/openshell-policy/src/lib.rs | 103 ++ crates/openshell-prover/src/credentials.rs | 71 +- crates/openshell-providers/src/lib.rs | 5 +- crates/openshell-providers/src/profiles.rs | 720 ++++++++- crates/openshell-server/Cargo.toml | 2 + crates/openshell-server/src/grpc/policy.rs | 26 +- crates/openshell-server/src/grpc/provider.rs | 1316 ++++++++++++++++- .../src/persistence/postgres.rs | 19 +- .../src/persistence/sqlite.rs | 18 +- .../openshell-server/src/provider_refresh.rs | 1122 +++++++++++++- .../src/l7/mod.rs | 74 +- .../src/l7/rest.rs | 97 +- .../openshell-supervisor-network/src/opa.rs | 82 + crates/openshell-tui/src/app.rs | 3 + docs/providers/aws-sigv4.mdx | 6 + docs/sandboxes/manage-providers.mdx | 57 +- docs/sandboxes/providers-v2.mdx | 30 +- examples/aws-s3-sts.md | 278 ++++ proto/openshell.proto | 16 + providers/aws-s3.yaml | 124 ++ providers/aws.yaml | 61 + 27 files changed, 4496 insertions(+), 199 deletions(-) create mode 100644 examples/aws-s3-sts.md create mode 100644 providers/aws-s3.yaml create mode 100644 providers/aws.yaml diff --git a/Cargo.lock b/Cargo.lock index 1de52d8841..e507c19bdc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -267,6 +267,31 @@ dependencies = [ "cc", ] +[[package]] +name = "aws-config" +version = "1.8.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11493b0bad143270fb8ad284a096dd529ba91924c5409adeac856cc1bf047dbc" +dependencies = [ + "aws-credential-types", + "aws-runtime", + "aws-sdk-sts", + "aws-smithy-async", + "aws-smithy-http", + "aws-smithy-json", + "aws-smithy-runtime", + "aws-smithy-runtime-api", + "aws-smithy-types", + "aws-types", + "bytes", + "fastrand", + "http 1.4.0", + "time", + "tokio", + "tracing", + "url", +] + [[package]] name = "aws-credential-types" version = "1.2.14" @@ -302,6 +327,56 @@ dependencies = [ "fs_extra", ] +[[package]] +name = "aws-runtime" +version = "1.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5fc0651c57e384202e47153c1260b84a9936e19803d747615edf199dc3b98d17" +dependencies = [ + "aws-credential-types", + "aws-sigv4", + "aws-smithy-async", + "aws-smithy-http", + "aws-smithy-runtime", + "aws-smithy-runtime-api", + "aws-smithy-types", + "aws-types", + "bytes", + "bytes-utils", + "fastrand", + "http 1.4.0", + "http-body 1.0.1", + "percent-encoding", + "pin-project-lite", + "tracing", + "uuid", +] + +[[package]] +name = "aws-sdk-sts" +version = "1.102.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fc35b7a14cabdad13795fbbbd26d5ddec0882c01492ceedf2af575aad5f37dd" +dependencies = [ + "aws-credential-types", + "aws-runtime", + "aws-smithy-async", + "aws-smithy-http", + "aws-smithy-json", + "aws-smithy-observability", + "aws-smithy-query", + "aws-smithy-runtime", + "aws-smithy-runtime-api", + "aws-smithy-types", + "aws-smithy-xml", + "aws-types", + "fastrand", + "http 0.2.12", + "http 1.4.0", + "regex-lite", + "tracing", +] + [[package]] name = "aws-sigv4" version = "1.4.2" @@ -356,6 +431,92 @@ dependencies = [ "tracing", ] +[[package]] +name = "aws-smithy-http-client" +version = "1.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c3ef8931ad1c98aa6a55b4256f847f3116090819844e0dd41ea682cac5dd2d3" +dependencies = [ + "aws-smithy-async", + "aws-smithy-runtime-api", + "aws-smithy-types", + "h2 0.3.27", + "h2 0.4.13", + "http 0.2.12", + "http 1.4.0", + "http-body 0.4.6", + "hyper 0.14.32", + "hyper 1.9.0", + "hyper-rustls 0.24.2", + "hyper-rustls 0.27.9", + "hyper-util", + "pin-project-lite", + "rustls 0.21.12", + "rustls 0.23.38", + "rustls-native-certs", + "rustls-pki-types", + "tokio", + "tokio-rustls 0.26.4", + "tower 0.5.3", + "tracing", +] + +[[package]] +name = "aws-smithy-json" +version = "0.62.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "701a947f4797e52a911e114a898667c746c39feea467bbd1abd7b3721f702ffa" +dependencies = [ + "aws-smithy-runtime-api", + "aws-smithy-schema", + "aws-smithy-types", +] + +[[package]] +name = "aws-smithy-observability" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a06c2315d173edbf1920da8ba3a7189695827002e4c0fc961973ab1c54abca9c" +dependencies = [ + "aws-smithy-runtime-api", +] + +[[package]] +name = "aws-smithy-query" +version = "0.60.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a56d79744fb3edb5d722ef79d86081e121d3b9422cb209eb03aea6aa4f21ebd" +dependencies = [ + "aws-smithy-types", + "urlencoding", +] + +[[package]] +name = "aws-smithy-runtime" +version = "1.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e6f5caf6fea86f8c2206541ab5857cfcda9013426cdbe8fa0098b9e2d32182" +dependencies = [ + "aws-smithy-async", + "aws-smithy-http", + "aws-smithy-http-client", + "aws-smithy-observability", + "aws-smithy-runtime-api", + "aws-smithy-schema", + "aws-smithy-types", + "bytes", + "fastrand", + "http 0.2.12", + "http 1.4.0", + "http-body 0.4.6", + "http-body 1.0.1", + "http-body-util", + "pin-project-lite", + "pin-utils", + "tokio", + "tracing", +] + [[package]] name = "aws-smithy-runtime-api" version = "1.12.3" @@ -385,6 +546,17 @@ dependencies = [ "syn 2.0.117", ] +[[package]] +name = "aws-smithy-schema" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7442cb268338f0eb8278140a107c046756aa01093d8ef5e99628d34ae09c94f5" +dependencies = [ + "aws-smithy-runtime-api", + "aws-smithy-types", + "http 1.4.0", +] + [[package]] name = "aws-smithy-types" version = "1.5.0" @@ -394,6 +566,7 @@ dependencies = [ "base64-simd", "bytes", "bytes-utils", + "futures-core", "http 0.2.12", "http 1.4.0", "http-body 0.4.6", @@ -406,6 +579,32 @@ dependencies = [ "ryu", "serde", "time", + "tokio", + "tokio-util", +] + +[[package]] +name = "aws-smithy-xml" +version = "0.60.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ce02add1aa3677d022f8adf81dcbe3046a95f17a1b1e8979c145cd21d3d22b3" +dependencies = [ + "xmlparser", +] + +[[package]] +name = "aws-types" +version = "1.3.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d16bf10b03a3c01e6b3b7d47cd964e873ffe9e7d4e80fad16bd4c077cb068531" +dependencies = [ + "aws-credential-types", + "aws-smithy-async", + "aws-smithy-runtime-api", + "aws-smithy-schema", + "aws-smithy-types", + "rustc_version", + "tracing", ] [[package]] @@ -422,7 +621,7 @@ dependencies = [ "http 1.4.0", "http-body 1.0.1", "http-body-util", - "hyper", + "hyper 1.9.0", "hyper-util", "itoa", "matchit", @@ -642,7 +841,7 @@ dependencies = [ "hex", "http 1.4.0", "http-body-util", - "hyper", + "hyper 1.9.0", "hyper-named-pipe", "hyper-util", "hyperlocal", @@ -1947,6 +2146,25 @@ dependencies = [ "subtle", ] +[[package]] +name = "h2" +version = "0.3.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0beca50380b1fc32983fc1cb4587bfa4bb9e78fc259aad4a0032d2080309222d" +dependencies = [ + "bytes", + "fnv", + "futures-core", + "futures-sink", + "futures-util", + "http 0.2.12", + "indexmap", + "slab", + "tokio", + "tokio-util", + "tracing", +] + [[package]] name = "h2" version = "0.4.13" @@ -2184,6 +2402,30 @@ dependencies = [ "typenum", ] +[[package]] +name = "hyper" +version = "0.14.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41dfc780fdec9373c01bae43289ea34c972e40ee3c9f6b3c8801a35f35586ce7" +dependencies = [ + "bytes", + "futures-channel", + "futures-core", + "futures-util", + "h2 0.3.27", + "http 0.2.12", + "http-body 0.4.6", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "socket2 0.5.10", + "tokio", + "tower-service", + "tracing", + "want", +] + [[package]] name = "hyper" version = "1.9.0" @@ -2194,7 +2436,7 @@ dependencies = [ "bytes", "futures-channel", "futures-core", - "h2", + "h2 0.4.13", "http 1.4.0", "http-body 1.0.1", "httparse", @@ -2213,7 +2455,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "73b7d8abf35697b81a825e386fc151e0d503e8cb5fcb93cc8669c376dfd6f278" dependencies = [ "hex", - "hyper", + "hyper 1.9.0", "hyper-util", "pin-project-lite", "tokio", @@ -2221,6 +2463,21 @@ dependencies = [ "winapi", ] +[[package]] +name = "hyper-rustls" +version = "0.24.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec3efd23720e2049821a693cbc7e65ea87c72f1c58ff2f9522ff332b1491e590" +dependencies = [ + "futures-util", + "http 0.2.12", + "hyper 0.14.32", + "log", + "rustls 0.21.12", + "tokio", + "tokio-rustls 0.24.1", +] + [[package]] name = "hyper-rustls" version = "0.27.9" @@ -2228,13 +2485,13 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "33ca68d021ef39cf6463ab54c1d0f5daf03377b70561305bb89a8f83aab66e0f" dependencies = [ "http 1.4.0", - "hyper", + "hyper 1.9.0", "hyper-util", "log", - "rustls", + "rustls 0.23.38", "rustls-native-certs", "tokio", - "tokio-rustls", + "tokio-rustls 0.26.4", "tower-service", "webpki-roots 1.0.7", ] @@ -2245,7 +2502,7 @@ version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2b90d566bffbce6a75bd8b09a05aa8c2cb1fabb6cb348f8840c9e4c90a0d83b0" dependencies = [ - "hyper", + "hyper 1.9.0", "hyper-util", "pin-project-lite", "tokio", @@ -2264,12 +2521,12 @@ dependencies = [ "futures-util", "http 1.4.0", "http-body 1.0.1", - "hyper", + "hyper 1.9.0", "ipnet", "libc", "percent-encoding", "pin-project-lite", - "socket2", + "socket2 0.6.3", "tokio", "tower-service", "tracing", @@ -2283,7 +2540,7 @@ checksum = "986c5ce3b994526b3cd75578e62554abd09f0899d6206de48b3e96ab34ccc8c7" dependencies = [ "hex", "http-body-util", - "hyper", + "hyper 1.9.0", "hyper-util", "pin-project-lite", "tokio", @@ -2810,15 +3067,15 @@ dependencies = [ "http 1.4.0", "http-body 1.0.1", "http-body-util", - "hyper", - "hyper-rustls", + "hyper 1.9.0", + "hyper-rustls 0.27.9", "hyper-timeout", "hyper-util", "jsonpath-rust", "k8s-openapi", "kube-core", "pem", - "rustls", + "rustls 0.23.38", "rustls-pemfile", "secrecy", "serde", @@ -3153,7 +3410,7 @@ checksum = "3589659543c04c7dc5526ec858591015b87cd8746583b51b48ef4353f99dbcda" dependencies = [ "base64 0.22.1", "http-body-util", - "hyper", + "hyper 1.9.0", "hyper-util", "indexmap", "ipnet", @@ -3587,8 +3844,8 @@ dependencies = [ "dialoguer", "futures", "http-body-util", - "hyper", - "hyper-rustls", + "hyper 1.9.0", + "hyper-rustls 0.27.9", "hyper-util", "indicatif", "miette", @@ -3603,7 +3860,7 @@ dependencies = [ "prost-types", "rcgen", "reqwest 0.12.28", - "rustls", + "rustls 0.23.38", "rustls-pemfile", "serde", "serde_json", @@ -3613,7 +3870,7 @@ dependencies = [ "tempfile", "thiserror 2.0.18", "tokio", - "tokio-rustls", + "tokio-rustls 0.26.4", "tokio-stream", "tokio-tungstenite 0.26.2", "tonic", @@ -3700,7 +3957,7 @@ dependencies = [ "clap", "futures", "http-body-util", - "hyper", + "hyper 1.9.0", "hyper-util", "miette", "nix", @@ -3854,7 +4111,7 @@ dependencies = [ "openshell-supervisor-network", "openshell-supervisor-process", "prost", - "rustls", + "rustls 0.23.38", "serde", "serde_json", "temp-env", @@ -3873,17 +4130,17 @@ version = "0.0.0" dependencies = [ "async-trait", "futures", - "hyper", + "hyper 1.9.0", "hyper-util", "miette", "oauth2", "openshell-core", "reqwest 0.12.28", - "rustls", + "rustls 0.23.38", "serde", "thiserror 2.0.18", "tokio", - "tokio-rustls", + "tokio-rustls 0.26.4", "tokio-stream", "tokio-tungstenite 0.26.2", "tonic", @@ -3898,6 +4155,8 @@ dependencies = [ "anyhow", "arc-swap", "async-trait", + "aws-config", + "aws-sdk-sts", "axum", "bytes", "clap", @@ -3909,8 +4168,8 @@ dependencies = [ "http 1.4.0", "http-body 1.0.1", "http-body-util", - "hyper", - "hyper-rustls", + "hyper 1.9.0", + "hyper-rustls 0.27.9", "hyper-util", "ipnet", "jsonwebtoken 9.3.1", @@ -3941,7 +4200,7 @@ dependencies = [ "reqwest 0.12.28", "russh", "rustix 1.1.4", - "rustls", + "rustls 0.23.38", "rustls-pemfile", "serde", "serde_json", @@ -3950,7 +4209,7 @@ dependencies = [ "tempfile", "thiserror 2.0.18", "tokio", - "tokio-rustls", + "tokio-rustls 0.26.4", "tokio-stream", "tokio-tungstenite 0.26.2", "toml", @@ -3999,7 +4258,7 @@ dependencies = [ "rcgen", "regorus", "reqwest 0.12.28", - "rustls", + "rustls 0.23.38", "rustls-pemfile", "serde", "serde_json", @@ -4011,7 +4270,7 @@ dependencies = [ "tempfile", "thiserror 2.0.18", "tokio", - "tokio-rustls", + "tokio-rustls 0.26.4", "tokio-tungstenite 0.26.2", "tower-mcp-types", "tracing", @@ -4689,8 +4948,8 @@ dependencies = [ "quinn-proto", "quinn-udp", "rustc-hash 2.1.2", - "rustls", - "socket2", + "rustls 0.23.38", + "socket2 0.6.3", "thiserror 2.0.18", "tokio", "tracing", @@ -4710,7 +4969,7 @@ dependencies = [ "rand 0.9.4", "ring", "rustc-hash 2.1.2", - "rustls", + "rustls 0.23.38", "rustls-pki-types", "slab", "thiserror 2.0.18", @@ -4728,7 +4987,7 @@ dependencies = [ "cfg_aliases", "libc", "once_cell", - "socket2", + "socket2 0.6.3", "tracing", "windows-sys 0.60.2", ] @@ -4911,6 +5170,12 @@ dependencies = [ "regex-syntax", ] +[[package]] +name = "regex-lite" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cab834c73d247e67f4fae452806d17d3c7501756d98c8808d7c9c7aa7d18f973" + [[package]] name = "regex-syntax" version = "0.8.10" @@ -4950,15 +5215,15 @@ dependencies = [ "http 1.4.0", "http-body 1.0.1", "http-body-util", - "hyper", - "hyper-rustls", + "hyper 1.9.0", + "hyper-rustls 0.27.9", "hyper-util", "js-sys", "log", "percent-encoding", "pin-project-lite", "quinn", - "rustls", + "rustls 0.23.38", "rustls-native-certs", "rustls-pki-types", "serde", @@ -4966,7 +5231,7 @@ dependencies = [ "serde_urlencoded", "sync_wrapper", "tokio", - "tokio-rustls", + "tokio-rustls 0.26.4", "tower 0.5.3", "tower-http 0.6.8", "tower-service", @@ -4990,15 +5255,15 @@ dependencies = [ "http 1.4.0", "http-body 1.0.1", "http-body-util", - "hyper", - "hyper-rustls", + "hyper 1.9.0", + "hyper-rustls 0.27.9", "hyper-util", "js-sys", "log", "percent-encoding", "pin-project-lite", "quinn", - "rustls", + "rustls 0.23.38", "rustls-pki-types", "rustls-platform-verifier", "serde", @@ -5006,7 +5271,7 @@ dependencies = [ "serde_urlencoded", "sync_wrapper", "tokio", - "tokio-rustls", + "tokio-rustls 0.26.4", "tokio-util", "tower 0.5.3", "tower-http 0.6.8", @@ -5242,6 +5507,18 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "rustls" +version = "0.21.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f56a14d1f48b391359b22f731fd4bd7e43c97f3c50eee276f3aa09c94784d3e" +dependencies = [ + "log", + "ring", + "rustls-webpki 0.101.7", + "sct", +] + [[package]] name = "rustls" version = "0.23.38" @@ -5253,7 +5530,7 @@ dependencies = [ "once_cell", "ring", "rustls-pki-types", - "rustls-webpki", + "rustls-webpki 0.103.13", "subtle", "zeroize", ] @@ -5300,10 +5577,10 @@ dependencies = [ "jni", "log", "once_cell", - "rustls", + "rustls 0.23.38", "rustls-native-certs", "rustls-platform-verifier-android", - "rustls-webpki", + "rustls-webpki 0.103.13", "security-framework", "security-framework-sys", "webpki-root-certs", @@ -5316,6 +5593,16 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f87165f0995f63a9fbeea62b64d10b4d9d8e78ec6d7d51fb2125fda7bb36788f" +[[package]] +name = "rustls-webpki" +version = "0.101.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b6275d1ee7a1cd780b64aca7726599a1dbc893b1e64144529e55c3c2f745765" +dependencies = [ + "ring", + "untrusted 0.9.0", +] + [[package]] name = "rustls-webpki" version = "0.103.13" @@ -5408,6 +5695,16 @@ dependencies = [ "sha2 0.10.9", ] +[[package]] +name = "sct" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da046153aa2352493d6cb7da4b6e5c0c057d8a1d0a9aa8560baffdd945acd414" +dependencies = [ + "ring", + "untrusted 0.9.0", +] + [[package]] name = "sec1" version = "0.7.3" @@ -5777,6 +6074,16 @@ dependencies = [ "serde", ] +[[package]] +name = "socket2" +version = "0.5.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e22376abed350d73dd1cd119b57ffccad95b4e585a7cda43e286245ce23c0678" +dependencies = [ + "libc", + "windows-sys 0.52.0", +] + [[package]] name = "socket2" version = "0.6.3" @@ -5880,7 +6187,7 @@ dependencies = [ "memchr", "once_cell", "percent-encoding", - "rustls", + "rustls 0.23.38", "serde", "serde_json", "sha2 0.10.9", @@ -6441,7 +6748,7 @@ dependencies = [ "parking_lot", "pin-project-lite", "signal-hook-registry", - "socket2", + "socket2 0.6.3", "tokio-macros", "windows-sys 0.61.2", ] @@ -6457,13 +6764,23 @@ dependencies = [ "syn 2.0.117", ] +[[package]] +name = "tokio-rustls" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c28327cf380ac148141087fbfb9de9d7bd4e84ab5d2c28fbc911d753de8a7081" +dependencies = [ + "rustls 0.21.12", + "tokio", +] + [[package]] name = "tokio-rustls" version = "0.26.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1729aa945f29d91ba541258c8df89027d5792d85a8841fb65e8bf0f4ede4ef61" dependencies = [ - "rustls", + "rustls 0.23.38", "tokio", ] @@ -6486,11 +6803,11 @@ checksum = "7a9daff607c6d2bf6c16fd681ccb7eecc83e4e2cdc1ca067ffaadfca5de7f084" dependencies = [ "futures-util", "log", - "rustls", + "rustls 0.23.38", "rustls-native-certs", "rustls-pki-types", "tokio", - "tokio-rustls", + "tokio-rustls 0.26.4", "tungstenite 0.26.2", ] @@ -6571,20 +6888,20 @@ dependencies = [ "axum", "base64 0.22.1", "bytes", - "h2", + "h2 0.4.13", "http 1.4.0", "http-body 1.0.1", "http-body-util", - "hyper", + "hyper 1.9.0", "hyper-timeout", "hyper-util", "percent-encoding", "pin-project", "rustls-native-certs", - "socket2", + "socket2 0.6.3", "sync_wrapper", "tokio", - "tokio-rustls", + "tokio-rustls 0.26.4", "tokio-stream", "tower 0.5.3", "tower-layer", @@ -6836,7 +7153,7 @@ dependencies = [ "httparse", "log", "rand 0.9.4", - "rustls", + "rustls 0.23.38", "rustls-pki-types", "sha1 0.10.6", "thiserror 2.0.18", @@ -6992,6 +7309,12 @@ dependencies = [ "serde_derive", ] +[[package]] +name = "urlencoding" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "daf8dba3b7eb870caf1ddeed7bc9d2a049f3cfdfae7cb521b087cc33ae4c49da" + [[package]] name = "utf-8" version = "0.7.6" @@ -7712,7 +8035,7 @@ dependencies = [ "futures", "http 1.4.0", "http-body-util", - "hyper", + "hyper 1.9.0", "hyper-util", "log", "once_cell", @@ -7850,6 +8173,12 @@ dependencies = [ "rustix 1.1.4", ] +[[package]] +name = "xmlparser" +version = "0.13.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66fee0b777b0f5ac1c69bb06d361268faafa61cd4682ae064a171c16c433e9e4" + [[package]] name = "xterm-color" version = "1.0.2" diff --git a/Cargo.toml b/Cargo.toml index 184c9aa398..84e6d1b963 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -79,6 +79,10 @@ tower-mcp-types = "0.12.0" # HTTP client reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls-native-roots"] } +# AWS SDK +aws-config = { version = "1", default-features = false, features = ["rustls", "rt-tokio", "behavior-version-latest"] } +aws-sdk-sts = { version = "1", default-features = false, features = ["rustls", "rt-tokio", "behavior-version-latest"] } + # WebSocket tokio-tungstenite = { version = "0.26", features = ["rustls-tls-native-roots"] } diff --git a/architecture/gateway.md b/architecture/gateway.md index 99a8420303..733ce68c25 100644 --- a/architecture/gateway.md +++ b/architecture/gateway.md @@ -259,7 +259,10 @@ state, SSH sessions, policy revisions, settings, inference configuration, and deployment records. Provider refresh material is stored as a separate object scoped to the provider instance through `objects.scope`; the provider record keeps only the current injectable credential values and optional per-credential -expiry timestamps. +expiry timestamps. A refresh normally mints one credential, but a strategy may +co-mint several (AWS STS mints the access key, secret key, and session token in +one call); the refresh state pins the resolved set of env keys it owns so +collision checks reserve all of them before the first mint. ### Optimistic Concurrency (CAS) diff --git a/architecture/security-policy.md b/architecture/security-policy.md index c4eaa2328a..10a8400fb9 100644 --- a/architecture/security-policy.md +++ b/architecture/security-policy.md @@ -46,18 +46,21 @@ request is denied. ## Host Wildcards Network endpoint `host` patterns accept a `*` wildcard inside the first DNS -label only. The OPA runtime matches with a `.` label boundary, so a wildcard -never spans dots. The validator enforces the same boundary so that policy load -fails fast instead of silently mismatching at the proxy. +label and as an entire middle DNS label. The OPA runtime matches with a `.` +label boundary, so a wildcard never spans dots. The validator enforces the same +boundary so that policy load fails fast instead of silently mismatching at the +proxy. | Pattern | Accepted | Example match | Notes | |---|---|---|---| | `*.example.com` | Yes | `api.example.com` | Single first label of any value. | | `**.example.com` | Yes | `a.b.example.com` | Recursive wildcard as the entire first label. | | `*-aiplatform.googleapis.com` | Yes | `us-central1-aiplatform.googleapis.com` | Intra-label wildcard inside the first DNS label. | +| `*.s3.*.amazonaws.com` | Yes | `bucket.s3.us-east-1.amazonaws.com` | Middle-label `*` matches exactly one DNS label. | | `*` or `**` | No | — | Matches every host. | | `*.com`, `**.com` | No | — | TLD wildcards (`labels <= 2`). | -| `foo.*.example.com` | No | — | Wildcard outside the first DNS label. | +| `foo.us-*.example.com` | No | — | Partial middle-label wildcards are not allowed. | +| `foo.**.example.com` | No | — | Recursive wildcard outside the first label is not allowed. | | `foo**.example.com` | No | — | Recursive `**` mixed inside a label; allowed only as the entire first label. | Validation rejects the disallowed patterns at policy load time with a message diff --git a/crates/openshell-cli/src/main.rs b/crates/openshell-cli/src/main.rs index 07b302a027..3e38af3dce 100644 --- a/crates/openshell-cli/src/main.rs +++ b/crates/openshell-cli/src/main.rs @@ -692,6 +692,7 @@ enum CliProviderRefreshStrategy { Oauth2RefreshToken, Oauth2ClientCredentials, GoogleServiceAccountJwt, + AwsStsAssumeRole, } impl CliProviderRefreshStrategy { @@ -700,6 +701,7 @@ impl CliProviderRefreshStrategy { Self::Oauth2RefreshToken => "oauth2_refresh_token", Self::Oauth2ClientCredentials => "oauth2_client_credentials", Self::GoogleServiceAccountJwt => "google_service_account_jwt", + Self::AwsStsAssumeRole => "aws_sts_assume_role", } } } diff --git a/crates/openshell-cli/src/run.rs b/crates/openshell-cli/src/run.rs index 924edf6f3c..0793228f64 100644 --- a/crates/openshell-cli/src/run.rs +++ b/crates/openshell-cli/src/run.rs @@ -5634,6 +5634,7 @@ fn provider_refresh_strategy(strategy: &str) -> Result { Ok(ProviderCredentialRefreshStrategy::GoogleServiceAccountJwt) } + "aws_sts_assume_role" => Ok(ProviderCredentialRefreshStrategy::AwsStsAssumeRole), _ => Err(miette!("unsupported provider refresh strategy: {strategy}")), } } @@ -5686,6 +5687,7 @@ fn provider_refresh_strategy_name(strategy: ProviderCredentialRefreshStrategy) - ProviderCredentialRefreshStrategy::Oauth2RefreshToken => "oauth2_refresh_token", ProviderCredentialRefreshStrategy::Oauth2ClientCredentials => "oauth2_client_credentials", ProviderCredentialRefreshStrategy::GoogleServiceAccountJwt => "google_service_account_jwt", + ProviderCredentialRefreshStrategy::AwsStsAssumeRole => "aws_sts_assume_role", ProviderCredentialRefreshStrategy::Unspecified => "unspecified", } } diff --git a/crates/openshell-policy/src/lib.rs b/crates/openshell-policy/src/lib.rs index f1721146ed..8caf7de3ac 100644 --- a/crates/openshell-policy/src/lib.rs +++ b/crates/openshell-policy/src/lib.rs @@ -1109,6 +1109,8 @@ pub enum PolicyViolation { TooManyPaths { count: usize }, /// A network endpoint uses a TLD wildcard (e.g. `*.com`). TldWildcard { policy_name: String, host: String }, + /// A network endpoint uses a wildcard shape that does not match runtime semantics. + InvalidHostWildcard { policy_name: String, host: String }, /// `credential_signing` is set but `signing_service` is missing. MissingSigningService { policy_name: String, host: String }, /// `credential_signing` has an unrecognized value. @@ -1158,6 +1160,14 @@ impl fmt::Display for PolicyViolation { use subdomain wildcards like '*.example.com' instead" ) } + Self::InvalidHostWildcard { policy_name, host } => { + write!( + f, + "network policy '{policy_name}': invalid host wildcard '{host}'; \ + middle DNS label wildcards must be the entire label '*' and recursive '**' \ + is only allowed as the entire first label" + ) + } Self::MissingSigningService { policy_name, host } => { write!( f, @@ -1288,6 +1298,12 @@ pub fn validate_sandbox_policy( }); } } + if host_wildcard_shape_invalid(&ep.host) { + violations.push(PolicyViolation::InvalidHostWildcard { + policy_name: name.clone(), + host: ep.host.clone(), + }); + } if !ep.credential_signing.is_empty() && !matches!( ep.credential_signing.as_str(), @@ -1322,6 +1338,25 @@ pub fn validate_sandbox_policy( } } +fn host_wildcard_shape_invalid(host: &str) -> bool { + if host == "*" || host == "**" { + return true; + } + if !host.contains('*') { + return false; + } + let labels: Vec<&str> = host.split('.').collect(); + let first_label = labels.first().copied().unwrap_or_default(); + if first_label.contains("**") && first_label != "**" { + return true; + } + labels + .iter() + .skip(1) + .copied() + .any(|label| label.contains("**") || (label.contains('*') && label != "*")) +} + /// Truncate a string for safe inclusion in error messages. fn truncate_for_display(s: &str) -> String { if s.len() <= 80 { @@ -1848,6 +1883,33 @@ network_policies: ); } + #[test] + fn validate_rejects_all_host_star_wildcards() { + for host in ["*", "**"] { + let mut policy = restrictive_default_policy(); + policy.network_policies.insert( + "bad".into(), + NetworkPolicyRule { + name: "bad-rule".into(), + endpoints: vec![NetworkEndpoint { + host: host.into(), + port: 443, + ..Default::default() + }], + ..Default::default() + }, + ); + + let violations = validate_sandbox_policy(&policy).unwrap_err(); + assert!( + violations + .iter() + .any(|v| matches!(v, PolicyViolation::InvalidHostWildcard { .. })), + "expected bare host wildcard {host:?} to be rejected, got {violations:?}" + ); + } + } + #[test] fn validate_accepts_subdomain_wildcard() { let mut policy = restrictive_default_policy(); @@ -1866,6 +1928,47 @@ network_policies: assert!(validate_sandbox_policy(&policy).is_ok()); } + #[test] + fn validate_accepts_middle_label_star_wildcard() { + let mut policy = restrictive_default_policy(); + policy.network_policies.insert( + "ok".into(), + NetworkPolicyRule { + name: "ok-rule".into(), + endpoints: vec![NetworkEndpoint { + host: "*.s3.*.amazonaws.com".into(), + port: 443, + ..Default::default() + }], + ..Default::default() + }, + ); + assert!(validate_sandbox_policy(&policy).is_ok()); + } + + #[test] + fn validate_rejects_partial_middle_label_wildcard() { + let mut policy = restrictive_default_policy(); + policy.network_policies.insert( + "bad".into(), + NetworkPolicyRule { + name: "bad-rule".into(), + endpoints: vec![NetworkEndpoint { + host: "*.s3.us-*.amazonaws.com".into(), + port: 443, + ..Default::default() + }], + ..Default::default() + }, + ); + let violations = validate_sandbox_policy(&policy).unwrap_err(); + assert!( + violations + .iter() + .any(|v| matches!(v, PolicyViolation::InvalidHostWildcard { .. })) + ); + } + #[test] fn validate_accepts_explicit_domain() { let mut policy = restrictive_default_policy(); diff --git a/crates/openshell-prover/src/credentials.rs b/crates/openshell-prover/src/credentials.rs index 586d0fbbf9..6c9a1a74f3 100644 --- a/crates/openshell-prover/src/credentials.rs +++ b/crates/openshell-prover/src/credentials.rs @@ -186,26 +186,39 @@ fn host_pattern_covers(pattern: &str, host: &str) -> bool { return false; }; + // A leading `**` matches one or more leading labels; the remaining labels + // match the tail of the host label-for-label, mirroring the runtime. if first_pattern_label == "**" { let suffix = &pattern_labels[1..]; - let host_suffix = host_labels - .len() - .checked_sub(suffix.len()) - .map(|start| &host_labels[start..]); - return !suffix.is_empty() - && host_labels.len() > suffix.len() - && matches!(host_suffix, Some(host_suffix) if host_suffix == suffix); + if suffix.is_empty() || host_labels.len() <= suffix.len() { + return false; + } + let start = host_labels.len() - suffix.len(); + return labels_match(suffix, &host_labels[start..]); } - if !first_pattern_label.contains('*') { - return false; - } + // Otherwise the pattern matches exactly one label per position. A `*` (or a + // partial `*` glob) matches a single label, literal labels must be equal, and + // wildcards may appear in any label — not just the first — to match the + // runtime's whole-middle-label wildcards (e.g. `*.s3.*.amazonaws.com`). + labels_match(&pattern_labels, &host_labels) +} - // Runtime host wildcards only apply in the first DNS label. Wildcards in - // later labels are not treated as policy globs here. +/// Match `pattern_labels` against `host_labels` positionally: equal label counts, +/// each `*`-bearing pattern label matched as a single-label glob and every other +/// label compared literally. +fn labels_match(pattern_labels: &[&str], host_labels: &[&str]) -> bool { pattern_labels.len() == host_labels.len() - && pattern_labels[1..] == host_labels[1..] - && wildcard_label_matches(first_pattern_label, host_labels[0]) + && pattern_labels + .iter() + .zip(host_labels) + .all(|(pattern, host)| { + if pattern.contains('*') { + wildcard_label_matches(pattern, host) + } else { + pattern == host + } + }) } fn wildcard_label_matches(pattern: &str, label: &str) -> bool { @@ -419,10 +432,38 @@ mod tests { "api-*.github.com", "uploads.github.com" )); - assert!(!host_patterns_overlap( + } + + #[test] + fn host_patterns_overlap_matches_whole_middle_label_wildcard() { + // A `*` matches exactly one label in any position, mirroring the runtime + // (e.g. the aws-s3 profile's `*.s3.*.amazonaws.com`). + assert!(host_patterns_overlap( "api.*.github.com", "api.v3.github.com" )); + assert!(host_patterns_overlap( + "*.s3.*.amazonaws.com", + "bucket.s3.us-east-1.amazonaws.com" + )); + assert!(host_patterns_overlap( + "s3.*.amazonaws.com", + "s3.eu-west-1.amazonaws.com" + )); + // A single `*` label matches exactly one label — not zero, not several. + assert!(!host_patterns_overlap( + "s3.*.amazonaws.com", + "s3.amazonaws.com" + )); + assert!(!host_patterns_overlap( + "*.s3.*.amazonaws.com", + "bucket.s3.dualstack.us-east-1.amazonaws.com" + )); + // A literal middle label must still match literally. + assert!(!host_patterns_overlap( + "api.*.github.com", + "api.v3.gitlab.com" + )); } #[test] diff --git a/crates/openshell-providers/src/lib.rs b/crates/openshell-providers/src/lib.rs index 1d78fe3612..fabe1a5bed 100644 --- a/crates/openshell-providers/src/lib.rs +++ b/crates/openshell-providers/src/lib.rs @@ -19,8 +19,9 @@ pub use context::{DiscoveryContext, RealDiscoveryContext}; pub use discovery::{discover_from_profile, discover_with_spec}; pub use profiles::{ CredentialRefreshProfile, ProfileError, ProfileValidationDiagnostic, ProviderTypeProfile, - builtin_profiles, normalize_profile_id, parse_profile_json, parse_profile_yaml, - profile_to_json, profile_to_yaml, profiles_to_json, profiles_to_yaml, validate_profile_set, + builtin_profiles, is_gateway_mintable_strategy, normalize_profile_id, parse_profile_json, + parse_profile_yaml, profile_to_json, profile_to_yaml, profiles_to_json, profiles_to_yaml, + strategy_output_env_key, strategy_output_spec, strategy_primary_env_key, validate_profile_set, }; #[derive(Debug, thiserror::Error)] diff --git a/crates/openshell-providers/src/profiles.rs b/crates/openshell-providers/src/profiles.rs index 62809138cd..c3441de533 100644 --- a/crates/openshell-providers/src/profiles.rs +++ b/crates/openshell-providers/src/profiles.rs @@ -8,8 +8,9 @@ use openshell_core::proto::{ GraphqlOperation, L7Allow, L7DenyRule, L7QueryMatcher, L7Rule, McpOptions, NetworkBinary, NetworkEndpoint, NetworkPolicyRule, ProviderCredentialRefresh, - ProviderCredentialRefreshMaterial, ProviderCredentialRefreshStrategy, ProviderProfile, - ProviderProfileCategory, ProviderProfileCredential, ProviderProfileDiscovery, + ProviderCredentialRefreshMaterial, ProviderCredentialRefreshOutput, + ProviderCredentialRefreshStrategy, ProviderProfile, ProviderProfileCategory, + ProviderProfileCredential, ProviderProfileDiscovery, }; use openshell_core::secrets::uses_reserved_revision_namespace; use serde::ser::SerializeStruct; @@ -21,7 +22,9 @@ use std::sync::OnceLock; const PATH_TEMPLATE_CREDENTIAL_PLACEHOLDER: &str = "{credential}"; const BUILT_IN_PROFILE_YAMLS: &[&str] = &[ + include_str!("../../../providers/aws.yaml"), include_str!("../../../providers/aws-bedrock.yaml"), + include_str!("../../../providers/aws-s3.yaml"), include_str!("../../../providers/claude-code.yaml"), include_str!("../../../providers/codex.yaml"), include_str!("../../../providers/copilot.yaml"), @@ -147,6 +150,11 @@ pub struct CredentialRefreshProfile { pub max_lifetime_seconds: i64, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub material: Vec, + /// Additional credentials this refresh mints beyond its primary credential. + /// Each entry maps a strategy-defined semantic output id to a sibling + /// credential whose `env_vars` receive the minted value. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub additional_outputs: Vec, } #[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)] @@ -160,6 +168,14 @@ pub struct CredentialRefreshMaterialProfile { pub secret: bool, } +#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)] +pub struct CredentialRefreshOutputProfile { + /// Strategy-defined semantic output id (e.g. `session_token`). + pub output: String, + /// Sibling credential name whose `env_vars` receive this output. + pub credential: String, +} + #[derive(Debug, Clone, Default, Deserialize, Serialize, PartialEq, Eq)] pub struct DiscoveryProfile { #[serde(default, skip_serializing_if = "Vec::is_empty")] @@ -383,12 +399,15 @@ impl ProviderTypeProfile { /// Empty provider creation is allowed when at least one credential can be /// resolved at runtime, and every required credential can be resolved at /// runtime. Runtime-resolvable credentials are either gateway-mintable - /// refresh credentials or sandbox-side dynamic token grants. + /// refresh credentials, sandbox-side dynamic token grants, or additional + /// outputs co-minted by another credential's gateway-mintable refresh. #[must_use] pub fn allows_empty_provider_credentials(&self) -> bool { + let co_minted = self.co_minted_credential_names(); let mut has_runtime_resolvable_credential = false; for credential in &self.credentials { - let is_runtime_resolvable = credential.is_runtime_resolvable(); + let is_runtime_resolvable = + credential.is_runtime_resolvable() || co_minted.contains(credential.name.as_str()); if credential.required && !is_runtime_resolvable { return false; } @@ -397,6 +416,54 @@ impl ProviderTypeProfile { has_runtime_resolvable_credential } + /// Names of credentials produced as `additional_outputs` of a + /// gateway-mintable refresh on some other credential. + fn co_minted_credential_names(&self) -> HashSet<&str> { + self.credentials + .iter() + .filter_map(|credential| credential.refresh.as_ref()) + .filter(|refresh| refresh.is_gateway_mintable()) + .flat_map(|refresh| refresh.additional_outputs.iter()) + .map(|output| output.credential.as_str()) + .collect() + } + + /// For the credential resolved by `credential_key` (matched by name or env + /// var) that carries a refresh with `additional_outputs`, resolve each + /// output to the concrete env key of its target credential. Returns a map + /// of semantic output id -> env key (empty when there is no such refresh or + /// no additional outputs). Skips outputs whose target credential is missing + /// or does not declare exactly one env var; `validate_profile_set` reports + /// those as errors. + #[must_use] + pub fn resolved_additional_output_keys(&self, credential_key: &str) -> HashMap { + let Some(refresh) = self + .credentials + .iter() + .find(|credential| { + credential.name == credential_key + || credential.env_vars.iter().any(|env| env == credential_key) + }) + .and_then(|credential| credential.refresh.as_ref()) + else { + return HashMap::new(); + }; + refresh + .additional_outputs + .iter() + .filter_map(|output| { + let target = self + .credentials + .iter() + .find(|credential| credential.name == output.credential)?; + let [env_key] = target.env_vars.as_slice() else { + return None; + }; + Some((output.output.clone(), env_key.clone())) + }) + .collect() + } + /// Returns the credential suitable for `--from-gcloud-adc` bootstrap, if any. /// /// A credential qualifies when its refresh strategy is `Oauth2RefreshToken` @@ -478,12 +545,73 @@ impl CredentialProfile { impl CredentialRefreshProfile { #[must_use] pub fn is_gateway_mintable(&self) -> bool { - matches!( - self.strategy, - ProviderCredentialRefreshStrategy::Oauth2RefreshToken - | ProviderCredentialRefreshStrategy::Oauth2ClientCredentials - | ProviderCredentialRefreshStrategy::GoogleServiceAccountJwt - ) + is_gateway_mintable_strategy(self.strategy) + } +} + +/// Whether the gateway can mint credentials for this refresh strategy (as +/// opposed to strategies resolved elsewhere, e.g. `Static`/`External`). +/// +/// Single source of truth shared with `openshell-server`; keep in sync with the +/// dispatch in `provider_refresh::mint_credential`. +#[must_use] +pub fn is_gateway_mintable_strategy(strategy: ProviderCredentialRefreshStrategy) -> bool { + matches!( + strategy, + ProviderCredentialRefreshStrategy::Oauth2RefreshToken + | ProviderCredentialRefreshStrategy::Oauth2ClientCredentials + | ProviderCredentialRefreshStrategy::GoogleServiceAccountJwt + | ProviderCredentialRefreshStrategy::AwsStsAssumeRole + ) +} + +/// Semantic output ids a refresh strategy can produce **in addition** to its +/// primary credential, split into required and optional. +/// +/// Drives `additional_outputs` validation. Strategies not listed here produce +/// only a single (primary) credential and reject any `additional_outputs`. +#[must_use] +pub fn strategy_output_spec( + strategy: ProviderCredentialRefreshStrategy, +) -> (&'static [&'static str], &'static [&'static str]) { + match strategy { + ProviderCredentialRefreshStrategy::AwsStsAssumeRole => { + (&["secret_access_key", "session_token"], &[]) + } + _ => (&[], &[]), + } +} + +/// Expected primary env key for strategies that constrain it, or `None` when the +/// strategy accepts any caller-chosen primary key. +/// +/// AWS `SigV4` signing looks up `AWS_ACCESS_KEY_ID` by name, so STS pins the +/// primary key. +#[must_use] +pub fn strategy_primary_env_key( + strategy: ProviderCredentialRefreshStrategy, +) -> Option<&'static str> { + match strategy { + ProviderCredentialRefreshStrategy::AwsStsAssumeRole => Some("AWS_ACCESS_KEY_ID"), + _ => None, + } +} + +/// Expected concrete env key for a given strategy output, when the strategy +/// constrains it (the `SigV4` signer resolves these by name). +#[must_use] +pub fn strategy_output_env_key( + strategy: ProviderCredentialRefreshStrategy, + output: &str, +) -> Option<&'static str> { + match (strategy, output) { + (ProviderCredentialRefreshStrategy::AwsStsAssumeRole, "secret_access_key") => { + Some("AWS_SECRET_ACCESS_KEY") + } + (ProviderCredentialRefreshStrategy::AwsStsAssumeRole, "session_token") => { + Some("AWS_SESSION_TOKEN") + } + _ => None, } } @@ -643,6 +771,7 @@ pub fn provider_refresh_strategy_from_yaml(raw: &str) -> Option { Some(ProviderCredentialRefreshStrategy::GoogleServiceAccountJwt) } + "aws_sts_assume_role" => Some(ProviderCredentialRefreshStrategy::AwsStsAssumeRole), _ => None, } } @@ -657,6 +786,7 @@ pub fn provider_refresh_strategy_to_yaml( ProviderCredentialRefreshStrategy::Oauth2RefreshToken => "oauth2_refresh_token", ProviderCredentialRefreshStrategy::Oauth2ClientCredentials => "oauth2_client_credentials", ProviderCredentialRefreshStrategy::GoogleServiceAccountJwt => "google_service_account_jwt", + ProviderCredentialRefreshStrategy::AwsStsAssumeRole => "aws_sts_assume_role", ProviderCredentialRefreshStrategy::Unspecified => "unspecified", } } @@ -679,6 +809,14 @@ fn credential_refresh_from_proto(refresh: &ProviderCredentialRefresh) -> Credent secret: material.secret, }) .collect(), + additional_outputs: refresh + .additional_outputs + .iter() + .map(|output| CredentialRefreshOutputProfile { + output: output.output.clone(), + credential: output.credential.clone(), + }) + .collect(), } } @@ -699,6 +837,14 @@ fn credential_refresh_to_proto(refresh: &CredentialRefreshProfile) -> ProviderCr secret: material.secret, }) .collect(), + additional_outputs: refresh + .additional_outputs + .iter() + .map(|output| ProviderCredentialRefreshOutput { + output: output.output.clone(), + credential: output.credential.clone(), + }) + .collect(), } } @@ -1291,6 +1437,136 @@ pub fn validate_profile_set( )); } } + + let strategy_name = provider_refresh_strategy_to_yaml(refresh.strategy); + let (required_outputs, optional_outputs) = strategy_output_spec(refresh.strategy); + let known_outputs: HashSet<&str> = required_outputs + .iter() + .chain(optional_outputs.iter()) + .copied() + .collect(); + + if known_outputs.is_empty() && !refresh.additional_outputs.is_empty() { + diagnostics.push(ProfileValidationDiagnostic::error( + source, + profile_id, + "credentials.refresh.additional_outputs", + format!("strategy {strategy_name} does not support additional_outputs"), + )); + } + + let mut seen_outputs = HashSet::new(); + let mut mapped_required = HashSet::new(); + for output in &refresh.additional_outputs { + let output_id = output.output.trim(); + let cred_name = output.credential.trim(); + + if output_id.is_empty() { + diagnostics.push(ProfileValidationDiagnostic::error( + source, + profile_id, + "credentials.refresh.additional_outputs.output", + "refresh additional output id is required", + )); + continue; + } + if !seen_outputs.insert(output_id.to_string()) { + diagnostics.push(ProfileValidationDiagnostic::error( + source, + profile_id, + "credentials.refresh.additional_outputs.output", + format!("duplicate refresh additional output: {output_id}"), + )); + } + if known_outputs.contains(output_id) { + if required_outputs.contains(&output_id) { + mapped_required.insert(output_id.to_string()); + } + } else if !known_outputs.is_empty() { + diagnostics.push(ProfileValidationDiagnostic::error( + source, + profile_id, + "credentials.refresh.additional_outputs.output", + format!( + "strategy {strategy_name} does not produce output '{output_id}'" + ), + )); + } + + let Some(sibling) = profile.credentials.iter().find(|c| c.name == cred_name) + else { + diagnostics.push(ProfileValidationDiagnostic::error( + source, + profile_id, + "credentials.refresh.additional_outputs.credential", + format!( + "refresh additional output '{output_id}' references unknown credential '{cred_name}'" + ), + )); + continue; + }; + if sibling.refresh.is_some() { + diagnostics.push(ProfileValidationDiagnostic::error( + source, + profile_id, + "credentials.refresh.additional_outputs.credential", + format!( + "credential '{cred_name}' is a refresh output and must not declare its own refresh" + ), + )); + } + if sibling.env_vars.len() != 1 { + diagnostics.push(ProfileValidationDiagnostic::error( + source, + profile_id, + "credentials.refresh.additional_outputs.credential", + format!( + "refresh output credential '{cred_name}' must declare exactly one env var" + ), + )); + continue; + } + let resolved = sibling.env_vars[0].as_str(); + if let Some(expected) = strategy_output_env_key(refresh.strategy, output_id) + && resolved != expected + { + diagnostics.push(ProfileValidationDiagnostic::error( + source, + profile_id, + "credentials.refresh.additional_outputs.credential", + format!( + "refresh output '{output_id}' must map to env var {expected}, found {resolved}" + ), + )); + } + } + + for required in required_outputs { + if !mapped_required.contains(*required) { + diagnostics.push(ProfileValidationDiagnostic::error( + source, + profile_id, + "credentials.refresh.additional_outputs", + format!( + "strategy {strategy_name} requires additional output '{required}'" + ), + )); + } + } + + if let Some(expected_primary) = strategy_primary_env_key(refresh.strategy) + && (credential.env_vars.len() != 1 + || credential.env_vars[0] != expected_primary) + { + diagnostics.push(ProfileValidationDiagnostic::error( + source, + profile_id, + "credentials.env_vars", + format!( + "strategy {strategy_name} requires primary credential to map to env var {expected_primary}" + ), + )); + } } if let Some(token_grant) = credential.token_grant.as_ref() @@ -2731,4 +3007,428 @@ endpoints: assert!(matches!(err, ProfileError::InvalidEndpoint { id, .. } if id == "bad-endpoint")); } + + #[test] + fn aws_sts_strategy_serde_roundtrip() { + use openshell_core::proto::ProviderCredentialRefreshStrategy; + assert_eq!( + super::provider_refresh_strategy_from_yaml("aws_sts_assume_role"), + Some(ProviderCredentialRefreshStrategy::AwsStsAssumeRole) + ); + assert_eq!( + super::provider_refresh_strategy_to_yaml( + ProviderCredentialRefreshStrategy::AwsStsAssumeRole + ), + "aws_sts_assume_role" + ); + } + + #[test] + fn aws_profile_parses_correctly() { + let aws = builtin_profile("aws"); + assert_eq!(aws.display_name, "AWS"); + assert_eq!(aws.credentials.len(), 3); + let access_key = aws + .credentials + .iter() + .find(|c| c.name == "access_key_id") + .unwrap(); + assert!(access_key.refresh.is_some()); + let refresh = access_key.refresh.as_ref().unwrap(); + assert_eq!( + refresh.strategy, + openshell_core::proto::ProviderCredentialRefreshStrategy::AwsStsAssumeRole + ); + assert!( + refresh + .material + .iter() + .any(|m| m.name == "role_arn" && m.required) + ); + } + + #[test] + fn aws_s3_profile_parses_with_endpoints() { + let aws_s3 = builtin_profile("aws-s3"); + assert_eq!(aws_s3.display_name, "AWS S3"); + assert!(!aws_s3.endpoints.is_empty()); + assert!( + !aws_s3 + .endpoints + .iter() + .any(|e| e.host == "**.amazonaws.com") + ); + assert!( + aws_s3 + .endpoints + .iter() + .any(|e| e.host == "*.s3.amazonaws.com") + ); + assert!( + aws_s3 + .endpoints + .iter() + .any(|e| e.host == "s3.amazonaws.com") + ); + assert!( + aws_s3 + .endpoints + .iter() + .any(|e| e.host == "*.s3.*.amazonaws.com") + ); + assert!( + aws_s3 + .endpoints + .iter() + .any(|e| e.host == "s3.*.amazonaws.com") + ); + assert!( + aws_s3 + .endpoints + .iter() + .any(|e| e.host == "*.s3.dualstack.*.amazonaws.com") + ); + assert!( + aws_s3 + .endpoints + .iter() + .any(|e| e.host == "s3.dualstack.*.amazonaws.com") + ); + } + + #[test] + fn aws_profile_declares_additional_outputs() { + for id in ["aws", "aws-s3"] { + let profile = builtin_profile(id); + let refresh = profile + .credentials + .iter() + .find(|c| c.name == "access_key_id") + .and_then(|c| c.refresh.as_ref()) + .expect("access_key_id refresh should exist"); + let outputs: Vec<(&str, &str)> = refresh + .additional_outputs + .iter() + .map(|o| (o.output.as_str(), o.credential.as_str())) + .collect(); + assert_eq!( + outputs, + vec![ + ("secret_access_key", "secret_access_key"), + ("session_token", "session_token"), + ], + "unexpected additional_outputs for {id}" + ); + } + } + + #[test] + fn aws_profiles_are_runtime_resolvable() { + // With AwsStsAssumeRole recognized as gateway-mintable, all three + // required credentials are runtime-resolvable, so `--runtime-credentials` + // (empty provider creation) is allowed. + for id in ["aws", "aws-s3"] { + let profile = builtin_profile(id); + assert!( + profile.allows_empty_provider_credentials(), + "{id} should allow empty provider credentials" + ); + } + } + + #[test] + fn is_gateway_mintable_strategy_includes_aws_sts() { + assert!(super::is_gateway_mintable_strategy( + openshell_core::proto::ProviderCredentialRefreshStrategy::AwsStsAssumeRole + )); + } + + #[test] + fn additional_outputs_round_trip_through_proto_and_yaml() { + let profile = parse_profile_yaml( + r" +id: aws-round-trip +display_name: AWS Round Trip +credentials: + - name: access_key_id + env_vars: [AWS_ACCESS_KEY_ID] + required: true + refresh: + strategy: aws_sts_assume_role + additional_outputs: + - output: secret_access_key + credential: secret_access_key + - output: session_token + credential: session_token + material: + - name: role_arn + required: true + - name: secret_access_key + env_vars: [AWS_SECRET_ACCESS_KEY] + required: true + - name: session_token + env_vars: [AWS_SESSION_TOKEN] + required: true +", + ) + .expect("profile should parse"); + + let from_proto = ProviderTypeProfile::from_proto(&profile.to_proto()); + assert_eq!( + from_proto.credentials[0].refresh, + profile.credentials[0].refresh + ); + + let exported = profile_to_yaml(&from_proto).expect("yaml"); + assert!(exported.contains("additional_outputs")); + assert!(exported.contains("session_token")); + let reparsed = parse_profile_yaml(&exported).expect("re-parse"); + assert_eq!( + reparsed.credentials[0].refresh, + profile.credentials[0].refresh + ); + } + + fn aws_output_profile(additional_outputs: &str, credentials_tail: &str) -> ProviderTypeProfile { + parse_profile_yaml(&format!( + r" +id: aws-outputs +display_name: AWS Outputs +credentials: + - name: access_key_id + env_vars: [AWS_ACCESS_KEY_ID] + required: true + refresh: + strategy: aws_sts_assume_role +{additional_outputs} + material: + - name: role_arn + required: true +{credentials_tail} +" + )) + .expect("profile should parse") + } + + const STANDARD_AWS_OUTPUT_TAIL: &str = " - name: secret_access_key + env_vars: [AWS_SECRET_ACCESS_KEY] + required: true + - name: session_token + env_vars: [AWS_SESSION_TOKEN] + required: true"; + + #[test] + fn validate_rejects_additional_output_unknown_credential() { + let profile = aws_output_profile( + " additional_outputs: + - output: secret_access_key + credential: nonexistent + - output: session_token + credential: session_token", + STANDARD_AWS_OUTPUT_TAIL, + ); + let diagnostics = validate_profile_set(&[("aws.yaml".to_string(), profile)]); + assert!( + diagnostics.iter().any(|d| d.field + == "credentials.refresh.additional_outputs.credential" + && d.message.contains("unknown credential 'nonexistent'")), + "diagnostics: {diagnostics:?}" + ); + } + + #[test] + fn validate_rejects_duplicate_additional_output() { + let profile = aws_output_profile( + " additional_outputs: + - output: secret_access_key + credential: secret_access_key + - output: secret_access_key + credential: secret_access_key + - output: session_token + credential: session_token", + STANDARD_AWS_OUTPUT_TAIL, + ); + let diagnostics = validate_profile_set(&[("aws.yaml".to_string(), profile)]); + assert!( + diagnostics + .iter() + .any(|d| d.message.contains("duplicate refresh additional output")), + "diagnostics: {diagnostics:?}" + ); + } + + #[test] + fn validate_rejects_unknown_output_for_strategy() { + let profile = aws_output_profile( + " additional_outputs: + - output: secret_access_key + credential: secret_access_key + - output: session_token + credential: session_token + - output: bogus + credential: session_token", + STANDARD_AWS_OUTPUT_TAIL, + ); + let diagnostics = validate_profile_set(&[("aws.yaml".to_string(), profile)]); + assert!( + diagnostics + .iter() + .any(|d| d.message.contains("does not produce output 'bogus'")), + "diagnostics: {diagnostics:?}" + ); + } + + #[test] + fn validate_rejects_missing_required_output() { + let profile = aws_output_profile( + " additional_outputs: + - output: secret_access_key + credential: secret_access_key", + STANDARD_AWS_OUTPUT_TAIL, + ); + let diagnostics = validate_profile_set(&[("aws.yaml".to_string(), profile)]); + assert!( + diagnostics.iter().any(|d| d + .message + .contains("requires additional output 'session_token'")), + "diagnostics: {diagnostics:?}" + ); + } + + #[test] + fn validate_rejects_output_credential_with_own_refresh() { + let tail = " - name: secret_access_key + env_vars: [AWS_SECRET_ACCESS_KEY] + required: true + refresh: + strategy: oauth2_client_credentials + - name: session_token + env_vars: [AWS_SESSION_TOKEN] + required: true"; + let profile = aws_output_profile( + " additional_outputs: + - output: secret_access_key + credential: secret_access_key + - output: session_token + credential: session_token", + tail, + ); + let diagnostics = validate_profile_set(&[("aws.yaml".to_string(), profile)]); + assert!( + diagnostics + .iter() + .any(|d| d.message.contains("must not declare its own refresh")), + "diagnostics: {diagnostics:?}" + ); + } + + #[test] + fn validate_rejects_nonstandard_aws_output_env_key() { + let tail = " - name: secret_access_key + env_vars: [WRONG_SECRET] + required: true + - name: session_token + env_vars: [AWS_SESSION_TOKEN] + required: true"; + let profile = aws_output_profile( + " additional_outputs: + - output: secret_access_key + credential: secret_access_key + - output: session_token + credential: session_token", + tail, + ); + let diagnostics = validate_profile_set(&[("aws.yaml".to_string(), profile)]); + assert!( + diagnostics.iter().any(|d| d + .message + .contains("must map to env var AWS_SECRET_ACCESS_KEY, found WRONG_SECRET")), + "diagnostics: {diagnostics:?}" + ); + } + + #[test] + fn validate_rejects_wrong_primary_env_key_for_aws_sts() { + let profile = parse_profile_yaml( + r" +id: aws-wrong-primary +display_name: AWS Wrong Primary +credentials: + - name: access_key_id + env_vars: [NOT_AWS_ACCESS_KEY_ID] + required: true + refresh: + strategy: aws_sts_assume_role + additional_outputs: + - output: secret_access_key + credential: secret_access_key + - output: session_token + credential: session_token + material: + - name: role_arn + required: true + - name: secret_access_key + env_vars: [AWS_SECRET_ACCESS_KEY] + required: true + - name: session_token + env_vars: [AWS_SESSION_TOKEN] + required: true +", + ) + .expect("profile should parse"); + let diagnostics = validate_profile_set(&[("aws.yaml".to_string(), profile)]); + assert!( + diagnostics.iter().any(|d| d + .message + .contains("requires primary credential to map to env var AWS_ACCESS_KEY_ID")), + "diagnostics: {diagnostics:?}" + ); + } + + #[test] + fn validate_rejects_additional_outputs_on_unsupported_strategy() { + let profile = parse_profile_yaml( + r" +id: oauth-with-outputs +display_name: OAuth With Outputs +credentials: + - name: access_token + env_vars: [ACCESS_TOKEN] + required: true + refresh: + strategy: oauth2_client_credentials + additional_outputs: + - output: extra + credential: other + - name: other + env_vars: [OTHER] + required: false +", + ) + .expect("profile should parse"); + let diagnostics = validate_profile_set(&[("oauth.yaml".to_string(), profile)]); + assert!( + diagnostics + .iter() + .any(|d| d.message.contains("does not support additional_outputs")), + "diagnostics: {diagnostics:?}" + ); + } + + #[test] + fn validate_accepts_standard_aws_additional_outputs() { + let profile = aws_output_profile( + " additional_outputs: + - output: secret_access_key + credential: secret_access_key + - output: session_token + credential: session_token", + STANDARD_AWS_OUTPUT_TAIL, + ); + let diagnostics = validate_profile_set(&[("aws.yaml".to_string(), profile)]); + assert!( + diagnostics.is_empty(), + "unexpected diagnostics: {diagnostics:?}" + ); + } } diff --git a/crates/openshell-server/Cargo.toml b/crates/openshell-server/Cargo.toml index c4fe7e8d0b..ca106a335f 100644 --- a/crates/openshell-server/Cargo.toml +++ b/crates/openshell-server/Cargo.toml @@ -81,6 +81,8 @@ toml = { workspace = true } tokio-stream = { workspace = true } sqlx = { workspace = true } reqwest = { workspace = true } +aws-config = { workspace = true } +aws-sdk-sts = { workspace = true } uuid = { workspace = true } hmac = "0.12" sha2 = { workspace = true } diff --git a/crates/openshell-server/src/grpc/policy.rs b/crates/openshell-server/src/grpc/policy.rs index 6fccf1eade..9a612f5e19 100644 --- a/crates/openshell-server/src/grpc/policy.rs +++ b/crates/openshell-server/src/grpc/policy.rs @@ -1481,7 +1481,7 @@ async fn profile_provider_policy_layers_with_catalog( Ok(layers) } -fn bool_setting_enabled(settings: &StoredSettings, key: &str) -> Result { +pub(super) fn bool_setting_enabled(settings: &StoredSettings, key: &str) -> Result { match settings.settings.get(key) { None => Ok(false), Some(StoredSettingValue::Bool(value)) => Ok(*value), @@ -3981,6 +3981,30 @@ pub(super) async fn load_global_settings(store: &Store) -> Result Result { + let global_settings = load_global_settings(store).await?; + bool_setting_enabled(&global_settings, key) +} + +/// Test helper: set a boolean global setting, loading current settings first so +/// the CAS write succeeds whether the record already exists or not. Available to +/// sibling test modules without exposing the private `StoredSettings` type. +#[cfg(test)] +pub async fn set_global_bool_setting_for_test( + store: &Store, + key: &str, + value: bool, +) -> Result<(), Status> { + let mut settings = load_global_settings(store).await?; + settings + .settings + .insert(key.to_string(), StoredSettingValue::Bool(value)); + save_global_settings(store, &settings).await +} + pub(super) async fn save_global_settings( store: &Store, settings: &StoredSettings, diff --git a/crates/openshell-server/src/grpc/provider.rs b/crates/openshell-server/src/grpc/provider.rs index aa4b3ab195..cae751b42a 100644 --- a/crates/openshell-server/src/grpc/provider.rs +++ b/crates/openshell-server/src/grpc/provider.rs @@ -1142,13 +1142,18 @@ async fn active_provider_environment_keys( ) -> Result, Status> { let mut keys = active_provider_credential_keys(provider, now_ms); if !provider.object_id().is_empty() { - keys.extend( + for state in crate::provider_refresh::list_refresh_states_for_provider(store, provider.object_id()) .await? - .into_iter() - .map(|state| state.credential_key) - .filter(|key| is_valid_env_key(key)), - ); + { + // The primary key plus every co-minted output key this refresh owns, + // so a configured-but-not-yet-minted refresh reserves all of them. + keys.extend( + std::iter::once(state.credential_key) + .chain(state.additional_output_keys.into_values()) + .filter(|key| is_valid_env_key(key)), + ); + } } keys.sort(); keys.dedup(); @@ -1218,7 +1223,8 @@ use openshell_core::proto::{ }; use openshell_providers::{ CredentialRefreshProfile, ProfileValidationDiagnostic, ProviderTypeProfile, - normalize_profile_id, normalize_provider_type, validate_profile_set, + normalize_profile_id, normalize_provider_type, strategy_output_env_key, strategy_output_spec, + strategy_primary_env_key, validate_profile_set, }; use std::sync::Arc; use tonic::{Request, Response}; @@ -1598,6 +1604,69 @@ fn provider_refresh_defaults( .and_then(|credential| credential.refresh.clone()) } +/// Resolve the env keys a refresh co-mints (beyond its primary credential) from +/// the provider's profile `additional_outputs`. Returns semantic output id -> +/// env key. Empty when the provider type has no profile or the credential +/// declares no additional outputs. +fn resolved_additional_output_keys( + catalog: &EffectiveProviderProfileCatalog, + provider: &Provider, + credential_key: &str, +) -> std::collections::HashMap { + let Some(profile) = get_provider_type_profile_with_catalog(catalog, &provider.r#type) else { + return std::collections::HashMap::new(); + }; + profile.resolved_additional_output_keys(credential_key) +} + +/// Validate that a strategy which pins canonical env keys (today only +/// `aws_sts_assume_role`) is configured against a matching profile binding. +/// +/// For such strategies the `SigV4` signer resolves credentials by fixed env +/// name, so a caller must not be able to configure the refresh on an arbitrary +/// credential key or on a provider whose profile does not declare it. This +/// requires: (1) a profile refresh declaration for `credential_key` whose +/// strategy matches, (2) `credential_key` equal to the canonical primary env +/// key, and (3) every required strategy output resolved to its canonical env key +/// via the profile's `additional_outputs`. Unconstrained strategies pass through. +fn validate_strategy_profile_binding( + strategy: ProviderCredentialRefreshStrategy, + credential_key: &str, + refresh_defaults: Option<&CredentialRefreshProfile>, + additional_output_keys: &std::collections::HashMap, +) -> Result<(), Status> { + let Some(expected_primary) = strategy_primary_env_key(strategy) else { + return Ok(()); + }; + let strategy_name = crate::provider_refresh::refresh_strategy_name(strategy as i32); + let refresh_defaults = refresh_defaults.ok_or_else(|| { + Status::failed_precondition(format!( + "strategy '{strategy_name}' requires a provider profile that declares this refresh on credential {expected_primary}" + )) + })?; + if refresh_defaults.strategy != strategy { + return Err(Status::failed_precondition(format!( + "provider profile declares strategy '{}' for {credential_key}, not '{strategy_name}'", + crate::provider_refresh::refresh_strategy_name(refresh_defaults.strategy as i32) + ))); + } + if credential_key != expected_primary { + return Err(Status::failed_precondition(format!( + "strategy '{strategy_name}' requires credential_key {expected_primary}, got {credential_key}" + ))); + } + let (required_outputs, _optional_outputs) = strategy_output_spec(strategy); + for output in required_outputs { + let expected_env = strategy_output_env_key(strategy, output).unwrap_or_default(); + if additional_output_keys.get(*output).map(String::as_str) != Some(expected_env) { + return Err(Status::failed_precondition(format!( + "strategy '{strategy_name}' requires profile additional output '{output}' bound to {expected_env}" + ))); + } + } + Ok(()) +} + fn validate_refresh_material( material: &std::collections::HashMap, refresh_defaults: Option<&CredentialRefreshProfile>, @@ -2035,6 +2104,18 @@ pub(super) async fn handle_configure_provider_refresh( crate::provider_refresh::refresh_strategy_name(strategy as i32) ))); } + if strategy == ProviderCredentialRefreshStrategy::AwsStsAssumeRole { + let global_settings = + crate::grpc::policy::load_global_settings(state.store.as_ref()).await?; + if !crate::grpc::policy::bool_setting_enabled( + &global_settings, + openshell_core::settings::PROVIDERS_V2_ENABLED_KEY, + )? { + return Err(Status::failed_precondition( + "aws_sts_assume_role requires providers_v2_enabled=true", + )); + } + } if request.material.len() > MAX_PROVIDER_CONFIG_ENTRIES { return Err(Status::invalid_argument(format!( "material exceeds maximum entries ({} > {MAX_PROVIDER_CONFIG_ENTRIES})", @@ -2082,6 +2163,42 @@ pub(super) async fn handle_configure_provider_refresh( "refresh token endpoints must be defined by the provider profile, not material", )); } + // The STS endpoint is always resolved from the region in production. Reject + // any caller-supplied override so an AWS-signed AssumeRole request cannot be + // redirected at an arbitrary service (CWE-918). Tests inject a mock endpoint + // through test-only code paths, not this boundary. + if request.material.contains_key("sts_endpoint_url") { + return Err(Status::invalid_argument( + "sts_endpoint_url material is not permitted", + )); + } + // Explicit AWS source credentials are all-or-nothing. Reject a partial pair + // early so a lone key can't later fall through to the gateway's ambient + // identity at mint time (CWE-20). + let has_source_access_key = request + .material + .get("aws_access_key_id") + .is_some_and(|value| !value.trim().is_empty()); + let has_source_secret_key = request + .material + .get("aws_secret_access_key") + .is_some_and(|value| !value.trim().is_empty()); + if has_source_access_key != has_source_secret_key { + return Err(Status::invalid_argument( + "aws_access_key_id and aws_secret_access_key must both be set or both omitted", + )); + } + // An optional session token supports temporary source credentials (SSO or a + // prior AssumeRole). It only makes sense alongside the source key pair. + let has_source_session_token = request + .material + .get("aws_session_token") + .is_some_and(|value| !value.trim().is_empty()); + if has_source_session_token && !has_source_access_key { + return Err(Status::invalid_argument( + "aws_session_token requires aws_access_key_id and aws_secret_access_key", + )); + } if request .expires_at_ms .is_some_and(|expires_at_ms| expires_at_ms < 0) @@ -2091,6 +2208,14 @@ pub(super) async fn handle_configure_provider_refresh( )); } + // Serialize the reserve-then-persist sequence against other configurations + // and sandbox mutations. The collision validation below and the refresh-state + // persist further down are otherwise separate steps: two concurrent + // configures of providers attached to the same sandbox could each pass + // validation before either persisted and both reserve the same key (CWE-362). + // This is the same guard sandbox create/attach and profile changes take. + let _sandbox_sync_guard = state.compute.sandbox_sync_guard().await; + let provider = state .store .get_message_by_name::(provider_name) @@ -2108,7 +2233,28 @@ pub(super) async fn handle_configure_provider_refresh( credential_key, ) .await?; + // Reserve every env key this refresh will co-mint (resolved from the + // profile's additional_outputs), not just the primary, so a + // configured-but-not-yet-minted refresh can't collide with another provider + // that later claims one of the derived keys. + let additional_output_keys = + resolved_additional_output_keys(&catalog, &provider, credential_key); + for additional_key in additional_output_keys.values() { + validate_provider_credential_key_available_for_attached_sandboxes_with_catalog( + state.store.as_ref(), + &catalog, + &provider, + additional_key, + ) + .await?; + } let refresh_defaults = provider_refresh_defaults(&catalog, &provider, credential_key); + validate_strategy_profile_binding( + strategy, + credential_key, + refresh_defaults.as_ref(), + &additional_output_keys, + )?; validate_refresh_material(&request.material, refresh_defaults.as_ref())?; let material_scopes = crate::provider_refresh::material_scopes(&request.material); let token_url = refresh_defaults @@ -2173,6 +2319,7 @@ pub(super) async fn handle_configure_provider_refresh( scopes, refresh_before_seconds, max_lifetime_seconds, + additional_output_keys, }, )?; if let Some(existing) = existing_refresh_state { @@ -2236,6 +2383,34 @@ pub(super) async fn handle_rotate_provider_credential( })) } +/// Remove the expiry for each key the refresh still owns — one whose stored +/// value equals the refresh's `expires_at_ms`. Independently updated expiries (no +/// longer matching) are left in place. +/// +/// This operates on `provider` in place so it can run inside a CAS closure +/// against the current stored provider. The equality check must see the latest +/// state, not a snapshot read earlier in the handler: a concurrent rotation or +/// provider update between the read and the write could otherwise be clobbered +/// by an unconditional zero (CWE-362). +fn clear_refresh_owned_expiries( + provider: &mut Provider, + refresh_expires_at_ms: i64, + owned_keys: &[String], +) { + if refresh_expires_at_ms <= 0 { + return; + } + for key in owned_keys { + if provider + .credential_expires_at_ms + .get(key) + .is_some_and(|expires_at_ms| *expires_at_ms == refresh_expires_at_ms) + { + provider.credential_expires_at_ms.remove(key); + } + } +} + pub(super) async fn handle_delete_provider_refresh( state: &Arc, request: Request, @@ -2268,38 +2443,30 @@ pub(super) async fn handle_delete_provider_refresh( ) .await?; - let refresh_owned_expiry = existing_refresh_state - .as_ref() - .is_some_and(|refresh_state| { - refresh_state.expires_at_ms > 0 - && provider - .credential_expires_at_ms - .get(credential_key) - .is_some_and(|expires_at_ms| *expires_at_ms == refresh_state.expires_at_ms) - }); - if refresh_owned_expiry { - let catalog = state - .provider_profile_sources - .snapshot_catalog(state.store.as_ref()) - .await?; - let updated = Provider { - metadata: Some(openshell_core::proto::datamodel::v1::ObjectMeta { - id: String::new(), - name: provider_name.to_string(), - created_at_ms: 0, - labels: std::collections::HashMap::new(), - resource_version: 0, - annotations: std::collections::HashMap::new(), - }), - r#type: String::new(), - credentials: std::collections::HashMap::new(), - config: std::collections::HashMap::new(), - credential_expires_at_ms: std::collections::HashMap::from([( - credential_key.to_string(), - 0, - )]), - }; - update_provider_record_with_catalog(state.store.as_ref(), &catalog, updated).await?; + // A refresh co-manages the expiry of its primary credential and every pinned + // additional output. Clear each expiry this refresh still owns, leaving + // independently updated ones in place. The equality check and removal run + // inside the CAS closure so they see the current stored provider — deciding + // from the snapshot read above would let a concurrent rotation or provider + // update land between the read and the write and then be clobbered (CWE-362). + if let Some(refresh_state) = existing_refresh_state + && refresh_state.expires_at_ms > 0 + { + let refresh_expires_at_ms = refresh_state.expires_at_ms; + let owned_keys: Vec = std::iter::once(credential_key.to_string()) + .chain(refresh_state.additional_output_keys.into_values()) + .collect(); + state + .store + .update_message_cas::(provider.object_id(), 0, |current| { + clear_refresh_owned_expiries(current, refresh_expires_at_ms, &owned_keys); + }) + .await + .map_err(|e| { + Status::internal(format!( + "clear refresh-owned credential expiries failed: {e}" + )) + })?; } Ok(Response::new(DeleteProviderRefreshResponse { @@ -3094,6 +3261,7 @@ mod tests { scopes: Vec::new(), refresh_before_seconds: 300, max_lifetime_seconds: 3600, + additional_outputs: Vec::new(), material: vec![ ProviderCredentialRefreshMaterial { name: "client_id".to_string(), @@ -3197,7 +3365,9 @@ mod tests { assert_eq!( ids, vec![ + "aws", "aws-bedrock", + "aws-s3", "claude-code", "codex", "copilot", @@ -3885,6 +4055,7 @@ mod tests { scopes: Vec::new(), refresh_before_seconds: 0, max_lifetime_seconds: 0, + additional_output_keys: HashMap::new(), }, ) .unwrap(); @@ -4075,6 +4246,170 @@ mod tests { ); } + #[tokio::test] + async fn delete_aws_sts_refresh_clears_all_pinned_output_expiries() { + use crate::grpc::policy::set_global_bool_setting_for_test; + + let state = test_server_state().await; + set_global_bool_setting_for_test( + state.store.as_ref(), + openshell_core::settings::PROVIDERS_V2_ENABLED_KEY, + true, + ) + .await + .unwrap(); + + create_provider_record( + state.store.as_ref(), + Provider { + metadata: Some(openshell_core::proto::datamodel::v1::ObjectMeta { + id: String::new(), + name: "aws-delete".to_string(), + created_at_ms: 0, + labels: HashMap::new(), + resource_version: 0, + annotations: HashMap::new(), + }), + r#type: "aws".to_string(), + credentials: HashMap::new(), + config: HashMap::new(), + credential_expires_at_ms: HashMap::new(), + }, + ) + .await + .unwrap(); + + let refresh_expires_at_ms = crate::persistence::current_time_ms() + 60_000; + handle_configure_provider_refresh( + &state, + Request::new(ConfigureProviderRefreshRequest { + provider: "aws-delete".to_string(), + credential_key: "AWS_ACCESS_KEY_ID".to_string(), + strategy: ProviderCredentialRefreshStrategy::AwsStsAssumeRole as i32, + material: HashMap::from([( + "role_arn".to_string(), + "arn:aws:iam::123456789012:role/Test".to_string(), + )]), + secret_material_keys: Vec::new(), + expires_at_ms: Some(refresh_expires_at_ms), + }), + ) + .await + .unwrap(); + + // Simulate a completed mint: the primary and secret share the refresh's + // expiry (refresh-owned), while the session token was independently + // updated to a later value that must survive the delete. + let independent_expires_at_ms = refresh_expires_at_ms + 120_000; + update_provider_record( + state.store.as_ref(), + Provider { + metadata: Some(openshell_core::proto::datamodel::v1::ObjectMeta { + id: String::new(), + name: "aws-delete".to_string(), + created_at_ms: 0, + labels: HashMap::new(), + resource_version: 0, + annotations: HashMap::new(), + }), + r#type: String::new(), + credentials: HashMap::new(), + config: HashMap::new(), + credential_expires_at_ms: HashMap::from([ + ("AWS_SECRET_ACCESS_KEY".to_string(), refresh_expires_at_ms), + ("AWS_SESSION_TOKEN".to_string(), independent_expires_at_ms), + ]), + }, + ) + .await + .unwrap(); + + handle_delete_provider_refresh( + &state, + Request::new(DeleteProviderRefreshRequest { + provider: "aws-delete".to_string(), + credential_key: "AWS_ACCESS_KEY_ID".to_string(), + }), + ) + .await + .unwrap(); + + let provider = state + .store + .get_message_by_name::("aws-delete") + .await + .unwrap() + .unwrap(); + // Refresh-owned expiries for the primary and secret are cleared. + assert!( + !provider + .credential_expires_at_ms + .contains_key("AWS_ACCESS_KEY_ID") + ); + assert!( + !provider + .credential_expires_at_ms + .contains_key("AWS_SECRET_ACCESS_KEY") + ); + // The independently updated session-token expiry is preserved. + assert_eq!( + provider.credential_expires_at_ms.get("AWS_SESSION_TOKEN"), + Some(&independent_expires_at_ms) + ); + } + + #[test] + fn clear_refresh_owned_expiries_preserves_concurrently_changed_expiry() { + // Regression for the delete-refresh TOCTOU: the clearing decision runs + // inside the CAS closure against the current provider. Simulate a + // concurrent rotation that updated AWS_SESSION_TOKEN's expiry after the + // handler's initial read but before its write — by the time the closure + // runs, that value no longer matches the deleted refresh's expiry and + // must survive, while the still-owned keys are cleared. + let refresh_expires_at_ms = 1_000_000; + let concurrently_changed = refresh_expires_at_ms + 500_000; + let mut provider = Provider { + metadata: Some(openshell_core::proto::datamodel::v1::ObjectMeta { + id: "p".to_string(), + name: "p".to_string(), + created_at_ms: 0, + labels: HashMap::new(), + resource_version: 0, + annotations: HashMap::new(), + }), + r#type: "aws".to_string(), + credentials: HashMap::new(), + config: HashMap::new(), + credential_expires_at_ms: HashMap::from([ + ("AWS_ACCESS_KEY_ID".to_string(), refresh_expires_at_ms), + ("AWS_SECRET_ACCESS_KEY".to_string(), refresh_expires_at_ms), + ("AWS_SESSION_TOKEN".to_string(), concurrently_changed), + ]), + }; + let owned_keys = vec![ + "AWS_ACCESS_KEY_ID".to_string(), + "AWS_SECRET_ACCESS_KEY".to_string(), + "AWS_SESSION_TOKEN".to_string(), + ]; + + clear_refresh_owned_expiries(&mut provider, refresh_expires_at_ms, &owned_keys); + + assert!( + !provider + .credential_expires_at_ms + .contains_key("AWS_ACCESS_KEY_ID") + ); + assert!( + !provider + .credential_expires_at_ms + .contains_key("AWS_SECRET_ACCESS_KEY") + ); + assert_eq!( + provider.credential_expires_at_ms.get("AWS_SESSION_TOKEN"), + Some(&concurrently_changed) + ); + } + #[tokio::test] async fn configure_provider_refresh_rejects_credential_key_collision_for_attached_sandbox() { let state = test_server_state().await; @@ -4568,6 +4903,7 @@ mod tests { &provider, "API_TOKEN", crate::provider_refresh::NewRefreshStateConfig { + additional_output_keys: HashMap::new(), strategy: ProviderCredentialRefreshStrategy::External, material: HashMap::from([( "endpoint".to_string(), @@ -4783,6 +5119,7 @@ mod tests { scopes: vec!["https://example.test/.default".to_string()], refresh_before_seconds: 300, max_lifetime_seconds: 3600, + additional_outputs: Vec::new(), material: vec![ ProviderCredentialRefreshMaterial { name: "client_id".to_string(), @@ -6269,6 +6606,909 @@ mod tests { assert_eq!(new_keys_count, 1); } + #[tokio::test] + async fn configure_aws_sts_requires_v2_enabled() { + let state = test_server_state().await; + create_provider_record( + state.store.as_ref(), + Provider { + metadata: Some(openshell_core::proto::datamodel::v1::ObjectMeta { + id: String::new(), + name: "my-aws".to_string(), + created_at_ms: 0, + labels: HashMap::new(), + resource_version: 0, + annotations: HashMap::new(), + }), + r#type: "aws".to_string(), + credentials: std::iter::once(( + "AWS_ACCESS_KEY_ID".to_string(), + "placeholder".to_string(), + )) + .collect(), + config: HashMap::new(), + credential_expires_at_ms: HashMap::new(), + }, + ) + .await + .unwrap(); + + let err = handle_configure_provider_refresh( + &state, + Request::new(ConfigureProviderRefreshRequest { + provider: "my-aws".to_string(), + credential_key: "AWS_ACCESS_KEY_ID".to_string(), + strategy: ProviderCredentialRefreshStrategy::AwsStsAssumeRole as i32, + material: HashMap::from([( + "role_arn".to_string(), + "arn:aws:iam::123456789012:role/Test".to_string(), + )]), + secret_material_keys: Vec::new(), + expires_at_ms: None, + }), + ) + .await + .unwrap_err(); + + assert_eq!(err.code(), Code::FailedPrecondition); + assert!(err.message().contains("providers_v2_enabled")); + } + + #[tokio::test] + async fn configure_aws_sts_succeeds_with_v2_enabled() { + use crate::grpc::StoredSettingValue; + use crate::grpc::StoredSettings; + use crate::grpc::policy::save_global_settings; + + let state = test_server_state().await; + + let global_settings = StoredSettings { + revision: 1, + settings: std::iter::once(( + openshell_core::settings::PROVIDERS_V2_ENABLED_KEY.to_string(), + StoredSettingValue::Bool(true), + )) + .collect(), + ..Default::default() + }; + save_global_settings(state.store.as_ref(), &global_settings) + .await + .unwrap(); + + create_provider_record( + state.store.as_ref(), + Provider { + metadata: Some(openshell_core::proto::datamodel::v1::ObjectMeta { + id: String::new(), + name: "my-aws-v2".to_string(), + created_at_ms: 0, + labels: HashMap::new(), + resource_version: 0, + annotations: HashMap::new(), + }), + r#type: "aws".to_string(), + credentials: std::iter::once(( + "AWS_ACCESS_KEY_ID".to_string(), + "placeholder".to_string(), + )) + .collect(), + config: HashMap::new(), + credential_expires_at_ms: HashMap::new(), + }, + ) + .await + .unwrap(); + + let response = handle_configure_provider_refresh( + &state, + Request::new(ConfigureProviderRefreshRequest { + provider: "my-aws-v2".to_string(), + credential_key: "AWS_ACCESS_KEY_ID".to_string(), + strategy: ProviderCredentialRefreshStrategy::AwsStsAssumeRole as i32, + material: HashMap::from([( + "role_arn".to_string(), + "arn:aws:iam::123456789012:role/Test".to_string(), + )]), + secret_material_keys: Vec::new(), + expires_at_ms: None, + }), + ) + .await + .unwrap() + .into_inner() + .status + .expect("status"); + + assert_eq!(response.credential_key, "AWS_ACCESS_KEY_ID"); + assert_eq!( + response.strategy, + ProviderCredentialRefreshStrategy::AwsStsAssumeRole as i32 + ); + } + + #[tokio::test] + async fn configure_aws_sts_rejects_endpoint_override_material() { + use crate::grpc::StoredSettingValue; + use crate::grpc::StoredSettings; + use crate::grpc::policy::save_global_settings; + + let state = test_server_state().await; + let global_settings = StoredSettings { + revision: 1, + settings: std::iter::once(( + openshell_core::settings::PROVIDERS_V2_ENABLED_KEY.to_string(), + StoredSettingValue::Bool(true), + )) + .collect(), + ..Default::default() + }; + save_global_settings(state.store.as_ref(), &global_settings) + .await + .unwrap(); + + create_provider_record( + state.store.as_ref(), + Provider { + metadata: Some(openshell_core::proto::datamodel::v1::ObjectMeta { + id: String::new(), + name: "aws-endpoint-override".to_string(), + created_at_ms: 0, + labels: HashMap::new(), + resource_version: 0, + annotations: HashMap::new(), + }), + r#type: "aws".to_string(), + credentials: HashMap::new(), + config: HashMap::new(), + credential_expires_at_ms: HashMap::new(), + }, + ) + .await + .unwrap(); + + let err = handle_configure_provider_refresh( + &state, + Request::new(ConfigureProviderRefreshRequest { + provider: "aws-endpoint-override".to_string(), + credential_key: "AWS_ACCESS_KEY_ID".to_string(), + strategy: ProviderCredentialRefreshStrategy::AwsStsAssumeRole as i32, + material: HashMap::from([ + ( + "role_arn".to_string(), + "arn:aws:iam::123456789012:role/Test".to_string(), + ), + ( + "sts_endpoint_url".to_string(), + "http://127.0.0.1:1/".to_string(), + ), + ]), + secret_material_keys: Vec::new(), + expires_at_ms: None, + }), + ) + .await + .unwrap_err(); + + assert_eq!(err.code(), Code::InvalidArgument); + assert!(err.message().contains("sts_endpoint_url")); + + // The rejected configuration must not leave a refresh state behind. + let provider = state + .store + .get_message_by_name::("aws-endpoint-override") + .await + .unwrap() + .unwrap(); + assert!( + crate::provider_refresh::get_refresh_state( + state.store.as_ref(), + provider.object_id(), + "AWS_ACCESS_KEY_ID", + ) + .await + .unwrap() + .is_none() + ); + } + + #[tokio::test] + async fn configure_aws_sts_rejects_partial_source_credentials() { + use crate::grpc::StoredSettingValue; + use crate::grpc::StoredSettings; + use crate::grpc::policy::save_global_settings; + + let state = test_server_state().await; + let global_settings = StoredSettings { + revision: 1, + settings: std::iter::once(( + openshell_core::settings::PROVIDERS_V2_ENABLED_KEY.to_string(), + StoredSettingValue::Bool(true), + )) + .collect(), + ..Default::default() + }; + save_global_settings(state.store.as_ref(), &global_settings) + .await + .unwrap(); + + create_provider_record( + state.store.as_ref(), + Provider { + metadata: Some(openshell_core::proto::datamodel::v1::ObjectMeta { + id: String::new(), + name: "aws-partial-source".to_string(), + created_at_ms: 0, + labels: HashMap::new(), + resource_version: 0, + annotations: HashMap::new(), + }), + r#type: "aws".to_string(), + credentials: HashMap::new(), + config: HashMap::new(), + credential_expires_at_ms: HashMap::new(), + }, + ) + .await + .unwrap(); + + // aws_access_key_id without its secret half must be rejected rather than + // silently falling back to the gateway's ambient identity. + let err = handle_configure_provider_refresh( + &state, + Request::new(ConfigureProviderRefreshRequest { + provider: "aws-partial-source".to_string(), + credential_key: "AWS_ACCESS_KEY_ID".to_string(), + strategy: ProviderCredentialRefreshStrategy::AwsStsAssumeRole as i32, + material: HashMap::from([ + ( + "role_arn".to_string(), + "arn:aws:iam::123456789012:role/Test".to_string(), + ), + ("aws_access_key_id".to_string(), "AKIATESTKEY".to_string()), + ]), + secret_material_keys: Vec::new(), + expires_at_ms: None, + }), + ) + .await + .unwrap_err(); + + assert_eq!(err.code(), Code::InvalidArgument); + assert!(err.message().contains("both be set or both omitted")); + } + + #[tokio::test] + async fn configure_aws_sts_rejects_session_token_without_pair() { + use crate::grpc::policy::set_global_bool_setting_for_test; + + let state = test_server_state().await; + set_global_bool_setting_for_test( + state.store.as_ref(), + openshell_core::settings::PROVIDERS_V2_ENABLED_KEY, + true, + ) + .await + .unwrap(); + + create_provider_record( + state.store.as_ref(), + Provider { + metadata: Some(openshell_core::proto::datamodel::v1::ObjectMeta { + id: String::new(), + name: "aws-lone-session".to_string(), + created_at_ms: 0, + labels: HashMap::new(), + resource_version: 0, + annotations: HashMap::new(), + }), + r#type: "aws".to_string(), + credentials: HashMap::new(), + config: HashMap::new(), + credential_expires_at_ms: HashMap::new(), + }, + ) + .await + .unwrap(); + + let err = handle_configure_provider_refresh( + &state, + Request::new(ConfigureProviderRefreshRequest { + provider: "aws-lone-session".to_string(), + credential_key: "AWS_ACCESS_KEY_ID".to_string(), + strategy: ProviderCredentialRefreshStrategy::AwsStsAssumeRole as i32, + material: HashMap::from([ + ( + "role_arn".to_string(), + "arn:aws:iam::123456789012:role/Test".to_string(), + ), + ( + "aws_session_token".to_string(), + "temp-session-token".to_string(), + ), + ]), + secret_material_keys: vec!["aws_session_token".to_string()], + expires_at_ms: None, + }), + ) + .await + .unwrap_err(); + + assert_eq!(err.code(), Code::InvalidArgument); + assert!(err.message().contains("aws_session_token requires")); + } + + #[tokio::test] + async fn configure_aws_sts_persists_resolved_additional_output_keys() { + use crate::grpc::StoredSettingValue; + use crate::grpc::StoredSettings; + use crate::grpc::policy::save_global_settings; + + let state = test_server_state().await; + let global_settings = StoredSettings { + revision: 1, + settings: std::iter::once(( + openshell_core::settings::PROVIDERS_V2_ENABLED_KEY.to_string(), + StoredSettingValue::Bool(true), + )) + .collect(), + ..Default::default() + }; + save_global_settings(state.store.as_ref(), &global_settings) + .await + .unwrap(); + + create_provider_record( + state.store.as_ref(), + Provider { + metadata: Some(openshell_core::proto::datamodel::v1::ObjectMeta { + id: String::new(), + name: "aws-outputs".to_string(), + created_at_ms: 0, + labels: HashMap::new(), + resource_version: 0, + annotations: HashMap::new(), + }), + r#type: "aws".to_string(), + credentials: HashMap::new(), + config: HashMap::new(), + credential_expires_at_ms: HashMap::new(), + }, + ) + .await + .unwrap(); + + handle_configure_provider_refresh( + &state, + Request::new(ConfigureProviderRefreshRequest { + provider: "aws-outputs".to_string(), + credential_key: "AWS_ACCESS_KEY_ID".to_string(), + strategy: ProviderCredentialRefreshStrategy::AwsStsAssumeRole as i32, + material: HashMap::from([( + "role_arn".to_string(), + "arn:aws:iam::123456789012:role/Test".to_string(), + )]), + secret_material_keys: Vec::new(), + expires_at_ms: None, + }), + ) + .await + .unwrap(); + + let provider = state + .store + .get_message_by_name::("aws-outputs") + .await + .unwrap() + .unwrap(); + let stored = crate::provider_refresh::get_refresh_state( + state.store.as_ref(), + provider.object_id(), + "AWS_ACCESS_KEY_ID", + ) + .await + .unwrap() + .expect("refresh state should exist"); + + assert_eq!( + stored.additional_output_keys.get("secret_access_key"), + Some(&"AWS_SECRET_ACCESS_KEY".to_string()) + ); + assert_eq!( + stored.additional_output_keys.get("session_token"), + Some(&"AWS_SESSION_TOKEN".to_string()) + ); + } + + #[tokio::test] + async fn configure_aws_sts_requires_profile_declaring_the_refresh() { + use crate::grpc::StoredSettingValue; + use crate::grpc::StoredSettings; + use crate::grpc::policy::save_global_settings; + + let state = test_server_state().await; + let global_settings = StoredSettings { + revision: 1, + settings: std::iter::once(( + openshell_core::settings::PROVIDERS_V2_ENABLED_KEY.to_string(), + StoredSettingValue::Bool(true), + )) + .collect(), + ..Default::default() + }; + save_global_settings(state.store.as_ref(), &global_settings) + .await + .unwrap(); + + // A generic provider has no profile, so it declares no STS refresh + // binding. STS must not be configurable against it. + create_provider_record( + state.store.as_ref(), + Provider { + metadata: Some(openshell_core::proto::datamodel::v1::ObjectMeta { + id: String::new(), + name: "generic-no-profile".to_string(), + created_at_ms: 0, + labels: HashMap::new(), + resource_version: 0, + annotations: HashMap::new(), + }), + r#type: "generic".to_string(), + credentials: std::iter::once(( + "AWS_ACCESS_KEY_ID".to_string(), + "placeholder".to_string(), + )) + .collect(), + config: HashMap::new(), + credential_expires_at_ms: HashMap::new(), + }, + ) + .await + .unwrap(); + + let err = handle_configure_provider_refresh( + &state, + Request::new(ConfigureProviderRefreshRequest { + provider: "generic-no-profile".to_string(), + credential_key: "AWS_ACCESS_KEY_ID".to_string(), + strategy: ProviderCredentialRefreshStrategy::AwsStsAssumeRole as i32, + material: HashMap::from([( + "role_arn".to_string(), + "arn:aws:iam::123456789012:role/Test".to_string(), + )]), + secret_material_keys: Vec::new(), + expires_at_ms: None, + }), + ) + .await + .unwrap_err(); + + assert_eq!(err.code(), Code::FailedPrecondition); + assert!(err.message().contains("provider profile")); + } + + #[tokio::test] + async fn configure_aws_sts_rejects_non_canonical_credential_key() { + use crate::grpc::StoredSettingValue; + use crate::grpc::StoredSettings; + use crate::grpc::policy::save_global_settings; + + let state = test_server_state().await; + let global_settings = StoredSettings { + revision: 1, + settings: std::iter::once(( + openshell_core::settings::PROVIDERS_V2_ENABLED_KEY.to_string(), + StoredSettingValue::Bool(true), + )) + .collect(), + ..Default::default() + }; + save_global_settings(state.store.as_ref(), &global_settings) + .await + .unwrap(); + + create_provider_record( + state.store.as_ref(), + Provider { + metadata: Some(openshell_core::proto::datamodel::v1::ObjectMeta { + id: String::new(), + name: "aws-wrong-key".to_string(), + created_at_ms: 0, + labels: HashMap::new(), + resource_version: 0, + annotations: HashMap::new(), + }), + r#type: "aws".to_string(), + credentials: HashMap::new(), + config: HashMap::new(), + credential_expires_at_ms: HashMap::new(), + }, + ) + .await + .unwrap(); + + // AWS_SECRET_ACCESS_KEY is a co-managed output, not the STS primary. The + // profile declares no refresh on it, so STS cannot be pinned there. + let err = handle_configure_provider_refresh( + &state, + Request::new(ConfigureProviderRefreshRequest { + provider: "aws-wrong-key".to_string(), + credential_key: "AWS_SECRET_ACCESS_KEY".to_string(), + strategy: ProviderCredentialRefreshStrategy::AwsStsAssumeRole as i32, + material: HashMap::from([( + "role_arn".to_string(), + "arn:aws:iam::123456789012:role/Test".to_string(), + )]), + secret_material_keys: Vec::new(), + expires_at_ms: None, + }), + ) + .await + .unwrap_err(); + + assert_eq!(err.code(), Code::FailedPrecondition); + assert!(err.message().contains("AWS_ACCESS_KEY_ID")); + } + + #[tokio::test] + async fn rotate_aws_sts_blocked_after_providers_v2_disabled() { + use crate::grpc::policy::set_global_bool_setting_for_test; + + let state = test_server_state().await; + + set_global_bool_setting_for_test( + state.store.as_ref(), + openshell_core::settings::PROVIDERS_V2_ENABLED_KEY, + true, + ) + .await + .unwrap(); + + create_provider_record( + state.store.as_ref(), + Provider { + metadata: Some(openshell_core::proto::datamodel::v1::ObjectMeta { + id: String::new(), + name: "aws-gate".to_string(), + created_at_ms: 0, + labels: HashMap::new(), + resource_version: 0, + annotations: HashMap::new(), + }), + r#type: "aws".to_string(), + credentials: HashMap::new(), + config: HashMap::new(), + credential_expires_at_ms: HashMap::new(), + }, + ) + .await + .unwrap(); + + handle_configure_provider_refresh( + &state, + Request::new(ConfigureProviderRefreshRequest { + provider: "aws-gate".to_string(), + credential_key: "AWS_ACCESS_KEY_ID".to_string(), + strategy: ProviderCredentialRefreshStrategy::AwsStsAssumeRole as i32, + material: HashMap::from([( + "role_arn".to_string(), + "arn:aws:iam::123456789012:role/Test".to_string(), + )]), + secret_material_keys: Vec::new(), + expires_at_ms: None, + }), + ) + .await + .unwrap(); + + // Disable the gate after the refresh is already configured. + set_global_bool_setting_for_test( + state.store.as_ref(), + openshell_core::settings::PROVIDERS_V2_ENABLED_KEY, + false, + ) + .await + .unwrap(); + + let err = handle_rotate_provider_credential( + &state, + Request::new(RotateProviderCredentialRequest { + provider: "aws-gate".to_string(), + credential_key: "AWS_ACCESS_KEY_ID".to_string(), + }), + ) + .await + .unwrap_err(); + + assert_eq!(err.code(), Code::FailedPrecondition); + assert!(err.message().contains("providers_v2_enabled")); + + // The gate rejection is recorded on the refresh state, and no credential + // was minted into the provider. + let provider = state + .store + .get_message_by_name::("aws-gate") + .await + .unwrap() + .unwrap(); + assert!(!provider.credentials.contains_key("AWS_ACCESS_KEY_ID")); + let refresh_state = crate::provider_refresh::get_refresh_state( + state.store.as_ref(), + provider.object_id(), + "AWS_ACCESS_KEY_ID", + ) + .await + .unwrap() + .expect("refresh state should exist"); + assert_eq!(refresh_state.status, "error"); + } + + #[tokio::test] + async fn active_provider_environment_keys_include_additional_output_keys() { + let state = test_server_state().await; + create_provider_record( + state.store.as_ref(), + Provider { + metadata: Some(openshell_core::proto::datamodel::v1::ObjectMeta { + id: String::new(), + name: "aws-env".to_string(), + created_at_ms: 0, + labels: HashMap::new(), + resource_version: 0, + annotations: HashMap::new(), + }), + r#type: "aws".to_string(), + credentials: HashMap::new(), + config: HashMap::new(), + credential_expires_at_ms: HashMap::new(), + }, + ) + .await + .unwrap(); + let provider = state + .store + .get_message_by_name::("aws-env") + .await + .unwrap() + .unwrap(); + + // A configured-but-not-yet-minted STS refresh: no minted values are in + // provider.credentials yet, but the reserved keys must still surface. + let refresh_state = crate::provider_refresh::new_refresh_state( + &provider, + "AWS_ACCESS_KEY_ID", + crate::provider_refresh::NewRefreshStateConfig { + additional_output_keys: HashMap::from([ + ( + "secret_access_key".to_string(), + "AWS_SECRET_ACCESS_KEY".to_string(), + ), + ("session_token".to_string(), "AWS_SESSION_TOKEN".to_string()), + ]), + strategy: ProviderCredentialRefreshStrategy::AwsStsAssumeRole, + material: HashMap::new(), + secret_material_keys: Vec::new(), + expires_at_ms: 0, + token_url: String::new(), + scopes: Vec::new(), + refresh_before_seconds: 0, + max_lifetime_seconds: 0, + }, + ) + .unwrap(); + crate::provider_refresh::put_refresh_state(state.store.as_ref(), &refresh_state) + .await + .unwrap(); + + let keys = active_provider_environment_keys(state.store.as_ref(), &provider, 0) + .await + .unwrap(); + assert!(keys.contains(&"AWS_ACCESS_KEY_ID".to_string())); + assert!(keys.contains(&"AWS_SECRET_ACCESS_KEY".to_string())); + assert!(keys.contains(&"AWS_SESSION_TOKEN".to_string())); + } + + #[tokio::test] + async fn configure_aws_sts_validates_additional_credential_key_collision() { + use crate::grpc::StoredSettingValue; + use crate::grpc::StoredSettings; + use crate::grpc::policy::save_global_settings; + + let state = test_server_state().await; + + let global_settings = StoredSettings { + revision: 1, + settings: std::iter::once(( + openshell_core::settings::PROVIDERS_V2_ENABLED_KEY.to_string(), + StoredSettingValue::Bool(true), + )) + .collect(), + ..Default::default() + }; + save_global_settings(state.store.as_ref(), &global_settings) + .await + .unwrap(); + + let mut existing_provider = Provider { + metadata: Some(openshell_core::proto::datamodel::v1::ObjectMeta { + id: String::new(), + name: "existing-aws-provider".to_string(), + created_at_ms: 0, + labels: HashMap::new(), + resource_version: 0, + annotations: HashMap::new(), + }), + r#type: "aws".to_string(), + credentials: HashMap::new(), + config: HashMap::new(), + credential_expires_at_ms: HashMap::new(), + }; + existing_provider.credentials.insert( + "AWS_SECRET_ACCESS_KEY".to_string(), + "existing-key".to_string(), + ); + create_provider_record(state.store.as_ref(), existing_provider) + .await + .unwrap(); + + let new_provider = Provider { + metadata: Some(openshell_core::proto::datamodel::v1::ObjectMeta { + id: String::new(), + name: "new-aws-provider".to_string(), + created_at_ms: 0, + labels: HashMap::new(), + resource_version: 0, + annotations: HashMap::new(), + }), + r#type: "aws".to_string(), + credentials: std::iter::once(( + "AWS_ACCESS_KEY_ID".to_string(), + "placeholder".to_string(), + )) + .collect(), + config: HashMap::new(), + credential_expires_at_ms: HashMap::new(), + }; + create_provider_record(state.store.as_ref(), new_provider) + .await + .unwrap(); + + state + .store + .put_message(&Sandbox { + metadata: Some(openshell_core::proto::datamodel::v1::ObjectMeta { + id: "sandbox-aws-configure-collision".to_string(), + name: "aws-configure-collision".to_string(), + created_at_ms: 1, + labels: HashMap::new(), + resource_version: 0, + annotations: HashMap::new(), + }), + spec: Some(SandboxSpec { + providers: vec![ + "existing-aws-provider".to_string(), + "new-aws-provider".to_string(), + ], + ..SandboxSpec::default() + }), + ..Default::default() + }) + .await + .unwrap(); + + let err = handle_configure_provider_refresh( + &state, + Request::new(ConfigureProviderRefreshRequest { + provider: "new-aws-provider".to_string(), + credential_key: "AWS_ACCESS_KEY_ID".to_string(), + strategy: ProviderCredentialRefreshStrategy::AwsStsAssumeRole as i32, + material: HashMap::from([( + "role_arn".to_string(), + "arn:aws:iam::123456789012:role/Test".to_string(), + )]), + secret_material_keys: Vec::new(), + expires_at_ms: None, + }), + ) + .await + .unwrap_err(); + + assert_eq!(err.code(), Code::FailedPrecondition); + assert!(err.message().contains("AWS_SECRET_ACCESS_KEY")); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn concurrent_configure_aws_sts_reserves_key_exactly_once() { + use crate::grpc::policy::set_global_bool_setting_for_test; + + let state = test_server_state().await; + set_global_bool_setting_for_test( + state.store.as_ref(), + openshell_core::settings::PROVIDERS_V2_ENABLED_KEY, + true, + ) + .await + .unwrap(); + + for name in ["aws-a", "aws-b"] { + create_provider_record( + state.store.as_ref(), + Provider { + metadata: Some(openshell_core::proto::datamodel::v1::ObjectMeta { + id: String::new(), + name: name.to_string(), + created_at_ms: 0, + labels: HashMap::new(), + resource_version: 0, + annotations: HashMap::new(), + }), + r#type: "aws".to_string(), + credentials: HashMap::new(), + config: HashMap::new(), + credential_expires_at_ms: HashMap::new(), + }, + ) + .await + .unwrap(); + } + + // Both providers are attached to the same sandbox, so their minted AWS + // credential env keys share a namespace and cannot both be reserved. + state + .store + .put_message(&Sandbox { + metadata: Some(openshell_core::proto::datamodel::v1::ObjectMeta { + id: "sandbox-concurrent-configure".to_string(), + name: "concurrent-configure".to_string(), + created_at_ms: 1, + labels: HashMap::new(), + resource_version: 0, + annotations: HashMap::new(), + }), + spec: Some(SandboxSpec { + providers: vec!["aws-a".to_string(), "aws-b".to_string()], + ..SandboxSpec::default() + }), + ..Default::default() + }) + .await + .unwrap(); + + let configure = |provider: &str| { + Request::new(ConfigureProviderRefreshRequest { + provider: provider.to_string(), + credential_key: "AWS_ACCESS_KEY_ID".to_string(), + strategy: ProviderCredentialRefreshStrategy::AwsStsAssumeRole as i32, + material: HashMap::from([( + "role_arn".to_string(), + "arn:aws:iam::123456789012:role/Test".to_string(), + )]), + secret_material_keys: Vec::new(), + expires_at_ms: None, + }) + }; + + let (result_a, result_b) = tokio::join!( + handle_configure_provider_refresh(&state, configure("aws-a")), + handle_configure_provider_refresh(&state, configure("aws-b")), + ); + + // Exactly one configuration wins; the other is rejected as a collision + // rather than both reserving the same key. + let ok_count = [&result_a, &result_b].iter().filter(|r| r.is_ok()).count(); + assert_eq!( + ok_count, + 1, + "exactly one concurrent configure should reserve the key; got a={:?} b={:?}", + result_a.as_ref().map(|_| ()), + result_b.as_ref().map(|_| ()) + ); + let err = [result_a, result_b] + .into_iter() + .find_map(Result::err) + .expect("one configure must fail"); + assert_eq!(err.code(), Code::FailedPrecondition); + } + fn google_cloud_provider(config: HashMap) -> Provider { Provider { metadata: Some(openshell_core::proto::datamodel::v1::ObjectMeta { diff --git a/crates/openshell-server/src/persistence/postgres.rs b/crates/openshell-server/src/persistence/postgres.rs index e3f9e5a7b3..12299805e9 100644 --- a/crates/openshell-server/src/persistence/postgres.rs +++ b/crates/openshell-server/src/persistence/postgres.rs @@ -164,17 +164,16 @@ RETURNING resource_version, created_at_ms, updated_at_ms updated_at_ms: row.get("updated_at_ms"), }) } else { - // Check if object exists to distinguish NotFound from Conflict + // The version-matched UPDATE matched no row. Distinguish a + // version mismatch (row present, different version) from an + // absent row (deleted / never existed). Both are CAS + // precondition failures, so report them as typed `Conflict` + // rather than a backend-dependent error string: absent rows + // carry `current_resource_version: None`. let existing = self.get(object_type, id).await?; - if let Some(record) = existing { - Err(PersistenceError::Conflict { - current_resource_version: Some(record.resource_version), - }) - } else { - Err(PersistenceError::Database(format!( - "object not found: {object_type}/{id}" - ))) - } + Err(PersistenceError::Conflict { + current_resource_version: existing.map(|record| record.resource_version), + }) } } WriteCondition::Unconditional => { diff --git a/crates/openshell-server/src/persistence/sqlite.rs b/crates/openshell-server/src/persistence/sqlite.rs index 0b1f50df6a..57d5c20e31 100644 --- a/crates/openshell-server/src/persistence/sqlite.rs +++ b/crates/openshell-server/src/persistence/sqlite.rs @@ -172,16 +172,16 @@ WHERE "object_type" = ?1 AND "id" = ?2 AND "resource_version" = ?3 .map_err(|e| map_db_error(&e))?; if result.rows_affected() == 0 { - // Check if object exists to distinguish NotFound from Conflict + // The version-matched UPDATE matched no row. Distinguish a + // version mismatch (row present, different version) from an + // absent row (deleted / never existed). Both are CAS + // precondition failures, so report them as typed `Conflict` + // rather than a backend-dependent error string: absent rows + // carry `current_resource_version: None`. let existing = self.get(object_type, id).await?; - if let Some(record) = existing { - return Err(PersistenceError::Conflict { - current_resource_version: Some(record.resource_version), - }); - } - return Err(PersistenceError::Database(format!( - "object not found: {object_type}/{id}" - ))); + return Err(PersistenceError::Conflict { + current_resource_version: existing.map(|record| record.resource_version), + }); } // Fetch the updated record to get the new resource_version diff --git a/crates/openshell-server/src/provider_refresh.rs b/crates/openshell-server/src/provider_refresh.rs index b604a3ef33..8c9b9c4d59 100644 --- a/crates/openshell-server/src/provider_refresh.rs +++ b/crates/openshell-server/src/provider_refresh.rs @@ -5,7 +5,7 @@ #![allow(clippy::result_large_err)] -use crate::persistence::{ObjectType, Store, current_time_ms}; +use crate::persistence::{ObjectType, PersistenceError, Store, WriteCondition, current_time_ms}; use openshell_core::proto::{ Provider, ProviderCredentialRefreshStatus, ProviderCredentialRefreshStrategy, StoredProviderCredentialRefreshState, @@ -47,6 +47,41 @@ pub async fn put_refresh_state( .map_err(|e| Status::internal(format!("persist provider refresh state failed: {e}"))) } +/// Persist an updated refresh state only if the row still exists with the +/// generation read at the start of the rotation. +/// +/// Uses a version-matched UPDATE, which never inserts — so a refresh deleted +/// while an STS (or OAuth) request was in flight is not resurrected, and its +/// stored source-credential material is not recreated (CWE-362). Returns the new +/// resource version when persisted, or `None` when the refresh was deleted or +/// superseded by a concurrent write (in which case nothing was written). +async fn persist_refresh_state_if_current( + store: &Store, + state: &StoredProviderCredentialRefreshState, + expected_version: u64, +) -> Result, Status> { + match store + .put_if( + StoredProviderCredentialRefreshState::object_type(), + state.object_id(), + state.object_name(), + &state.encode_to_vec(), + None, + WriteCondition::MatchResourceVersion(expected_version), + ) + .await + { + Ok(result) => Ok(Some(result.resource_version)), + // The version-matched UPDATE matched no row: the refresh was deleted + // (current version `None`) or superseded by a concurrent write (a + // different current version). Either way nothing was written. + Err(PersistenceError::Conflict { .. }) => Ok(None), + Err(e) => Err(Status::internal(format!( + "persist provider refresh state failed: {e}" + ))), + } +} + pub async fn list_refresh_states_for_provider( store: &Store, provider_id: &str, @@ -176,6 +211,10 @@ pub struct NewRefreshStateConfig { pub scopes: Vec, pub refresh_before_seconds: i64, pub max_lifetime_seconds: i64, + /// Resolved semantic output id -> concrete env key for credentials this + /// refresh co-mints beyond its primary. Pinned from the profile's + /// `additional_outputs` at configure time. + pub additional_output_keys: HashMap, } #[allow(clippy::unnecessary_wraps)] @@ -217,6 +256,7 @@ pub fn new_refresh_state( scopes: config.scopes, refresh_before_seconds: config.refresh_before_seconds, max_lifetime_seconds: config.max_lifetime_seconds, + additional_output_keys: config.additional_output_keys, }) } @@ -227,6 +267,7 @@ struct MintedCredential { access_token: String, expires_at_ms: i64, refresh_token: Option, + additional_credentials: HashMap, } #[derive(Debug, Deserialize)] @@ -280,18 +321,12 @@ pub fn refresh_strategy_name(strategy: i32) -> &'static str { ProviderCredentialRefreshStrategy::Oauth2RefreshToken => "oauth2_refresh_token", ProviderCredentialRefreshStrategy::Oauth2ClientCredentials => "oauth2_client_credentials", ProviderCredentialRefreshStrategy::GoogleServiceAccountJwt => "google_service_account_jwt", + ProviderCredentialRefreshStrategy::AwsStsAssumeRole => "aws_sts_assume_role", ProviderCredentialRefreshStrategy::Unspecified => "unspecified", } } -pub fn is_gateway_mintable_strategy(strategy: ProviderCredentialRefreshStrategy) -> bool { - matches!( - strategy, - ProviderCredentialRefreshStrategy::Oauth2RefreshToken - | ProviderCredentialRefreshStrategy::Oauth2ClientCredentials - | ProviderCredentialRefreshStrategy::GoogleServiceAccountJwt - ) -} +pub use openshell_providers::is_gateway_mintable_strategy; pub async fn refresh_provider_credential( store: &Store, @@ -307,6 +342,13 @@ pub async fn refresh_provider_credential( else { return Err(Status::not_found("provider refresh state not found")); }; + // Generation of the refresh at the start of the rotation. Terminal persists + // match on it so a concurrent delete or rotation is detected rather than + // clobbered, and a deleted refresh is never recreated (CWE-362). + let expected_version = state + .metadata + .as_ref() + .map_or(0, |meta| meta.resource_version); info!( provider = %state.provider_name, @@ -318,30 +360,33 @@ pub async fn refresh_provider_credential( "provider credential refresh started" ); + // Enforce the providers_v2 gate on every mint, not just at configure time. + // Otherwise disabling providers_v2_enabled leaves already-configured refresh + // states that the worker and manual rotation keep minting from. + if let Err(err) = ensure_refresh_providers_v2_gate(store, &state).await { + let now_ms = current_time_ms(); + state.status = "error".to_string(); + state.last_error = err.message().to_string(); + state.next_refresh_at_ms = + now_ms.saturating_add(REFRESH_ERROR_RETRY_SECONDS.saturating_mul(1000)); + persist_refresh_state_if_current(store, &state, expected_version).await?; + warn!( + provider = %state.provider_name, + credential_key = %state.credential_key, + strategy = %refresh_strategy_name(state.strategy), + status = %state.status, + error = %err, + "provider credential refresh gate rejected" + ); + return Err(err); + } + match mint_credential(&state).await { Ok(minted) => { let now_ms = current_time_ms(); - if let Err(err) = - apply_minted_credential(store, &provider, credential_key, &minted).await - { - state.status = "error".to_string(); - state.last_error = err.message().to_string(); - state.next_refresh_at_ms = - now_ms.saturating_add(REFRESH_ERROR_RETRY_SECONDS.saturating_mul(1000)); - put_refresh_state(store, &state).await?; - warn!( - provider = %state.provider_name, - credential_key = %state.credential_key, - strategy = %refresh_strategy_name(state.strategy), - status = %state.status, - next_refresh_at_ms = state.next_refresh_at_ms, - seconds_until_refresh = seconds_until_ms(now_ms, state.next_refresh_at_ms), - error = %err, - "provider credential refresh errored" - ); - return Err(err); - } - if let Some(refresh_token) = minted.refresh_token { + // Fold the minted result into the refresh state before claiming the + // generation. + if let Some(refresh_token) = minted.refresh_token.clone() { state .material .insert("refresh_token".to_string(), refresh_token); @@ -363,7 +408,52 @@ pub async fn refresh_provider_credential( state.last_refresh_at_ms = now_ms; state.status = "refreshed".to_string(); state.last_error.clear(); - put_refresh_state(store, &state).await?; + + // Claim the refresh generation with a version-matched write BEFORE + // touching the provider. It succeeds only if the refresh still holds + // the generation we started from; if it was deleted, recreated, or a + // concurrent rotation won, it returns `None` and we leave both the + // refresh state and the provider unchanged — no credentials minted + // from a stale generation are written, and a deleted refresh is not + // resurrected (CWE-362). This makes generation ownership the gate on + // the provider credential write. + let Some(new_version) = + persist_refresh_state_if_current(store, &state, expected_version).await? + else { + warn!( + provider = %state.provider_name, + credential_key = %state.credential_key, + strategy = %refresh_strategy_name(state.strategy), + "provider credential refresh deleted or superseded during rotation; discarding minted credentials" + ); + return Err(Status::aborted( + "provider refresh was deleted or superseded during rotation", + )); + }; + + // Generation is ours; write the minted credentials into the provider. + if let Err(err) = + apply_minted_credential(store, &provider, credential_key, &minted).await + { + state.status = "error".to_string(); + state.last_error = err.message().to_string(); + state.next_refresh_at_ms = + now_ms.saturating_add(REFRESH_ERROR_RETRY_SECONDS.saturating_mul(1000)); + // Reflect the failure on the state we just wrote; skip silently + // if it was deleted concurrently (it is not recreated). + persist_refresh_state_if_current(store, &state, new_version).await?; + warn!( + provider = %state.provider_name, + credential_key = %state.credential_key, + strategy = %refresh_strategy_name(state.strategy), + status = %state.status, + next_refresh_at_ms = state.next_refresh_at_ms, + seconds_until_refresh = seconds_until_ms(now_ms, state.next_refresh_at_ms), + error = %err, + "provider credential refresh errored" + ); + return Err(err); + } info!( provider = %state.provider_name, credential_key = %state.credential_key, @@ -382,7 +472,7 @@ pub async fn refresh_provider_credential( state.last_error = err.message().to_string(); state.next_refresh_at_ms = now_ms.saturating_add(REFRESH_ERROR_RETRY_SECONDS.saturating_mul(1000)); - put_refresh_state(store, &state).await?; + persist_refresh_state_if_current(store, &state, expected_version).await?; warn!( provider = %state.provider_name, credential_key = %state.credential_key, @@ -408,12 +498,23 @@ async fn apply_minted_credential( updated .credentials .insert(credential_key.to_string(), minted.access_token.clone()); + for (key, value) in &minted.additional_credentials { + updated.credentials.insert(key.clone(), value.clone()); + } if minted.expires_at_ms > 0 { updated .credential_expires_at_ms .insert(credential_key.to_string(), minted.expires_at_ms); + for key in minted.additional_credentials.keys() { + updated + .credential_expires_at_ms + .insert(key.clone(), minted.expires_at_ms); + } } else { updated.credential_expires_at_ms.remove(credential_key); + for key in minted.additional_credentials.keys() { + updated.credential_expires_at_ms.remove(key); + } } crate::grpc::provider::validate_provider_update_against_attached_sandboxes(store, &updated) .await?; @@ -422,12 +523,23 @@ async fn apply_minted_credential( current .credentials .insert(credential_key.to_string(), minted.access_token.clone()); + for (key, value) in &minted.additional_credentials { + current.credentials.insert(key.clone(), value.clone()); + } if minted.expires_at_ms > 0 { current .credential_expires_at_ms .insert(credential_key.to_string(), minted.expires_at_ms); + for key in minted.additional_credentials.keys() { + current + .credential_expires_at_ms + .insert(key.clone(), minted.expires_at_ms); + } } else { current.credential_expires_at_ms.remove(credential_key); + for key in minted.additional_credentials.keys() { + current.credential_expires_at_ms.remove(key); + } } }) .await @@ -435,6 +547,31 @@ async fn apply_minted_credential( .map_err(|e| Status::internal(format!("persist refreshed provider credential failed: {e}"))) } +/// Reject minting for strategies that require `providers_v2_enabled` when the +/// setting is off. Runs on every refresh (worker sweep and manual rotation), so +/// disabling the setting halts further mints from already-configured states. +async fn ensure_refresh_providers_v2_gate( + store: &Store, + state: &StoredProviderCredentialRefreshState, +) -> Result<(), Status> { + let strategy = ProviderCredentialRefreshStrategy::try_from(state.strategy) + .unwrap_or(ProviderCredentialRefreshStrategy::Unspecified); + if strategy != ProviderCredentialRefreshStrategy::AwsStsAssumeRole { + return Ok(()); + } + if !crate::grpc::policy::global_bool_setting_enabled( + store, + openshell_core::settings::PROVIDERS_V2_ENABLED_KEY, + ) + .await? + { + return Err(Status::failed_precondition( + "aws_sts_assume_role requires providers_v2_enabled=true", + )); + } + Ok(()) +} + async fn mint_credential( state: &StoredProviderCredentialRefreshState, ) -> Result { @@ -450,6 +587,9 @@ async fn mint_credential( ProviderCredentialRefreshStrategy::GoogleServiceAccountJwt => { mint_google_service_account_jwt(state).await } + ProviderCredentialRefreshStrategy::AwsStsAssumeRole => { + mint_aws_sts_assume_role(state).await + } ProviderCredentialRefreshStrategy::External | ProviderCredentialRefreshStrategy::Static | ProviderCredentialRefreshStrategy::Unspecified => Err(Status::failed_precondition( @@ -545,6 +685,131 @@ async fn mint_google_service_account_jwt( request_token(&token_url, &form, lifetime_secs).await } +async fn mint_aws_sts_assume_role( + state: &StoredProviderCredentialRefreshState, +) -> Result { + let role_arn = required_material(&state.material, "role_arn")?; + let session_name = material_value(&state.material, &["session_name"]) + .unwrap_or_else(|| "openshell-sandbox".to_string()); + let external_id = material_value(&state.material, &["external_id"]); + let region = + material_value(&state.material, &["aws_region"]).unwrap_or_else(|| "us-east-1".to_string()); + + let region_provider = aws_sdk_sts::config::Region::new(region); + let mut config_loader = + aws_config::defaults(aws_config::BehaviorVersion::latest()).region(region_provider); + + // Explicit source credentials are all-or-nothing. A lone key must not + // silently fall through to the gateway's ambient identity (CWE-20): the + // caller asked for a specific principal, so an incomplete pair is an error. + // An optional session token supports temporary source credentials (SSO or a + // prior AssumeRole); it requires the access/secret pair. + let session_token = material_value(&state.material, &["aws_session_token"]); + match ( + material_value(&state.material, &["aws_access_key_id"]), + material_value(&state.material, &["aws_secret_access_key"]), + ) { + (Some(access_key), Some(secret_key)) => { + let creds = aws_sdk_sts::config::Credentials::new( + access_key, + secret_key, + session_token, + None, + "openshell-provider-refresh", + ); + config_loader = config_loader.credentials_provider(creds); + } + (None, None) if session_token.is_some() => { + return Err(Status::invalid_argument( + "aws_session_token requires aws_access_key_id and aws_secret_access_key", + )); + } + (None, None) => {} + _ => { + return Err(Status::invalid_argument( + "aws_access_key_id and aws_secret_access_key must both be set or both omitted", + )); + } + } + + let sdk_config = config_loader.load().await; + let sts_config = { + let mut builder = aws_sdk_sts::config::Builder::from(&sdk_config); + // Endpoint overrides exist only to point tests at a local mock STS. In + // production the endpoint is always resolved from the region so a caller + // cannot redirect an AWS-signed AssumeRole request at an arbitrary + // service (CWE-918). See `test_sts_endpoint_override`. + if let Some(endpoint) = test_sts_endpoint_override(state) { + builder = builder.endpoint_url(endpoint); + } + builder.build() + }; + let client = aws_sdk_sts::Client::from_conf(sts_config); + + let max_lifetime_i64 = if state.max_lifetime_seconds > 0 { + state.max_lifetime_seconds + } else { + DEFAULT_MAX_LIFETIME_SECONDS + }; + let max_lifetime = i32::try_from(max_lifetime_i64.min(i64::from(i32::MAX))).unwrap_or(i32::MAX); + + let mut req = client + .assume_role() + .role_arn(&role_arn) + .role_session_name(&session_name) + .duration_seconds(max_lifetime); + + if let Some(eid) = external_id { + req = req.external_id(eid); + } + + let resp = req + .send() + .await + .map_err(|e| Status::internal(format!("STS AssumeRole failed: {e}")))?; + + let creds = resp + .credentials() + .ok_or_else(|| Status::internal("STS AssumeRole response missing credentials"))?; + + let access_key_id = creds.access_key_id().to_string(); + let secret_access_key = creds.secret_access_key().to_string(); + let session_token = creds.session_token().to_string(); + + let now_ms = current_time_ms(); + let expires_at_ms = creds + .expiration() + .to_millis() + .unwrap_or_else(|_| now_ms + max_lifetime_i64 * 1000); + let max_expires = now_ms + max_lifetime_i64 * 1000; + let expires_at_ms = expires_at_ms.min(max_expires); + + // Map STS response fields to the env keys the profile bound to each semantic + // output. Configure pins these from the profile's additional_outputs, so a + // missing mapping means the state was not configured against a valid AWS STS + // profile binding; refuse rather than guessing standard AWS names. + let output_values = [ + ("secret_access_key", secret_access_key), + ("session_token", session_token), + ]; + let mut additional = HashMap::new(); + for (output_id, value) in output_values { + let env_key = state.additional_output_keys.get(output_id).ok_or_else(|| { + Status::failed_precondition(format!( + "refresh state missing resolved output key for '{output_id}'; reconfigure the AWS STS refresh" + )) + })?; + additional.insert(env_key.clone(), value); + } + + Ok(MintedCredential { + access_token: access_key_id, + expires_at_ms, + refresh_token: None, + additional_credentials: additional, + }) +} + async fn request_token( token_url: &str, form: &[(String, String)], @@ -604,6 +869,7 @@ async fn request_token( refresh_token: token .refresh_token .filter(|refresh_token| !refresh_token.trim().is_empty()), + additional_credentials: HashMap::new(), }) } @@ -681,6 +947,27 @@ fn is_loopback_host(host: &str) -> bool { matches!(host, "localhost" | "127.0.0.1" | "::1") } +/// Test-only STS endpoint override. Reads the `sts_endpoint_url` material and +/// accepts it only when it is a loopback URL, so unit tests can target a local +/// mock STS. Compiled out of production builds entirely: the configure boundary +/// also rejects the `sts_endpoint_url` material key, so it can never reach a +/// stored refresh state outside tests. +#[cfg(test)] +fn test_sts_endpoint_override(state: &StoredProviderCredentialRefreshState) -> Option { + material_value(&state.material, &["sts_endpoint_url"]).filter(|endpoint| { + reqwest::Url::parse(endpoint) + .ok() + .and_then(|parsed| parsed.host_str().map(is_loopback_host)) + .unwrap_or(false) + }) +} + +#[cfg(not(test))] +#[allow(clippy::missing_const_for_fn)] +fn test_sts_endpoint_override(_state: &StoredProviderCredentialRefreshState) -> Option { + None +} + pub fn spawn_refresh_worker(state: std::sync::Arc, interval: Duration) { info!( interval_seconds = interval.as_secs(), @@ -773,8 +1060,8 @@ async fn run_refresh_worker_tick(store: &Store) -> Result<(), Status> { #[cfg(test)] mod tests { use super::{ - NewRefreshStateConfig, get_refresh_state, new_refresh_state, put_refresh_state, - refresh_provider_credential, refresh_state_name, refresh_strategy_name, + NewRefreshStateConfig, delete_refresh_state, get_refresh_state, new_refresh_state, + put_refresh_state, refresh_provider_credential, refresh_state_name, refresh_strategy_name, run_refresh_worker_tick, seconds_until_ms, }; use crate::persistence::test_store; @@ -855,6 +1142,7 @@ mod tests { &provider, "MS_GRAPH_ACCESS_TOKEN", NewRefreshStateConfig { + additional_output_keys: HashMap::new(), strategy: ProviderCredentialRefreshStrategy::Oauth2ClientCredentials, material: HashMap::from([ ("client_id".to_string(), "client-id".to_string()), @@ -939,6 +1227,7 @@ mod tests { &provider_b, "MS_GRAPH_ACCESS_TOKEN", NewRefreshStateConfig { + additional_output_keys: HashMap::new(), strategy: ProviderCredentialRefreshStrategy::Oauth2ClientCredentials, material: HashMap::from([ ("client_id".to_string(), "client-id".to_string()), @@ -1007,6 +1296,7 @@ mod tests { &provider, "MS_GRAPH_ACCESS_TOKEN", NewRefreshStateConfig { + additional_output_keys: HashMap::new(), strategy: ProviderCredentialRefreshStrategy::Oauth2RefreshToken, material: HashMap::from([ ("client_id".to_string(), "client-id".to_string()), @@ -1086,6 +1376,7 @@ mod tests { &provider, "GOOGLE_DRIVE_ACCESS_TOKEN", NewRefreshStateConfig { + additional_output_keys: HashMap::new(), strategy: ProviderCredentialRefreshStrategy::GoogleServiceAccountJwt, material: HashMap::from([ ( @@ -1132,6 +1423,7 @@ mod tests { &provider, "MS_GRAPH_ACCESS_TOKEN", NewRefreshStateConfig { + additional_output_keys: HashMap::new(), strategy: ProviderCredentialRefreshStrategy::External, material: HashMap::new(), secret_material_keys: Vec::new(), @@ -1166,6 +1458,768 @@ mod tests { ); } + #[test] + fn refresh_strategy_name_includes_aws_sts() { + assert_eq!( + refresh_strategy_name(ProviderCredentialRefreshStrategy::AwsStsAssumeRole as i32), + "aws_sts_assume_role" + ); + } + + #[tokio::test] + async fn aws_sts_assume_role_mints_three_credentials_from_mock_endpoint() { + let mock_server = MockServer::start().await; + Mock::given(method("POST")) + .and(body_string_contains("Action=AssumeRole")) + .and(body_string_contains("RoleArn=arn")) + .respond_with(ResponseTemplate::new(200).set_body_string( + r#" + + + AROA3XFRBF23:test-session + arn:aws:sts::123456789012:assumed-role/TestRole/test-session + + + ASIAMOCKKEY + MockSecretAccessKey123 + MockSessionTokenXYZ + 2099-01-01T00:00:00Z + + + + 01234567-89ab-cdef-0123-456789abcdef + +"#, + )) + .mount(&mock_server) + .await; + + let store = test_store().await; + crate::grpc::policy::set_global_bool_setting_for_test( + &store, + openshell_core::settings::PROVIDERS_V2_ENABLED_KEY, + true, + ) + .await + .unwrap(); + let prov = provider("aws-sts-test", "aws"); + store.put_message(&prov).await.unwrap(); + + let state = new_refresh_state( + &prov, + "AWS_ACCESS_KEY_ID", + NewRefreshStateConfig { + additional_output_keys: HashMap::from([ + ( + "secret_access_key".to_string(), + "AWS_SECRET_ACCESS_KEY".to_string(), + ), + ("session_token".to_string(), "AWS_SESSION_TOKEN".to_string()), + ]), + strategy: ProviderCredentialRefreshStrategy::AwsStsAssumeRole, + material: HashMap::from([ + ( + "role_arn".to_string(), + "arn:aws:iam::123456789012:role/TestRole".to_string(), + ), + ("session_name".to_string(), "test-session".to_string()), + ("aws_access_key_id".to_string(), "AKIATESTKEY".to_string()), + ( + "aws_secret_access_key".to_string(), + "TestSecretKey".to_string(), + ), + ("sts_endpoint_url".to_string(), mock_server.uri()), + ]), + secret_material_keys: vec!["aws_secret_access_key".to_string()], + expires_at_ms: 0, + token_url: String::new(), + scopes: Vec::new(), + refresh_before_seconds: 300, + max_lifetime_seconds: 3600, + }, + ) + .unwrap(); + put_refresh_state(&store, &state).await.unwrap(); + + let refreshed = refresh_provider_credential(&store, "aws-sts-test", "AWS_ACCESS_KEY_ID") + .await + .unwrap(); + assert_eq!(refreshed.status, "refreshed"); + assert!(refreshed.expires_at_ms > 0); + + let stored = store + .get_message_by_name::("aws-sts-test") + .await + .unwrap() + .unwrap(); + assert_eq!( + stored.credentials.get("AWS_ACCESS_KEY_ID"), + Some(&"ASIAMOCKKEY".to_string()) + ); + assert_eq!( + stored.credentials.get("AWS_SECRET_ACCESS_KEY"), + Some(&"MockSecretAccessKey123".to_string()) + ); + assert_eq!( + stored.credentials.get("AWS_SESSION_TOKEN"), + Some(&"MockSessionTokenXYZ".to_string()) + ); + } + + #[tokio::test] + async fn aws_sts_mint_writes_to_resolved_additional_output_keys() { + let mock_server = MockServer::start().await; + Mock::given(method("POST")) + .and(body_string_contains("Action=AssumeRole")) + .respond_with(ResponseTemplate::new(200).set_body_string( + r#" + + + ASIAMOCKKEY + MockSecretAccessKey123 + MockSessionTokenXYZ + 2099-01-01T00:00:00Z + + +"#, + )) + .mount(&mock_server) + .await; + + let store = test_store().await; + crate::grpc::policy::set_global_bool_setting_for_test( + &store, + openshell_core::settings::PROVIDERS_V2_ENABLED_KEY, + true, + ) + .await + .unwrap(); + let prov = provider("aws-sts-custom", "aws"); + store.put_message(&prov).await.unwrap(); + + // The minter honors the resolved output->env-key map from state, not + // hardcoded AWS names. + let state = new_refresh_state( + &prov, + "AWS_ACCESS_KEY_ID", + NewRefreshStateConfig { + additional_output_keys: HashMap::from([ + ("secret_access_key".to_string(), "CUSTOM_SECRET".to_string()), + ("session_token".to_string(), "CUSTOM_SESSION".to_string()), + ]), + strategy: ProviderCredentialRefreshStrategy::AwsStsAssumeRole, + material: HashMap::from([ + ( + "role_arn".to_string(), + "arn:aws:iam::123456789012:role/TestRole".to_string(), + ), + ("aws_access_key_id".to_string(), "AKIATESTKEY".to_string()), + ( + "aws_secret_access_key".to_string(), + "TestSecretKey".to_string(), + ), + ("sts_endpoint_url".to_string(), mock_server.uri()), + ]), + secret_material_keys: vec!["aws_secret_access_key".to_string()], + expires_at_ms: 0, + token_url: String::new(), + scopes: Vec::new(), + refresh_before_seconds: 300, + max_lifetime_seconds: 3600, + }, + ) + .unwrap(); + put_refresh_state(&store, &state).await.unwrap(); + + refresh_provider_credential(&store, "aws-sts-custom", "AWS_ACCESS_KEY_ID") + .await + .unwrap(); + + let stored = store + .get_message_by_name::("aws-sts-custom") + .await + .unwrap() + .unwrap(); + assert_eq!( + stored.credentials.get("AWS_ACCESS_KEY_ID"), + Some(&"ASIAMOCKKEY".to_string()) + ); + assert_eq!( + stored.credentials.get("CUSTOM_SECRET"), + Some(&"MockSecretAccessKey123".to_string()) + ); + assert_eq!( + stored.credentials.get("CUSTOM_SESSION"), + Some(&"MockSessionTokenXYZ".to_string()) + ); + assert!(!stored.credentials.contains_key("AWS_SECRET_ACCESS_KEY")); + } + + #[tokio::test] + async fn aws_sts_mint_rejects_partial_source_credentials() { + let store = test_store().await; + crate::grpc::policy::set_global_bool_setting_for_test( + &store, + openshell_core::settings::PROVIDERS_V2_ENABLED_KEY, + true, + ) + .await + .unwrap(); + let prov = provider("aws-sts-partial", "aws"); + store.put_message(&prov).await.unwrap(); + + // Only the access key half of the explicit source pair is present. The + // mint must fail rather than fall back to the gateway's ambient identity. + let state = new_refresh_state( + &prov, + "AWS_ACCESS_KEY_ID", + NewRefreshStateConfig { + additional_output_keys: HashMap::from([ + ( + "secret_access_key".to_string(), + "AWS_SECRET_ACCESS_KEY".to_string(), + ), + ("session_token".to_string(), "AWS_SESSION_TOKEN".to_string()), + ]), + strategy: ProviderCredentialRefreshStrategy::AwsStsAssumeRole, + material: HashMap::from([ + ( + "role_arn".to_string(), + "arn:aws:iam::123456789012:role/TestRole".to_string(), + ), + ("aws_access_key_id".to_string(), "AKIATESTKEY".to_string()), + ]), + secret_material_keys: Vec::new(), + expires_at_ms: 0, + token_url: String::new(), + scopes: Vec::new(), + refresh_before_seconds: 300, + max_lifetime_seconds: 3600, + }, + ) + .unwrap(); + put_refresh_state(&store, &state).await.unwrap(); + + let err = refresh_provider_credential(&store, "aws-sts-partial", "AWS_ACCESS_KEY_ID") + .await + .unwrap_err(); + assert_eq!(err.code(), tonic::Code::InvalidArgument); + assert!(err.message().contains("both be set or both omitted")); + + let stored = store + .get_message_by_name::("aws-sts-partial") + .await + .unwrap() + .unwrap(); + assert!(!stored.credentials.contains_key("AWS_ACCESS_KEY_ID")); + } + + #[tokio::test] + async fn apply_minted_credential_writes_additional_keys() { + use super::apply_minted_credential; + + let store = test_store().await; + let mut prov = provider("aws-test", "aws"); + prov.credentials + .insert("AWS_ACCESS_KEY_ID".to_string(), "old-key".to_string()); + store.put_message(&prov).await.unwrap(); + + let minted = super::MintedCredential { + access_token: "AKIAIOSFODNN7EXAMPLE".to_string(), + expires_at_ms: 4_000_000_000_000, + refresh_token: None, + additional_credentials: HashMap::from([ + ( + "AWS_SECRET_ACCESS_KEY".to_string(), + "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY".to_string(), + ), + ( + "AWS_SESSION_TOKEN".to_string(), + "FwoGZXIvYXdzEBYaDH...EXAMPLETOKEN".to_string(), + ), + ]), + }; + + apply_minted_credential(&store, &prov, "AWS_ACCESS_KEY_ID", &minted) + .await + .unwrap(); + + let stored = store + .get_message_by_name::("aws-test") + .await + .unwrap() + .unwrap(); + assert_eq!( + stored.credentials.get("AWS_ACCESS_KEY_ID"), + Some(&"AKIAIOSFODNN7EXAMPLE".to_string()) + ); + assert_eq!( + stored.credentials.get("AWS_SECRET_ACCESS_KEY"), + Some(&"wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY".to_string()) + ); + assert_eq!( + stored.credentials.get("AWS_SESSION_TOKEN"), + Some(&"FwoGZXIvYXdzEBYaDH...EXAMPLETOKEN".to_string()) + ); + assert_eq!( + stored.credential_expires_at_ms.get("AWS_ACCESS_KEY_ID"), + Some(&4_000_000_000_000) + ); + assert_eq!( + stored.credential_expires_at_ms.get("AWS_SECRET_ACCESS_KEY"), + Some(&4_000_000_000_000) + ); + assert_eq!( + stored.credential_expires_at_ms.get("AWS_SESSION_TOKEN"), + Some(&4_000_000_000_000) + ); + } + + #[tokio::test] + async fn apply_minted_credential_validates_additional_keys_against_sandboxes() { + use super::apply_minted_credential; + + let store = test_store().await; + let mut existing_provider = provider("existing-aws", "aws"); + existing_provider + .credentials + .insert("AWS_SECRET_ACCESS_KEY".to_string(), "existing".to_string()); + store.put_message(&existing_provider).await.unwrap(); + + let refreshing_provider = provider("refreshing-aws", "aws"); + store.put_message(&refreshing_provider).await.unwrap(); + + store + .put_message(&Sandbox { + metadata: Some(ObjectMeta { + id: "sandbox-aws-collision".to_string(), + name: "aws-collision".to_string(), + created_at_ms: 1, + labels: HashMap::new(), + resource_version: 0, + annotations: HashMap::new(), + }), + spec: Some(SandboxSpec { + providers: vec!["existing-aws".to_string(), "refreshing-aws".to_string()], + ..SandboxSpec::default() + }), + ..Default::default() + }) + .await + .unwrap(); + + let minted = super::MintedCredential { + access_token: "AKIAIOSFODNN7EXAMPLE".to_string(), + expires_at_ms: 4_000_000_000_000, + refresh_token: None, + additional_credentials: HashMap::from([ + ( + "AWS_SECRET_ACCESS_KEY".to_string(), + "secret-key".to_string(), + ), + ("AWS_SESSION_TOKEN".to_string(), "session-token".to_string()), + ]), + }; + + let err = + apply_minted_credential(&store, &refreshing_provider, "AWS_ACCESS_KEY_ID", &minted) + .await + .unwrap_err(); + assert_eq!(err.code(), tonic::Code::FailedPrecondition); + assert!(err.message().contains("AWS_SECRET_ACCESS_KEY")); + } + + // A wiremock responder that blocks the STS response until the test releases + // it, so a delete-refresh can be interleaved deterministically while the + // rotation is parked awaiting STS. + struct GatedStsResponder { + hit: std::sync::Mutex>>, + release: std::sync::Mutex>, + body: String, + } + + impl wiremock::Respond for GatedStsResponder { + fn respond(&self, _request: &wiremock::Request) -> ResponseTemplate { + let hit = self.hit.lock().unwrap().take(); + if let Some(hit) = hit { + let _ = hit.send(()); + } + let _ = self.release.lock().unwrap().recv(); + ResponseTemplate::new(200).set_body_string(self.body.clone()) + } + } + + #[tokio::test] + async fn aws_sts_mint_accepts_session_token_with_source_pair() { + let mock_server = MockServer::start().await; + Mock::given(method("POST")) + .and(body_string_contains("Action=AssumeRole")) + .respond_with(ResponseTemplate::new(200).set_body_string( + r#" + + + ASIAMOCKKEY + MockSecretAccessKey123 + MockSessionTokenXYZ + 2099-01-01T00:00:00Z + + +"#, + )) + .mount(&mock_server) + .await; + + let store = test_store().await; + crate::grpc::policy::set_global_bool_setting_for_test( + &store, + openshell_core::settings::PROVIDERS_V2_ENABLED_KEY, + true, + ) + .await + .unwrap(); + let prov = provider("aws-sts-session", "aws"); + store.put_message(&prov).await.unwrap(); + + // Temporary source credentials: access key + secret + session token. + let state = new_refresh_state( + &prov, + "AWS_ACCESS_KEY_ID", + NewRefreshStateConfig { + additional_output_keys: HashMap::from([ + ( + "secret_access_key".to_string(), + "AWS_SECRET_ACCESS_KEY".to_string(), + ), + ("session_token".to_string(), "AWS_SESSION_TOKEN".to_string()), + ]), + strategy: ProviderCredentialRefreshStrategy::AwsStsAssumeRole, + material: HashMap::from([ + ( + "role_arn".to_string(), + "arn:aws:iam::123456789012:role/TestRole".to_string(), + ), + ("aws_access_key_id".to_string(), "ASIASOURCEKEY".to_string()), + ( + "aws_secret_access_key".to_string(), + "SourceSecretKey".to_string(), + ), + ( + "aws_session_token".to_string(), + "SourceSessionToken".to_string(), + ), + ("sts_endpoint_url".to_string(), mock_server.uri()), + ]), + secret_material_keys: vec![ + "aws_secret_access_key".to_string(), + "aws_session_token".to_string(), + ], + expires_at_ms: 0, + token_url: String::new(), + scopes: Vec::new(), + refresh_before_seconds: 300, + max_lifetime_seconds: 3600, + }, + ) + .unwrap(); + put_refresh_state(&store, &state).await.unwrap(); + + let refreshed = refresh_provider_credential(&store, "aws-sts-session", "AWS_ACCESS_KEY_ID") + .await + .unwrap(); + assert_eq!(refreshed.status, "refreshed"); + let stored = store + .get_message_by_name::("aws-sts-session") + .await + .unwrap() + .unwrap(); + assert_eq!( + stored.credentials.get("AWS_ACCESS_KEY_ID"), + Some(&"ASIAMOCKKEY".to_string()) + ); + } + + #[tokio::test] + async fn aws_sts_mint_rejects_session_token_without_source_pair() { + let store = test_store().await; + crate::grpc::policy::set_global_bool_setting_for_test( + &store, + openshell_core::settings::PROVIDERS_V2_ENABLED_KEY, + true, + ) + .await + .unwrap(); + let prov = provider("aws-sts-lonesession", "aws"); + store.put_message(&prov).await.unwrap(); + + let state = new_refresh_state( + &prov, + "AWS_ACCESS_KEY_ID", + NewRefreshStateConfig { + additional_output_keys: HashMap::from([ + ( + "secret_access_key".to_string(), + "AWS_SECRET_ACCESS_KEY".to_string(), + ), + ("session_token".to_string(), "AWS_SESSION_TOKEN".to_string()), + ]), + strategy: ProviderCredentialRefreshStrategy::AwsStsAssumeRole, + material: HashMap::from([ + ( + "role_arn".to_string(), + "arn:aws:iam::123456789012:role/TestRole".to_string(), + ), + ( + "aws_session_token".to_string(), + "SourceSessionToken".to_string(), + ), + ]), + secret_material_keys: vec!["aws_session_token".to_string()], + expires_at_ms: 0, + token_url: String::new(), + scopes: Vec::new(), + refresh_before_seconds: 300, + max_lifetime_seconds: 3600, + }, + ) + .unwrap(); + put_refresh_state(&store, &state).await.unwrap(); + + let err = refresh_provider_credential(&store, "aws-sts-lonesession", "AWS_ACCESS_KEY_ID") + .await + .unwrap_err(); + assert_eq!(err.code(), tonic::Code::InvalidArgument); + assert!(err.message().contains("aws_session_token requires")); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn rotation_does_not_resurrect_refresh_deleted_mid_flight() { + let mock_server = MockServer::start().await; + let (hit_tx, hit_rx) = tokio::sync::oneshot::channel::<()>(); + let (release_tx, release_rx) = std::sync::mpsc::channel::<()>(); + Mock::given(method("POST")) + .and(body_string_contains("Action=AssumeRole")) + .respond_with(GatedStsResponder { + hit: std::sync::Mutex::new(Some(hit_tx)), + release: std::sync::Mutex::new(release_rx), + body: r#" + + + ASIAMOCKKEY + MockSecretAccessKey123 + MockSessionTokenXYZ + 2099-01-01T00:00:00Z + + +"# + .to_string(), + }) + .mount(&mock_server) + .await; + + let store = test_store().await; + crate::grpc::policy::set_global_bool_setting_for_test( + &store, + openshell_core::settings::PROVIDERS_V2_ENABLED_KEY, + true, + ) + .await + .unwrap(); + let prov = provider("aws-race", "aws"); + store.put_message(&prov).await.unwrap(); + let provider_id = prov.object_id().to_string(); + + let state = new_refresh_state( + &prov, + "AWS_ACCESS_KEY_ID", + NewRefreshStateConfig { + additional_output_keys: HashMap::from([ + ( + "secret_access_key".to_string(), + "AWS_SECRET_ACCESS_KEY".to_string(), + ), + ("session_token".to_string(), "AWS_SESSION_TOKEN".to_string()), + ]), + strategy: ProviderCredentialRefreshStrategy::AwsStsAssumeRole, + material: HashMap::from([ + ( + "role_arn".to_string(), + "arn:aws:iam::123456789012:role/TestRole".to_string(), + ), + ("aws_access_key_id".to_string(), "AKIATESTKEY".to_string()), + ( + "aws_secret_access_key".to_string(), + "TestSecretKey".to_string(), + ), + ("sts_endpoint_url".to_string(), mock_server.uri()), + ]), + secret_material_keys: vec!["aws_secret_access_key".to_string()], + expires_at_ms: 0, + token_url: String::new(), + scopes: Vec::new(), + refresh_before_seconds: 300, + max_lifetime_seconds: 3600, + }, + ) + .unwrap(); + put_refresh_state(&store, &state).await.unwrap(); + + let rotate = refresh_provider_credential(&store, "aws-race", "AWS_ACCESS_KEY_ID"); + let interfere = async { + // Wait until the rotation is inside the STS call (its state read has + // already happened), then delete the refresh and release STS. + if tokio::time::timeout(std::time::Duration::from_secs(15), hit_rx) + .await + .is_err() + { + return; + } + delete_refresh_state(&store, &provider_id, "AWS_ACCESS_KEY_ID") + .await + .unwrap(); + let _ = release_tx.send(()); + }; + let (rotate_result, ()) = tokio::join!(rotate, interfere); + + // The rotation must fail rather than complete against a deleted refresh. + assert!( + rotate_result.is_err(), + "rotation should abort when its refresh is deleted mid-flight" + ); + // The deleted refresh state must not be resurrected. + assert!( + get_refresh_state(&store, &provider_id, "AWS_ACCESS_KEY_ID") + .await + .unwrap() + .is_none(), + "deleted refresh state must not be recreated" + ); + // No credentials were minted into the provider. + let stored = store + .get_message_by_name::("aws-race") + .await + .unwrap() + .unwrap(); + assert!(!stored.credentials.contains_key("AWS_ACCESS_KEY_ID")); + assert!(!stored.credentials.contains_key("AWS_SECRET_ACCESS_KEY")); + assert!(!stored.credentials.contains_key("AWS_SESSION_TOKEN")); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn rotation_superseded_mid_flight_discards_credentials() { + let mock_server = MockServer::start().await; + let (hit_tx, hit_rx) = tokio::sync::oneshot::channel::<()>(); + let (release_tx, release_rx) = std::sync::mpsc::channel::<()>(); + Mock::given(method("POST")) + .and(body_string_contains("Action=AssumeRole")) + .respond_with(GatedStsResponder { + hit: std::sync::Mutex::new(Some(hit_tx)), + release: std::sync::Mutex::new(release_rx), + body: r#" + + + ASIAMOCKKEY + MockSecretAccessKey123 + MockSessionTokenXYZ + 2099-01-01T00:00:00Z + + +"# + .to_string(), + }) + .mount(&mock_server) + .await; + + let store = test_store().await; + crate::grpc::policy::set_global_bool_setting_for_test( + &store, + openshell_core::settings::PROVIDERS_V2_ENABLED_KEY, + true, + ) + .await + .unwrap(); + let prov = provider("aws-superseded", "aws"); + store.put_message(&prov).await.unwrap(); + let provider_id = prov.object_id().to_string(); + + let state = new_refresh_state( + &prov, + "AWS_ACCESS_KEY_ID", + NewRefreshStateConfig { + additional_output_keys: HashMap::from([ + ( + "secret_access_key".to_string(), + "AWS_SECRET_ACCESS_KEY".to_string(), + ), + ("session_token".to_string(), "AWS_SESSION_TOKEN".to_string()), + ]), + strategy: ProviderCredentialRefreshStrategy::AwsStsAssumeRole, + material: HashMap::from([ + ( + "role_arn".to_string(), + "arn:aws:iam::123456789012:role/TestRole".to_string(), + ), + ("aws_access_key_id".to_string(), "AKIATESTKEY".to_string()), + ( + "aws_secret_access_key".to_string(), + "TestSecretKey".to_string(), + ), + ("sts_endpoint_url".to_string(), mock_server.uri()), + ]), + secret_material_keys: vec!["aws_secret_access_key".to_string()], + expires_at_ms: 0, + token_url: String::new(), + scopes: Vec::new(), + refresh_before_seconds: 300, + max_lifetime_seconds: 3600, + }, + ) + .unwrap(); + put_refresh_state(&store, &state).await.unwrap(); + + let rotate = refresh_provider_credential(&store, "aws-superseded", "AWS_ACCESS_KEY_ID"); + let interfere = async { + if tokio::time::timeout(std::time::Duration::from_secs(15), hit_rx) + .await + .is_err() + { + return; + } + // Simulate a concurrent rotation or reconfigure winning the + // generation: any write to the refresh state bumps its version, so + // the in-flight rotation's version-matched persist will lose. + let mut winner = get_refresh_state(&store, &provider_id, "AWS_ACCESS_KEY_ID") + .await + .unwrap() + .unwrap(); + winner.last_error = "won-by-concurrent-writer".to_string(); + put_refresh_state(&store, &winner).await.unwrap(); + let _ = release_tx.send(()); + }; + let (rotate_result, ()) = tokio::join!(rotate, interfere); + + // The superseded (losing) rotation must abort rather than complete. + assert!( + rotate_result.is_err(), + "a rotation whose generation was superseded must abort" + ); + // It must not write its stale-generation credentials into the provider. + let stored = store + .get_message_by_name::("aws-superseded") + .await + .unwrap() + .unwrap(); + assert!(!stored.credentials.contains_key("AWS_ACCESS_KEY_ID")); + assert!(!stored.credentials.contains_key("AWS_SECRET_ACCESS_KEY")); + assert!(!stored.credentials.contains_key("AWS_SESSION_TOKEN")); + // The concurrent writer's refresh state must survive untouched. + let refresh = get_refresh_state(&store, &provider_id, "AWS_ACCESS_KEY_ID") + .await + .unwrap() + .expect("refresh state should still exist"); + assert_eq!(refresh.last_error, "won-by-concurrent-writer"); + assert_ne!(refresh.status, "refreshed"); + } + fn provider(name: &str, provider_type: &str) -> Provider { Provider { metadata: Some(ObjectMeta { diff --git a/crates/openshell-supervisor-network/src/l7/mod.rs b/crates/openshell-supervisor-network/src/l7/mod.rs index d10c19b8e8..005e37ff6e 100644 --- a/crates/openshell-supervisor-network/src/l7/mod.rs +++ b/crates/openshell-supervisor-network/src/l7/mod.rs @@ -455,18 +455,26 @@ fn validate_host_wildcard(errors: &mut Vec, loc: &str, host: &str) { let labels: Vec<&str> = host.split('.').collect(); let first_label = labels.first().copied().unwrap_or_default(); - if labels.iter().skip(1).any(|label| label.contains('*')) { - errors.push(format!( - "{loc}: host wildcard may only appear in the first DNS label, got '{host}'" - )); - return; - } if first_label.contains("**") && first_label != "**" { errors.push(format!( "{loc}: recursive host wildcard '**' is only allowed as the entire first DNS label, got '{host}'" )); return; } + for label in labels.iter().skip(1).copied() { + if label.contains("**") { + errors.push(format!( + "{loc}: recursive host wildcard '**' is only allowed as the entire first DNS label, got '{host}'" + )); + return; + } + if label.contains('*') && label != "*" { + errors.push(format!( + "{loc}: middle DNS label wildcard must be the entire label '*', got '{host}'" + )); + return; + } + } // Reject TLD or single-label wildcards. They are accepted by the policy // engine but silently fail at the proxy layer (see #787). @@ -2877,12 +2885,36 @@ mod tests { } #[test] - fn validate_wildcard_host_mid_label_error() { + fn validate_wildcard_host_middle_label_star_valid_no_error() { + let data = serde_json::json!({ + "network_policies": { + "test": { + "endpoints": [{ + "host": "*.s3.*.amazonaws.com", + "port": 443 + }], + "binaries": [] + } + } + }); + let (errors, warnings) = validate_l7_policies(&data); + assert!( + errors.is_empty(), + "*.s3.*.amazonaws.com should be valid, got errors: {errors:?}" + ); + assert!( + warnings.is_empty(), + "*.s3.*.amazonaws.com should not warn, got warnings: {warnings:?}" + ); + } + + #[test] + fn validate_wildcard_host_middle_label_partial_star_error() { let data = serde_json::json!({ "network_policies": { "test": { "endpoints": [{ - "host": "foo.*.example.com", + "host": "*.s3.us-*.amazonaws.com", "port": 443 }], "binaries": [] @@ -2891,8 +2923,30 @@ mod tests { }); let (errors, _warnings) = validate_l7_policies(&data); assert!( - errors.iter().any(|e| e.contains("first DNS label")), - "Mid-label wildcard should be rejected, got errors: {errors:?}" + errors + .iter() + .any(|e| e.contains("middle DNS label wildcard")), + "Partial middle-label wildcard should be rejected, got errors: {errors:?}" + ); + } + + #[test] + fn validate_wildcard_host_middle_label_double_star_error() { + let data = serde_json::json!({ + "network_policies": { + "test": { + "endpoints": [{ + "host": "*.s3.**.amazonaws.com", + "port": 443 + }], + "binaries": [] + } + } + }); + let (errors, _warnings) = validate_l7_policies(&data); + assert!( + errors.iter().any(|e| e.contains("recursive host wildcard")), + "Middle-label ** wildcard should be rejected, got errors: {errors:?}" ); } diff --git a/crates/openshell-supervisor-network/src/l7/rest.rs b/crates/openshell-supervisor-network/src/l7/rest.rs index 5c62f6f9ee..99f2f328eb 100644 --- a/crates/openshell-supervisor-network/src/l7/rest.rs +++ b/crates/openshell-supervisor-network/src/l7/rest.rs @@ -560,11 +560,21 @@ where // route chunked requests to the streaming path, but // guard here as defense-in-depth. let body_length = parse_body_length(header_str)?; - if matches!(body_length, BodyLength::Chunked) { - return Err(miette!( - "SigV4 body signing requires Content-Length; \ - chunked transfer encoding is not supported in this mode" - )); + match body_length { + BodyLength::ContentLength(_) | BodyLength::None => { + // ContentLength: buffer and sign the body. + // None: no body (e.g. GET/HEAD/DELETE) — sign + // with the empty-body hash. boto3 sends + // x-amz-content-sha256 set to the SHA-256 of + // "" on all requests, which routes here via + // detect_payload_mode's catch-all. + } + BodyLength::Chunked => { + return Err(miette!( + "SigV4 body signing requires Content-Length; \ + chunked transfer encoding is not supported in this mode" + )); + } } // NOTE(defense-in-depth): Build the full request from // rewritten headers + body. `rewrite_result.rewritten` @@ -5402,6 +5412,83 @@ mod tests { assert!(!forwarded.contains("openshell:resolve:env:")); } + #[tokio::test] + async fn relay_sigv4_body_signing_signs_empty_body_without_content_length() { + let (_, resolver) = SecretResolver::from_provider_env( + [ + ("AWS_ACCESS_KEY_ID".to_string(), "AKIATESTKEY".to_string()), + ( + "AWS_SECRET_ACCESS_KEY".to_string(), + "test-secret-key".to_string(), + ), + ] + .into_iter() + .collect(), + ); + let resolver = resolver.expect("resolver"); + + let raw_header = + b"GET /?list-type=2 HTTP/1.1\r\nHost: s3.us-east-1.amazonaws.com\r\n\r\n".to_vec(); + let req = L7Request { + action: "GET".to_string(), + target: "/".to_string(), + query_params: HashMap::from([("list-type".to_string(), vec!["2".to_string()])]), + raw_header, + body_length: BodyLength::None, + }; + let (mut proxy_to_upstream, mut upstream_side) = tokio::io::duplex(8192); + let (mut _app_side, mut proxy_to_client) = tokio::io::duplex(8192); + + let upstream_task = tokio::spawn(async move { + let mut buf = vec![0u8; 8192]; + let mut total = 0usize; + loop { + let n = upstream_side.read(&mut buf[total..]).await.unwrap(); + if n == 0 { + break; + } + total += n; + if buf[..total].windows(4).any(|w| w == b"\r\n\r\n") { + upstream_side + .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok") + .await + .unwrap(); + upstream_side.flush().await.unwrap(); + break; + } + } + String::from_utf8_lossy(&buf[..total]).to_string() + }); + + let relay_result = tokio::time::timeout( + std::time::Duration::from_secs(5), + relay_http_request_with_options_guarded( + &req, + &mut proxy_to_client, + &mut proxy_to_upstream, + RelayRequestOptions { + resolver: Some(&resolver), + credential_signing: crate::l7::CredentialSigning::SigV4Body, + signing_service: "s3", + signing_region: "us-east-1", + host: "s3.us-east-1.amazonaws.com", + port: 443, + ..Default::default() + }, + ), + ) + .await + .expect("relay must not deadlock"); + drop(proxy_to_upstream); + let forwarded = upstream_task.await.expect("upstream task should complete"); + + relay_result.expect("bodyless GET with SigV4Body should succeed"); + assert!( + forwarded.contains("authorization:"), + "forwarded request should have SigV4 authorization header: {forwarded}" + ); + } + #[tokio::test] async fn relay_injects_url_path_credential_telegram_style() { let (child_env, resolver) = SecretResolver::from_provider_env( diff --git a/crates/openshell-supervisor-network/src/opa.rs b/crates/openshell-supervisor-network/src/opa.rs index 829c63caa4..935946920d 100644 --- a/crates/openshell-supervisor-network/src/opa.rs +++ b/crates/openshell-supervisor-network/src/opa.rs @@ -5804,6 +5804,88 @@ network_policies: ); } + #[test] + fn wildcard_host_middle_label_matches_one_region_label() { + let data = r#" +network_policies: + s3: + name: s3 + endpoints: + - { host: "*.s3.*.amazonaws.com", port: 443 } + binaries: + - { path: /usr/bin/curl } +"#; + let engine = OpaEngine::from_strings(TEST_POLICY, data).unwrap(); + let input = NetworkInput { + host: "my-bucket.s3.us-east-1.amazonaws.com".into(), + port: 443, + binary_path: PathBuf::from("/usr/bin/curl"), + binary_sha256: "unused".into(), + ancestors: vec![], + cmdline_paths: vec![], + }; + let decision = engine.evaluate_network(&input).unwrap(); + assert!( + decision.allowed, + "*.s3.*.amazonaws.com should match one regional S3 label: {}", + decision.reason + ); + } + + #[test] + fn wildcard_host_middle_label_does_not_match_missing_bucket_label() { + let data = r#" +network_policies: + s3: + name: s3 + endpoints: + - { host: "*.s3.*.amazonaws.com", port: 443 } + binaries: + - { path: /usr/bin/curl } +"#; + let engine = OpaEngine::from_strings(TEST_POLICY, data).unwrap(); + let input = NetworkInput { + host: "s3.us-east-1.amazonaws.com".into(), + port: 443, + binary_path: PathBuf::from("/usr/bin/curl"), + binary_sha256: "unused".into(), + ancestors: vec![], + cmdline_paths: vec![], + }; + let decision = engine.evaluate_network(&input).unwrap(); + assert!( + !decision.allowed, + "*.s3.*.amazonaws.com should not match path-style S3 host" + ); + } + + #[test] + fn wildcard_host_middle_label_does_not_skip_dualstack_label() { + let data = r#" +network_policies: + s3: + name: s3 + endpoints: + - { host: "*.s3.*.amazonaws.com", port: 443 } + binaries: + - { path: /usr/bin/curl } +"#; + let engine = OpaEngine::from_strings(TEST_POLICY, data).unwrap(); + let input = NetworkInput { + host: "my-bucket.s3.dualstack.us-east-1.amazonaws.com".into(), + port: 443, + binary_path: PathBuf::from("/usr/bin/curl"), + binary_sha256: "unused".into(), + ancestors: vec![], + cmdline_paths: vec![], + }; + let decision = engine.evaluate_network(&input).unwrap(); + assert!( + !decision.allowed, + "*.s3.*.amazonaws.com should not match the extra dualstack label" + ); + } + #[test] fn wildcard_host_multi_port() { let data = r#" diff --git a/crates/openshell-tui/src/app.rs b/crates/openshell-tui/src/app.rs index f8ebe49895..e5ef60c95a 100644 --- a/crates/openshell-tui/src/app.rs +++ b/crates/openshell-tui/src/app.rs @@ -751,6 +751,9 @@ fn refresh_strategy_label(strategy: i32) -> &'static str { openshell_core::proto::ProviderCredentialRefreshStrategy::GoogleServiceAccountJwt => { "google_service_account_jwt" } + openshell_core::proto::ProviderCredentialRefreshStrategy::AwsStsAssumeRole => { + "aws_sts_assume_role" + } openshell_core::proto::ProviderCredentialRefreshStrategy::Unspecified => "unspecified", } } diff --git a/docs/providers/aws-sigv4.mdx b/docs/providers/aws-sigv4.mdx index fc5e02040b..61465fa1b8 100644 --- a/docs/providers/aws-sigv4.mdx +++ b/docs/providers/aws-sigv4.mdx @@ -35,6 +35,12 @@ openshell provider create \ --credential AWS_SESSION_TOKEN=FwoGZX... ``` +To have the gateway mint and rotate STS credentials for you instead of supplying +them statically, use the `aws` or `aws-s3` profile with the `aws_sts_assume_role` +refresh strategy. A single `sts:AssumeRole` mints all three env vars +(`AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_SESSION_TOKEN`) that the +signer reads. See [Manage Providers](/sandboxes/manage-providers#aws-sts). + ## Policy Configuration Enable SigV4 signing on a per-endpoint basis using three policy fields: diff --git a/docs/sandboxes/manage-providers.mdx b/docs/sandboxes/manage-providers.mdx index 1324859ed7..d639c37acb 100644 --- a/docs/sandboxes/manage-providers.mdx +++ b/docs/sandboxes/manage-providers.mdx @@ -135,9 +135,9 @@ Use `0` as the timestamp to clear expiry for a credential key. Provider refresh stores non-injectable refresh material separately from the provider's current credential values. The gateway can mint OAuth2 refresh-token -tokens, OAuth2 client credentials tokens, and Google service account JWT tokens, -then write the current access token back to the provider record for sandbox -injection. +tokens, OAuth2 client credentials tokens, Google service account JWT tokens, and +AWS STS temporary credentials, then write the current access token back to the +provider record for sandbox injection. Configure refresh metadata for one injectable credential key: @@ -177,6 +177,57 @@ Force a gateway-managed refresh for one credential: openshell provider refresh rotate my-graph --credential-key MS_GRAPH_ACCESS_TOKEN ``` +### AWS STS + +AWS STS refresh requires `providers_v2_enabled=true`. The gateway calls +`sts:AssumeRole` and writes three short-lived credentials (`AWS_ACCESS_KEY_ID`, +`AWS_SECRET_ACCESS_KEY`, `AWS_SESSION_TOKEN`) to the provider record atomically. +The `aws` and `aws-s3` profiles declare `AWS_SECRET_ACCESS_KEY` and +`AWS_SESSION_TOKEN` as `additional_outputs` of the `AWS_ACCESS_KEY_ID` refresh, +so all three credentials are gateway-minted. Create the provider with +`--runtime-credentials` — no placeholder credential is needed. + +```shell +openshell settings set --global --key providers_v2_enabled --value true --yes + +openshell provider create --name my-aws --type aws-s3 --runtime-credentials + +openshell provider refresh configure my-aws \ + --credential-key AWS_ACCESS_KEY_ID \ + --strategy aws-sts-assume-role \ + --material role_arn="arn:aws:iam::123456789012:role/SandboxS3Writer" \ + --material session_name="openshell-sandbox" + +openshell provider refresh rotate my-aws --credential-key AWS_ACCESS_KEY_ID +``` + +The gateway resolves its own AWS credentials using the default credential chain +(instance role, IRSA, ECS task role, environment variables). For gateways not +running on AWS, provide explicit IAM keys via refresh material: + +```shell +openshell provider refresh configure my-aws \ + --credential-key AWS_ACCESS_KEY_ID \ + --strategy aws-sts-assume-role \ + --material role_arn="arn:aws:iam::123456789012:role/SandboxS3Writer" \ + --material aws_access_key_id="$AWS_ACCESS_KEY_ID" \ + --secret-material-env aws_secret_access_key=AWS_SECRET_ACCESS_KEY +``` + +Pass the long-lived secret with `--secret-material-env` so the CLI reads it +from its own environment instead of expanding it into a process argument, +where it would be visible in the host process table. + +For temporary source credentials (AWS SSO or a prior `AssumeRole`), also pass a +session token with `--secret-material-env aws_session_token=AWS_SESSION_TOKEN`. +It requires the `aws_access_key_id` and `aws_secret_access_key` pair. + +Use the generic `aws` profile type for multi-service access and scope endpoints +via sandbox network policy. Use `aws-s3` for S3-specific endpoint rules. + +The proxy re-signs requests using SigV4 before forwarding to AWS. Both curl and +Python boto3 are supported. + External refresh systems should continue to push new current credentials through `openshell provider update`. The `--credential-expires-at` option works for static credentials, externally refreshed credentials, and gateway-managed diff --git a/docs/sandboxes/providers-v2.mdx b/docs/sandboxes/providers-v2.mdx index c3c84b8383..a8890f9f8b 100644 --- a/docs/sandboxes/providers-v2.mdx +++ b/docs/sandboxes/providers-v2.mdx @@ -311,8 +311,9 @@ Profile YAML can declare these refresh strategies: | `oauth2_refresh_token` | The gateway exchanges a refresh token for a short-lived access token. | | `oauth2_client_credentials` | The gateway mints a short-lived access token with OAuth2 client credentials. | | `google_service_account_jwt` | The gateway signs a Google service account JWT and exchanges it for an access token. | +| `aws_sts_assume_role` | The gateway calls `sts:AssumeRole` and mints `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and `AWS_SESSION_TOKEN` in one operation. Requires `providers_v2_enabled=true`. | -`openshell provider refresh configure` accepts only gateway-mintable strategies: `oauth2-refresh-token`, `oauth2-client-credentials`, and `google-service-account-jwt`. Use `openshell provider update` for `static` and `external` refresh patterns. +`openshell provider refresh configure` accepts only gateway-mintable strategies: `oauth2-refresh-token`, `oauth2-client-credentials`, `google-service-account-jwt`, and `aws-sts-assume-role`. Use `openshell provider update` for `static` and `external` refresh patterns. Gateway-managed refresh strategies use these material keys: @@ -321,9 +322,36 @@ Gateway-managed refresh strategies use these material keys: | `oauth2_refresh_token` | `client_id`, `refresh_token`, optional `client_secret`. | | `oauth2_client_credentials` | `client_id`, `client_secret`, optional `tenant_id` for Microsoft Entra token URLs. | | `google_service_account_jwt` | `client_email`, `private_key`, optional `subject` or `sub`. | +| `aws_sts_assume_role` | `role_arn`, optional `session_name`, `external_id`, `aws_region`, and optional long-lived `aws_access_key_id` / `aws_secret_access_key` for gateways without ambient AWS credentials. | OpenShell keeps token endpoints profile-owned. Refresh material cannot override `token_url` or `token_uri` during refresh configuration. +### Additional Outputs + +Most refresh strategies mint a single credential. `aws_sts_assume_role` mints three. A refresh declares the extra credentials it co-mints with `additional_outputs`, mapping each strategy-defined output id to a sibling credential whose `env_vars` receive the value: + +```yaml +credentials: + - name: access_key_id + env_vars: [AWS_ACCESS_KEY_ID] + required: true + refresh: + strategy: aws_sts_assume_role + additional_outputs: + - output: secret_access_key + credential: secret_access_key + - output: session_token + credential: session_token + - name: secret_access_key + env_vars: [AWS_SECRET_ACCESS_KEY] + required: true + - name: session_token + env_vars: [AWS_SESSION_TOKEN] + required: true +``` + +The refresh attaches to the primary credential (`access_key_id`). Each referenced sibling must exist, declare exactly one env var, and not carry its own refresh. Because a refresh's outputs are runtime-resolvable, a profile whose only credentials are STS-minted can be created with `--runtime-credentials`. The resolved output-to-env-key mapping is pinned when refresh is configured, so later profile edits do not silently redirect where minted values are written. + ### Dynamic Token Grants `token_grant` belongs to one credential declaration. When a sandbox with the provider attached sends HTTP traffic to a matching profile endpoint, the supervisor requests a SPIFFE JWT-SVID from the local Workload API, exchanges it at `token_endpoint`, caches the returned access token, and injects it before forwarding the request upstream. Use `auth_style: bearer` to inject `Authorization: Bearer `, or `auth_style: header` with `header_name` to inject the raw access token into a custom header. Token grants do not support `query` or `path` placement. diff --git a/examples/aws-s3-sts.md b/examples/aws-s3-sts.md new file mode 100644 index 0000000000..e622e71117 --- /dev/null +++ b/examples/aws-s3-sts.md @@ -0,0 +1,278 @@ +# Manual E2E Test: S3 Access via STS Credentials + +This guide walks through an end-to-end test of an OpenShell sandbox accessing +AWS S3 using gateway-minted STS temporary credentials with proxy-side SigV4 +re-signing. The sandbox never sees real AWS credentials — the proxy resolves +placeholders and signs requests on the fly. + +## Prerequisites + +- AWS CLI authenticated (`aws sts get-caller-identity` succeeds) +- Podman running (`podman info` succeeds) +- OpenShell built from source with AWS STS refresh and SigV4 signing support + +## 1. Create AWS test resources + +Create an S3 bucket and an IAM role the gateway can assume: + +```shell +BUCKET="openshell-sts-test-$(date +%s)" +ACCOUNT=$(aws sts get-caller-identity --query Account --output text) + +aws s3 mb "s3://${BUCKET}" --region us-east-1 + +aws iam create-role \ + --role-name openshell-sts-test-role \ + --assume-role-policy-document '{ + "Version": "2012-10-17", + "Statement": [{ + "Effect": "Allow", + "Principal": {"AWS": "arn:aws:iam::'${ACCOUNT}':root"}, + "Action": "sts:AssumeRole" + }] + }' + +aws iam put-role-policy \ + --role-name openshell-sts-test-role \ + --policy-name s3-access \ + --policy-document '{ + "Version": "2012-10-17", + "Statement": [{ + "Effect": "Allow", + "Action": ["s3:PutObject", "s3:GetObject", "s3:ListBucket"], + "Resource": ["arn:aws:s3:::'${BUCKET}'", "arn:aws:s3:::'${BUCKET}'/*"] + }] + }' +``` + +Verify the role works: + +```shell +aws sts assume-role \ + --role-arn "arn:aws:iam::${ACCOUNT}:role/openshell-sts-test-role" \ + --role-session-name test \ + --query Credentials.AccessKeyId --output text +``` + +## 2. Build the supervisor image + +The supervisor image must include the SigV4 re-signing code and the updated +proto definitions. Build it from the branch: + +```shell +CONTAINER_ENGINE=podman IMAGE_TAG=dev mise run build:docker:supervisor +``` + +Verify the image exists locally: + +```shell +podman images | grep "openshell/supervisor.*dev" +``` + +## 3. Start the gateway + +The gateway needs AWS credentials in its environment to call `sts:AssumeRole`. +Export them before starting: + +```shell +eval "$(aws configure export-credentials --format env)" +``` + +The gateway must use the locally built supervisor image. The `mise run gateway` +script places `supervisor_image` in the wrong TOML section, so start the gateway +binary directly with a hand-written config. + +Write `.cache/gateway-podman/gateway.toml` in the repo root (adjust JWT paths +if your gateway cache directory differs): + +```toml +[openshell] +version = 1 + +[openshell.gateway] +compute_drivers = ["podman"] +default_image = "ghcr.io/nvidia/openshell-community/sandboxes/base:latest" +disable_tls = true +supervisor_image = "localhost/openshell/supervisor:dev" + +[openshell.gateway.auth] +allow_unauthenticated_users = true + +[openshell.gateway.gateway_jwt] +signing_key_path = ".cache/gateway-podman/tls/jwt/signing.pem" +public_key_path = ".cache/gateway-podman/tls/jwt/public.pem" +kid_path = ".cache/gateway-podman/tls/jwt/kid" +gateway_id = "podman-dev" +ttl_secs = 3600 + +[openshell.drivers.podman] +image_pull_policy = "missing" +``` + +If the JWT key files do not exist yet, run `mise run gateway` once to generate +them, then stop the gateway and restart with the config above. + +Start the gateway: + +```shell +eval "$(aws configure export-credentials --format env)" +./target/debug/openshell-gateway \ + --config .cache/gateway-podman/gateway.toml \ + --port 18080 --log-level info --drivers podman --disable-tls \ + --db-url "sqlite:.cache/gateway-podman/gateway.db?mode=rwc" +``` + +## 4. Configure the provider + +In a separate terminal: + +```shell +export OPENSHELL_BASE_URL=http://localhost:18080 + +# Enable provider v2 (required for STS) +openshell settings set --global --key providers_v2_enabled --value true --yes + +# Create the provider with the aws-s3 profile. All three credentials are +# gateway-minted via STS, so no static credential is needed. +openshell provider create --name s3-test --type aws-s3 --runtime-credentials + +# Configure STS refresh +openshell provider refresh configure s3-test \ + --credential-key AWS_ACCESS_KEY_ID \ + --strategy aws-sts-assume-role \ + --material role_arn="arn:aws:iam::${ACCOUNT}:role/openshell-sts-test-role" \ + --material session_name="openshell-sandbox" \ + --material aws_region="us-east-1" + +# Mint the first set of credentials +openshell provider refresh rotate s3-test \ + --credential-key AWS_ACCESS_KEY_ID + +# Verify +openshell provider refresh status s3-test +``` + +The status should show `refreshed` with an expiry ~1 hour from now. + +## 5. Test S3 access from a sandbox + +### Using boto3 (Python) + +boto3 is not in the base sandbox image, and the `aws-s3` profile allows only S3 +egress. Attach the built-in `pypi` profile so `pip` can reach PyPI (or bake +boto3 into a custom sandbox image): + +```shell +openshell provider create --name pypi --type pypi --runtime-credentials + +openshell sandbox create --name s3-smoke \ + --provider s3-test \ + --provider pypi \ + -- bash -c ' +export AWS_CA_BUNDLE=/etc/openshell-tls/ca-bundle.pem +pip install boto3 -q 2>&1 | tail -1 +python3 -c " +import boto3 + +s3 = boto3.client(\"s3\", region_name=\"us-east-1\") + +print(\"Upload...\") +s3.put_object( + Bucket=\"'"${BUCKET}"'\", + Key=\"from-sandbox.txt\", + Body=b\"hello from openshell sandbox via STS\" +) +print(\"OK\") + +print(\"List...\") +resp = s3.list_objects_v2(Bucket=\"'"${BUCKET}"'\", MaxKeys=5) +for obj in resp.get(\"Contents\", []): + print(\" \" + obj[\"Key\"] + \" (\" + str(obj[\"Size\"]) + \" bytes)\") + +print(\"Download...\") +body = s3.get_object( + Bucket=\"'"${BUCKET}"'\", + Key=\"from-sandbox.txt\" +)[\"Body\"].read() +print(body.decode()) +" +' +``` + +All three operations should succeed. The download should print +`hello from openshell sandbox via STS`. + +### Using curl + +```shell +openshell sandbox create --name s3-curl \ + --provider s3-test \ + -- bash -c ' +BUCKET="'"${BUCKET}"'" +REGION="us-east-1" +CA=/etc/openshell-tls/ca-bundle.pem + +echo "=== Upload ===" +curl -s --cacert $CA -X PUT -H "Content-Type: text/plain" \ + -d "hello from openshell sandbox via STS" \ + "https://${BUCKET}.s3.${REGION}.amazonaws.com/from-sandbox.txt" \ + -w "HTTP %{http_code}\n" + +echo "" +echo "=== Download ===" +curl -s --cacert $CA \ + "https://${BUCKET}.s3.${REGION}.amazonaws.com/from-sandbox.txt" \ + -w "\nHTTP %{http_code}\n" +' +``` + +Both operations should return `HTTP 200`. + +### What's happening + +1. The gateway called `sts:AssumeRole` and stored three short-lived credentials + (`AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_SESSION_TOKEN`) in the + provider record. +2. The sandbox received placeholder values for these credentials as environment + variables. +3. The client (boto3 or curl) sent an HTTP request through the sandbox proxy's + CONNECT tunnel. boto3 signs the request with placeholder credentials; curl + sends unsigned requests. Either way, the proxy handles it. +4. The proxy terminated TLS, stripped any existing AWS auth headers, resolved + the real credentials from the `SecretResolver`, computed a fresh SigV4 + signature using the `aws-sigv4` crate, and forwarded the signed request to + S3. +5. S3 validated the signature and accepted the request. + +The sandbox never saw real AWS credentials — only placeholders. + +### TLS CA trust + +The proxy terminates TLS and presents a certificate signed by the OpenShell +Sandbox CA. Curl needs `--cacert /etc/openshell-tls/ca-bundle.pem` to trust +it. Python clients need `AWS_CA_BUNDLE=/etc/openshell-tls/ca-bundle.pem` set +in the environment. + +## 6. Clean up + +```shell +# Delete the sandboxes and the pypi provider +openshell sandbox delete s3-smoke +openshell sandbox delete s3-curl +openshell provider delete pypi + +# Delete AWS resources +aws s3 rb "s3://${BUCKET}" --force +aws iam delete-role-policy --role-name openshell-sts-test-role --policy-name s3-access +aws iam delete-role --role-name openshell-sts-test-role +``` + +## Troubleshooting + +| Symptom | Cause | Fix | +|---------|-------|-----| +| `STS AssumeRole failed: dispatch failure` | Gateway doesn't have AWS credentials | Export credentials before starting: `eval "$(aws configure export-credentials --format env)"` | +| `Policy discovery sync failed: invalid wire type` | Supervisor image doesn't have updated proto | Rebuild: `CONTAINER_ENGINE=podman IMAGE_TAG=dev mise run build:docker:supervisor` | +| `CONNECT ... not permitted by policy` | Binary not in profile's `binaries` list | Use curl (in the list) or add your binary path to the policy | +| `403 AccessDenied` from S3 | IAM role missing permissions, or STS creds expired | Check `openshell provider refresh status`; re-rotate if expired | +| Supervisor uses wrong image | `mise run gateway` places `supervisor_image` in wrong TOML section | Use the hand-written config from step 3 instead of `mise run gateway` | diff --git a/proto/openshell.proto b/proto/openshell.proto index b437613b04..710cb2d8f6 100644 --- a/proto/openshell.proto +++ b/proto/openshell.proto @@ -1014,6 +1014,7 @@ enum ProviderCredentialRefreshStrategy { PROVIDER_CREDENTIAL_REFRESH_STRATEGY_OAUTH2_REFRESH_TOKEN = 3; PROVIDER_CREDENTIAL_REFRESH_STRATEGY_OAUTH2_CLIENT_CREDENTIALS = 4; PROVIDER_CREDENTIAL_REFRESH_STRATEGY_GOOGLE_SERVICE_ACCOUNT_JWT = 5; + PROVIDER_CREDENTIAL_REFRESH_STRATEGY_AWS_STS_ASSUME_ROLE = 6; } message ProviderCredentialRefreshMaterial { @@ -1023,6 +1024,15 @@ message ProviderCredentialRefreshMaterial { bool secret = 4; } +// Declares that a single refresh operation mints more than one credential. +// The refresh is attached to a primary credential; each additional output +// maps a strategy-defined semantic output id to a sibling credential whose +// env_vars receive the minted value. +message ProviderCredentialRefreshOutput { + string output = 1; // strategy-defined semantic output id (e.g. "session_token") + string credential = 2; // sibling credential name whose env_vars receive this output +} + message ProviderCredentialRefresh { ProviderCredentialRefreshStrategy strategy = 1; string token_url = 2; @@ -1030,6 +1040,7 @@ message ProviderCredentialRefresh { int64 refresh_before_seconds = 4; int64 max_lifetime_seconds = 5; repeated ProviderCredentialRefreshMaterial material = 6; + repeated ProviderCredentialRefreshOutput additional_outputs = 7; } message ProviderCredentialRefreshStatus { @@ -1067,6 +1078,11 @@ message StoredProviderCredentialRefreshState { repeated string scopes = 14; int64 refresh_before_seconds = 15; int64 max_lifetime_seconds = 16; + // Resolved mapping of strategy-defined output id -> concrete env key, pinned + // at configure time from the profile's additional_outputs. Read by minting, + // collision reservation, and env-key surfacing so later profile edits cannot + // silently redirect writes. + map additional_output_keys = 17; } message GetProviderRefreshStatusRequest { diff --git a/providers/aws-s3.yaml b/providers/aws-s3.yaml new file mode 100644 index 0000000000..699f067ff1 --- /dev/null +++ b/providers/aws-s3.yaml @@ -0,0 +1,124 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +id: aws-s3 +display_name: AWS S3 +description: AWS S3 storage via STS temporary credentials +category: other +credentials: + - name: access_key_id + description: AWS access key ID (gateway-minted via STS) + env_vars: [AWS_ACCESS_KEY_ID] + required: true + refresh: + strategy: aws_sts_assume_role + refresh_before_seconds: 300 + max_lifetime_seconds: 3600 + # One AssumeRole call mints all three AWS credentials. The refresh is + # attached to access_key_id (primary); these outputs co-manage the + # secret key and session token on their sibling credentials. + additional_outputs: + - output: secret_access_key + credential: secret_access_key + - output: session_token + credential: session_token + material: + - name: role_arn + description: ARN of the IAM role to assume + required: true + secret: false + - name: session_name + description: Session name for CloudTrail attribution + required: false + secret: false + - name: external_id + description: External ID for cross-account role assumption + required: false + secret: false + - name: aws_region + description: AWS region for STS endpoint + required: false + secret: false + - name: aws_access_key_id + description: Long-lived IAM access key (only needed if gateway lacks ambient AWS credentials) + required: false + secret: false + - name: aws_secret_access_key + description: Long-lived IAM secret key (only needed if gateway lacks ambient AWS credentials) + required: false + secret: true + - name: aws_session_token + description: Session token for temporary source credentials (SSO or a prior AssumeRole); requires the access/secret pair + required: false + secret: true + - name: secret_access_key + description: AWS secret access key (co-managed with access_key_id) + env_vars: [AWS_SECRET_ACCESS_KEY] + required: true + - name: session_token + description: AWS session token (co-managed with access_key_id) + env_vars: [AWS_SESSION_TOKEN] + required: true +endpoints: + # S3 regional endpoints. `*` matches exactly one DNS label, so the region + # wildcard does not cover extra labels like dualstack unless listed. + # us-east-1 uses the global endpoint without a region label. + - host: "*.s3.amazonaws.com" + port: 443 + protocol: rest + tls: terminate + access: read-write + enforcement: enforce + credential_signing: sigv4 + signing_service: s3 + signing_region: us-east-1 + - host: "s3.amazonaws.com" + port: 443 + protocol: rest + tls: terminate + access: read-write + enforcement: enforce + credential_signing: sigv4 + signing_service: s3 + signing_region: us-east-1 + - host: "*.s3.*.amazonaws.com" + port: 443 + protocol: rest + tls: terminate + access: read-write + enforcement: enforce + credential_signing: sigv4 + signing_service: s3 + - host: "s3.*.amazonaws.com" + port: 443 + protocol: rest + tls: terminate + access: read-write + enforcement: enforce + credential_signing: sigv4 + signing_service: s3 + - host: "*.s3.dualstack.*.amazonaws.com" + port: 443 + protocol: rest + tls: terminate + access: read-write + enforcement: enforce + credential_signing: sigv4 + signing_service: s3 + - host: "s3.dualstack.*.amazonaws.com" + port: 443 + protocol: rest + tls: terminate + access: read-write + enforcement: enforce + credential_signing: sigv4 + signing_service: s3 +binaries: + - /sandbox/.venv/bin/python + - /sandbox/.venv/bin/python3 + - /sandbox/.uv/python/** + - /usr/bin/python3 + - /usr/bin/python3.* + - /usr/bin/curl + - /usr/local/bin/aws + - /bin/bash diff --git a/providers/aws.yaml b/providers/aws.yaml new file mode 100644 index 0000000000..90f13765f0 --- /dev/null +++ b/providers/aws.yaml @@ -0,0 +1,61 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +id: aws +display_name: AWS +description: Generic AWS access via STS temporary credentials +category: other +credentials: + - name: access_key_id + description: AWS access key ID (gateway-minted via STS) + env_vars: [AWS_ACCESS_KEY_ID] + required: true + refresh: + strategy: aws_sts_assume_role + refresh_before_seconds: 300 + max_lifetime_seconds: 3600 + # One AssumeRole call mints all three AWS credentials. The refresh is + # attached to access_key_id (primary); these outputs co-manage the + # secret key and session token on their sibling credentials. + additional_outputs: + - output: secret_access_key + credential: secret_access_key + - output: session_token + credential: session_token + material: + - name: role_arn + description: ARN of the IAM role to assume + required: true + secret: false + - name: session_name + description: Session name for CloudTrail attribution + required: false + secret: false + - name: external_id + description: External ID for cross-account role assumption + required: false + secret: false + - name: aws_region + description: AWS region for STS endpoint + required: false + secret: false + - name: aws_access_key_id + description: Long-lived IAM access key (only needed if gateway lacks ambient AWS credentials) + required: false + secret: false + - name: aws_secret_access_key + description: Long-lived IAM secret key (only needed if gateway lacks ambient AWS credentials) + required: false + secret: true + - name: aws_session_token + description: Session token for temporary source credentials (SSO or a prior AssumeRole); requires the access/secret pair + required: false + secret: true + - name: secret_access_key + description: AWS secret access key (co-managed with access_key_id) + env_vars: [AWS_SECRET_ACCESS_KEY] + required: true + - name: session_token + description: AWS session token (co-managed with access_key_id) + env_vars: [AWS_SESSION_TOKEN] + required: true From 32f052442e3a8608c4457a03a3d5651e0d4384d5 Mon Sep 17 00:00:00 2001 From: Piotr Mlocek Date: Thu, 16 Jul 2026 15:52:20 -0700 Subject: [PATCH 2/5] rfc-0009: supervisor middleware (#1738) Signed-off-by: Piotr Mlocek --- rfc/0009-supervisor-middleware/README.md | 522 ++++++++++++++++++ .../appendices/deployment-options.md | 41 ++ .../appendices/protocol-extensions.md | 86 +++ 3 files changed, 649 insertions(+) create mode 100644 rfc/0009-supervisor-middleware/README.md create mode 100644 rfc/0009-supervisor-middleware/appendices/deployment-options.md create mode 100644 rfc/0009-supervisor-middleware/appendices/protocol-extensions.md diff --git a/rfc/0009-supervisor-middleware/README.md b/rfc/0009-supervisor-middleware/README.md new file mode 100644 index 0000000000..f43e05ed79 --- /dev/null +++ b/rfc/0009-supervisor-middleware/README.md @@ -0,0 +1,522 @@ +--- +authors: + - "@pimlock" +state: accepted +links: + - https://github.com/NVIDIA/OpenShell/issues/1043 + - https://github.com/NVIDIA/OpenShell/issues/1733 + - https://github.com/NVIDIA/OpenShell/issues/1734 + - https://github.com/NVIDIA/OpenShell/issues/1919 + - https://github.com/NVIDIA/OpenShell/issues/2010 + - https://github.com/NVIDIA/OpenShell/pull/2027 +--- + +# RFC 0009 - Supervisor Middleware + +## Summary + +This RFC proposes the introduction of supervisor middleware: a supervisor-side extension system for hooks that can inspect, transform, block, and annotate supervisor-managed operations at specific operation phases. The first hook family is supervisor egress middleware for outbound sandbox HTTP requests, but the framework is intentionally named and shaped so later supervisor hooks can cover other protocols or supervisor operations without renaming the feature. + +## Motivation + +OpenShell already controls *where* a sandbox can connect. The supervisor enforces network policy on every outbound connection and only allows egress to approved endpoints. Today, that control stops at the destination: once a connection is allowed, the request can carry any payload. Network policy can decide whether a sandbox may talk to `api.openai.com`, but it cannot decide whether a particular request to `api.openai.com` should be allowed based on what that request contains. + +Users have a need to control the content that leaves the sandbox. Agents routinely send prompts, tool arguments, uploaded files, which may contain sensitive information. Acting on that traffic, requires inspecting the request itself (e.g. redacting PII or secrets before they leave the sandbox, blocking requests that carry confidential documents, requiring sensitive content to be processed by a local model). + +This RFC introduces supervisor middleware and its first hook family, supervisor egress middleware: hooks that run within the supervisor proxy flow and can inspect, transform, block, and annotate outbound requests based on their content. Rather than building a fixed set of content checks into OpenShell, the middleware contract lets operators process selected requests through trusted services that implement their own logic. OpenShell cannot embed every useful detection and transformation approach. We want to allow dedicated PII tools such as Presidio or NeMo Anonymizer, organization-specific classifiers, and experimental research scanners to be plugged in. A stable contract lets teams and researchers iterate on different implementations without changing OpenShell itself. + +OpenShell may still ship first-party middleware for a small number of operations where it makes sense. First-party middleware uses the same request-processing model where possible, but restricted hooks may expose supervisor-only host capabilities that external middleware can never receive. + +### Use-case: Privacy Guard + +Privacy Guard is the motivating use case for this RFC. It is middleware that inspects outbound request content for sensitive data and applies a mitigation before the request leaves the sandbox. We use it throughout this document as a concrete example because it exercises every property the contract needs: policy-controlled placement in the proxy flow, an external service configuration, a request/response contract, failure behavior, and audit-safe findings. + +Consider an agent configured with a cloud model. The operator wants uploaded images to never reach that model. With supervisor middleware, they configure Privacy Guard on requests bound for the model endpoint. When the agent uploads an image and asks the model about it, the middleware inspects the request content, detects the image, and redacts it - replacing it with a placeholder (for example, `image upload is disabled for this model`) before the request leaves the sandbox. + +Beyond redaction, middleware also produces structured findings and string metadata about a request. That metadata is only an annotation surface in v1; the model-router work will define any routing-grade typed contract later. + +## Non-goals + +- **Model routing.** This RFC defines the v1 string metadata that middleware can emit, but not the component that consumes findings or metadata to pick a model. Routing a request to a different model based on findings is a separate concern tracked in [#1734](https://github.com/NVIDIA/OpenShell/issues/1734). Here we only avoid blocking a future routing contract: v1 middleware decisions stay `allow`/`deny`, and any later route-selection hook should be limited to OpenShell-managed routes rather than arbitrary rewrites from one external endpoint to another. +- **A general-purpose OpenShell plugin framework.** The first version targets supervisor-owned request processing, beginning with outbound HTTP requests in the supervisor proxy flow. It is not an arbitrary plugin system for every extension point in OpenShell, and it does not cover gateway control-plane hooks, compute driver behavior, or non-supervisor extension points. +- **Constraining or sandboxing the middleware itself.** A middleware gets raw access to request content. OpenShell routes payloads to a service the operator chose to trust; it does not sandbox the middleware, verify its behavior, or prevent a malicious one from mishandling the data it inspects. Authenticated encrypted transport protects the connection but does not make the service trustworthy. Stronger service isolation, such as running middleware in its own sandbox, remains follow-up work. +- **Runtime management of middleware.** Middleware is declared in gateway configuration. A runtime CLI or API to add, list, or validate middleware - and ergonomic tooling to make registration easy, such as a dedicated command or an agent skill that scaffolds and registers a new service - is deferred to follow-up work once the contract stabilizes. +- **Guaranteeing detection correctness.** OpenShell places the hook and enforces the decision the middleware returns, but it does not guarantee that a middleware actually catches all sensitive content. Detection quality is the middleware's responsibility. +- **Support for every deployment mode.** The first version supports in-process built-ins and statically registered external middleware services. Other shapes such as WASM middleware, OpenShell-managed images, sidecars, and running middleware inside its own sandbox are not designed in this RFC. They remain explicitly open for later evaluation rather than being baked into the initial contract. See [appendices/deployment-options.md](appendices/deployment-options.md). + +## Terminology + +This RFC uses the following terms with specific meanings. + +- **Egress.** An outbound request a sandbox sends to an upstream destination through the supervisor proxy. The v1 middleware hook acts on the parsed request the supervisor has already admitted and is about to forward, not on raw packets or arbitrary network activity. +- **Middleware.** A service that inspects, transforms, blocks, or annotates supervisor operations through the contract defined in this RFC. In the v1 egress hook, a middleware owns its detection and transformation logic and never makes the upstream call itself; the supervisor always owns the upstream call. +- **Registered middleware.** An external middleware service an operator declares in gateway configuration as a diagnostic name plus a gRPC endpoint. Registration is an administrative action that establishes which endpoints may receive raw request content. The service exposes stable binding IDs through `Describe`, and policy refers to those binding IDs rather than to the registration name. +- **Built-in middleware.** A middleware that ships inside the supervisor binary and runs in-process, with no network hop and no gateway registration. Built-in binding IDs use the reserved `openshell/` namespace, for example `openshell/regex`. +- **Operation.** The typed method plus typed phase that identifies the point where OpenShell invokes middleware. This RFC's v1 middleware evaluates `method=HTTP_REQUEST, phase=PRE_CREDENTIALS`. +- **Hook.** A named middleware API contract for one operation. Middleware hook names are part of the middleware API, not arbitrary strings supplied by the caller. The v1 hook is `HTTP_REQUEST/PRE_CREDENTIALS`, which runs in the HTTP relay once the request is parsed and admitted by policy and before credential injection. The design allows more typed operations later without changing the v1 hook's request shape. +- **Evaluation.** One invocation of middleware for a specific operation, request context, bounded body, and middleware config. Middleware keeps operation-specific methods such as `EvaluateHttpRequest` because inputs and outputs differ by protocol or operation type. +- **Result.** The response to an evaluation. For the v1 HTTP request hook, the result carries an allow/deny decision, optional replacement content and safe header mutations, findings, metadata, and safe error information. +- **Middleware config.** A policy entry stored under a stable policy-local map key that namespaces metadata and diagnostics. The optional `name` field is a human-readable label and defaults to the map key. The `middleware` field binds the entry to a service-owned binding ID, while the remaining fields define service-specific configuration, endpoint selectors, failure behavior, and ordering. +- **Manifest.** The self-description a middleware returns from `Describe`: its service version and service-owned bindings for the hooks it supports. The protobuf package `openshell.middleware.v1` defines the wire-version boundary; requests and manifests do not carry a duplicate API-version string. +- **Decision.** The allow-or-deny outcome a middleware returns for a request. `allow` lets the request proceed (possibly transformed); `deny` short-circuits it. This vocabulary matches the rest of the OpenShell policy system. +- **Failure policy.** The configured `on_error` behavior when middleware cannot return a valid result: `fail_closed` denies the request, while `fail_open` lets it continue without that middleware's transformation while recording an enforcement failure. `fail_closed` is the default whenever processing is required. +- **Transformation.** A middleware returning replacement content, and any allowed header mutations, that the supervisor forwards in place of the original request. A later middleware in a chain sees the previous stage's transformed content. +- **Finding.** A structured, audit-safe observation a middleware reports about a request, such as a machine-readable type, safe label, count, confidence, and optional severity. A finding never carries raw matched values, redacted spans, or the original sensitive content. The supervisor maps findings into OCSF `DetectionFinding` events. +- **Metadata.** Namespaced string key/value annotations a middleware emits into a request-local bag. V1 metadata never carries raw sensitive values. Routing-grade typed metadata, including usage markers such as audit-safe, routing-safe, or internal-only, is deferred until a component consumes it. +- **Chain.** The ordered set of middleware configs that applies to a single request. Each config runs in turn, a later stage sees the previous stage's transformed content, a `deny` short-circuits the remaining stages, and each matching config runs at most once per request. + +## Proposal + +The first version makes supervisor middleware concrete through one egress hook family without prematurely standardizing every future deployment model. It supports first-party built-ins that run inside the supervisor and external services that the operator runs and statically registers. OpenShell routes selected egress through the resulting chain, and each stage returns a decision plus optional transformed content, findings, and metadata. This keeps the first iteration focused on the contract, failure behavior, and sandbox integration while leaving other deployment shapes open (see [appendices/deployment-options.md](appendices/deployment-options.md)). + +External middleware services are exposed over gRPC network endpoints. The stable contract requires authenticated encrypted transport; phase 1 alone may explicitly opt into plaintext for trusted local or isolated research environments, and phase 2 removes that exception. See [appendices/protocol-extensions.md](appendices/protocol-extensions.md#middleware-authentication). + +### Architecture + +Three components participate: + +- **Gateway (control plane).** Registers middleware, validates that each registered service supports the policies that reference it, and distributes the effective middleware configuration to supervisors. The gateway never sees live request bodies; it stays off the hot path. +- **Supervisor proxy (data plane).** Calls the middleware on the request hot path, enforces the returned decision, forwards only the content the middleware returns, and carries emitted metadata forward. The supervisor owns the upstream call. +- **Middleware implementation.** Inspects the request and returns a decision, optional transformed content, findings, and metadata. A middleware can be a first-party built-in installed in-process or an operator-run service reached over gRPC. Both use the same chain and result semantics and never make the upstream call. Restricted built-ins may access supervisor-only capabilities unavailable to external services. + +```mermaid +graph LR + subgraph CP["Control Plane"] + GW["Gateway"] + end + subgraph SB["Sandbox"] + AGENT["Agent process"] + SUP["Supervisor proxy"] + end + subgraph MI["Middleware implementation"] + BI["Built-in
(in-process)"] + MW["Operator-run service
(gRPC)"] + end + UP["Upstream service"] + + GW -. "config (supervisor-initiated)" .- SUP + AGENT -->|"outbound request"| SUP + SUP -->|"in-process stage"| BI + BI -->|"decision + transformed content"| SUP + SUP -->|"request content + context"| MW + MW -->|"decision + transformed
content + metadata"| SUP + SUP -->|"forwards allowed request"| UP +``` + +### Operation phases and placement + +A middleware service provides hook implementations that the supervisor invokes at defined operation phases in the proxy flow. This version defines a single typed middleware operation, `HTTP_REQUEST/PRE_CREDENTIALS`, and is structured so more operations can be added later. The supervisor invokes the hook in the HTTP relay once the request has been parsed and admitted by policy, and before OpenShell injects upstream credentials. + +```mermaid +graph LR + REQ["Sandbox request"] --> L4["Network / L4 policy"] + L4 --> SSRF["SSRF checks"] + SSRF --> L7["L7 policy
(when protocol set)"] + L7 --> SELECT["Host selector
(middleware chain)"] + SELECT --> HOOK["HTTP_REQUEST / PRE_CREDENTIALS
(middleware stage)"] + HOOK -->|"deny"| DENY["Request denied"] + HOOK -->|"allow + transformed content"| RECHECK["Body-aware L7
policy re-evaluation"] + RECHECK -->|"deny"| DENY + RECHECK -->|"next stage or complete"| ROUTE["Route selection"] + ROUTE --> CRED["Credential injection"] + CRED --> UP["Upstream forwarding"] +``` + +This ordering is deliberate: + +- Network policy (and L7 policy, where the endpoint declares a `protocol`) runs first, so OpenShell never sends already-denied traffic to a middleware service. +- Middleware selection uses the admitted request host and is independent of which user, provider, or merged network rule admitted the request. This gives the effective policy one stable selection model after policy composition. +- Middleware runs before credential injection, so a middleware never receives OpenShell-managed upstream credentials. +- After a stage replaces the request body, OpenShell re-evaluates body-aware GraphQL, JSON-RPC, or MCP policy before invoking the next stage or forwarding upstream. A policy evaluation error or an unparseable replacement is a hard denial. An enforced policy denial stops and denies. In audit mode, OpenShell records the denial, stops the remaining middleware chain, and forwards the transformed request. +- A middleware's explicit denial and `fail_closed` behavior are enforcement decisions in their own right and remain blocking even when the network endpoint uses `enforcement: audit`. +- Route selection - choosing which upstream, and in future which model, serves the request - runs after the hook, so the later model-router work has a clear handoff point for any middleware findings or metadata it chooses to consume. There is no model router in v1; this box marks where one would plug in. Middleware does not forward traffic itself, and v1 deliberately has no `forward_to` decision. Any later route-selection phase should return an OpenShell-owned route decision for managed destinations, not an arbitrary rewrite from one external endpoint to another. +- The upstream call stays owned by the supervisor, never the middleware. + +The hook operates on a parsed HTTP request, so it runs wherever OpenShell can parse one. The supervisor proxy TLS-terminates and HTTP-parses every egress connection that is not marked `tls: skip` and is not opaque, non-HTTP traffic, so the hook fires on those requests regardless of whether the endpoint also declares a `protocol`. Declaring a `protocol` additionally subjects the request to L7 Rego policy; an endpoint without one is still terminated and parsed and the middleware hook runs on it. The only traffic the hook cannot inspect is traffic OpenShell never parses: `tls: skip` endpoints and opaque TCP or TLS passthrough. Policy validation rejects any middleware selector whose possible hosts overlap an endpoint configured with `tls: skip`, so selector-based middleware cannot be silently bypassed by an unparsed path. + +If matching middleware exists but a request becomes uninspectable at runtime, OpenShell examines the whole matching chain. If any stage is `fail_closed`, the request is denied. If every matching stage is `fail_open`, OpenShell relays the request and emits a bypass `DetectionFinding`. This chain-level rule prevents one permissive stage from overriding a required stage. + +WebSocket sits on this boundary. The upgrade request is a normal HTTP/1.1 request that the hook can inspect, allow, or deny, but the frames exchanged after the connection upgrades are out of scope for v1 (a later `message.*` hook may cover them). To keep the v1 boundary unambiguous: + +**In scope for v1:** + +- Inspectable HTTP/1.x requests that OpenShell terminates and parses, after L4 and SSRF admit them (and L7 policy too, where the endpoint declares a `protocol`). +- WebSocket upgrade (handshake) requests - the HTTP request that initiates the upgrade. +- Bounded request bodies: a `Content-Length` or bounded chunked body OpenShell can buffer within the applicable chain cap. +- Safe metadata output for later routing or audit. + +**Out of scope for v1:** + +- HTTP/2 and HTTP/3. The proxy's TLS termination pins ALPN to `http/1.1` today, so these are not introspected. +- Post-upgrade WebSocket frames, and response-body scanning. +- Opaque TCP streams and endpoints with `tls: skip`. +- Unbounded streaming uploads or full-duplex request processing. +- Multipart or compressed body semantics, unless a selected service's manifest and policy explicitly support them within the size limits. + +The request hook is synchronous and runs once for every selected stage. Timeout, failure behavior, and body buffering are therefore load-bearing parts of the design. The supervisor buffers up to the largest resolved stage limit, bounded by the 4 MiB platform maximum. A stage whose smaller limit is exceeded applies its own `on_error`, and later stages may still run when that result is `fail_open`. If an oversized `Content-Length` is known before body consumption, the supervisor may preserve streaming and fail open only when every affected stage permits it. If a chunked body crosses the cap after bytes have been consumed, the request is denied because the raw stream can no longer be resumed safely. The hook remains before any credential rewrite, which keeps OpenShell-managed credentials away from external middleware. Other operation phases such as pre-policy classification, a credential-visible `HttpRequest/post_credentials` hook for request signing (built-in-only, for example `openshell/sigv4`), response inspection, route selection for OpenShell-managed destinations, and streaming message hooks are possible future extensions and are out of scope for v1. + +### The middleware contract + +The contract has two parts: a configuration-time handshake and a request-time evaluation. The evaluation runs on the *hot path* - the synchronous, per-request path through the supervisor proxy, as opposed to the control-plane path used to fetch config. Middleware only sits on this path for sandboxes whose policy configures it: a sandbox with no middleware in its policy is unaffected and pays no per-request cost. Middleware is therefore an explicit opt-in, and this change is transparent to existing usage. + +Configuration-time: + +- `Describe` reports a service-provided diagnostic name, service version, and service-owned bindings for the typed operation and phase pairs it supports. A binding includes its maximum accepted body size and may override the service RPC timeout. +- `ValidateConfig` lets the service validate its own service-specific configuration fragment. + +Request-time: + +- `EvaluateHttpRequest` carries the selected binding ID and typed operation phase (`PRE_CREDENTIALS`) plus the request context, middleware configuration from policy, HTTP request target, repeated safe headers in wire order, and bounded body. +- `HttpRequestResult` is a response OpenShell can apply directly: `allow` or `deny`, a reason, optional replacement content, ordered header mutations, findings, and namespaced metadata. + +A simplified sketch of the gRPC contract: + +```protobuf +service SupervisorMiddleware { + // Configuration-time + rpc Describe(google.protobuf.Empty) returns (MiddlewareManifest); + rpc ValidateConfig(ValidateConfigRequest) returns (ValidateConfigResponse); + + // operation=HTTP_REQUEST, phase=PRE_CREDENTIALS. + rpc EvaluateHttpRequest(HttpRequestEvaluation) returns (HttpRequestResult); +} + +message MiddlewareManifest { + string name = 1; // service-provided diagnostic name + string service_version = 2; // service implementation version, informational + repeated MiddlewareBinding bindings = 3; +} + +message MiddlewareBinding { + string id = 1; // service-owned stable ID + SupervisorMiddlewareOperation operation = 2; + SupervisorMiddlewarePhase phase = 3; + uint64 max_body_bytes = 4; + string timeout = 5; // optional binding-specific RPC timeout +} + +message HttpRequestEvaluation { + string binding_id = 1; // selected manifest binding + SupervisorMiddlewarePhase phase = 2; + + RequestContext context = 3; + google.protobuf.Struct config = 4; // service-specific, from policy + + HttpRequestTarget target = 5; + repeated HttpHeader headers = 6; // safe subset, duplicates and wire order preserved + bytes body = 7; // bounded +} + +message RequestContext { + string request_id = 1; + string sandbox_id = 2; + Process originating_process = 3; // optional, per-connection +} + +message HttpRequestTarget { + string scheme = 1; + string host = 2; + uint32 port = 3; + string method = 4; + string path = 5; + string query = 6; // raw request query string; never log +} + +// Mirrors the originating process OpenShell already resolves for network policy and OCSF audit. +message Process { + string binary = 1; // resolved binary path + uint32 pid = 2; + repeated string ancestors = 3; // ancestor binary paths from the process-tree walk +} + +message Finding { + string type = 1; // e.g. "pii.email" + string label = 2; // safe display label + uint32 count = 3; // number of matches, never raw values + string confidence = 4; // service-defined confidence marker + string severity = 5; // service-defined severity marker +} + +message HttpHeader { + string name = 1; + string value = 2; +} + +message HeaderMutation { + oneof operation { + WriteHeader write = 1; + RemoveHeader remove = 2; + } +} + +message WriteHeader { + string name = 1; + string value = 2; + ExistingHeaderAction on_existing = 3; // APPEND, OVERWRITE, or SKIP +} + +message RemoveHeader { + string name = 1; +} + +message HttpRequestResult { + Decision decision = 1; // ALLOW or DENY + string reason = 2; // normalized by OpenShell before security output + + bytes body = 3; // replacement content when transformed + bool has_body = 4; // distinguishes no replacement from an empty replacement + + repeated HeaderMutation header_mutations = 5; + repeated Finding findings = 6; + map metadata = 7; +} +``` + +The evaluation and result are shaped so middleware composes cleanly in a chain. The allow/deny decision is a first-class result field rather than being mixed into content. If `has_body` is true, the transformed content a middleware returns (`HttpRequestResult.body`) becomes the request body the next middleware receives as `HttpRequestEvaluation.body`; if `has_body` is false, the supervisor keeps the previous body. The supervisor also feeds allowed header mutations into the next stage, so a chain is effectively a fold over a single request representation; a `deny` from any stage short-circuits the rest. See [Middleware ordering](#middleware-ordering) for how chains are assembled and ordered. + +Headers use a repeated representation so duplicate lines and wire order survive evaluation and chaining. Before an external call, OpenShell omits credential-bearing, routing, framing, hop-by-hop, and `Connection`-nominated headers. A result may return ordered writes and removals. Writes support append, overwrite, and skip modes but may target only the `x-openshell-middleware-*` namespace. Removals may target other headers visible to middleware, except credential-bearing, routing, framing, hop-by-hop, and `Connection`-nominated headers. Header values containing control characters are invalid. OpenShell validates and applies a stage's mutations atomically. If any mutation is invalid, none are applied and the stage follows its configured `on_error` behavior. + +The interface is gRPC. The protobuf package `openshell.middleware.v1` is the protocol version boundary, so manifests and evaluation messages do not repeat an API-version string. The hot-path v1 RPC is unary: the supervisor buffers the bounded body, sends one `HttpRequestEvaluation`, and receives one `HttpRequestResult`. Streaming is deliberately not baked into `EvaluateHttpRequest`; if OpenShell later needs chunked or incremental processing, it should add a separate operation-specific method rather than changing the v1 method cardinality. Possible extensions are collected in the [protocol-extensions appendix](appendices/protocol-extensions.md). Built-in middleware uses the same logical contract in-process with no network hop. + +V1 applies explicit public envelope limits before invoking a service or accepting its result: 64 KiB for encoded config, 4 KiB for request context, 32 KiB for the target, 128 header lines and 64 KiB of encoded headers, 4 MiB for the body, 4 KiB for a reason, 64 header mutations with at most 32 KiB of validated name/value data and 64 KiB encoded, 32 findings per stage with each finding at most 4 KiB encoded, and 64 metadata entries totaling at most 32 KiB. A chain has at most 10 stages and therefore at most 320 findings. Middleware gRPC servers configure request and response message limits to cover the 4 MiB body plus at least 292 KiB for the remaining envelope. + +The `originating_process` is the same identity OpenShell resolves on the egress path - the binary, pid, and ancestor chain it uses for binary-scoped network policy and OCSF audit. It is per-connection rather than strictly per-request and is optional. Middleware must treat missing process data as unavailable rather than as an authorization failure. The initial implementation leaves this field unset until reliable propagation is available. + +### Relationship to RFC 0010 + +[RFC 0010](https://github.com/NVIDIA/OpenShell/pull/1927) defines gateway interceptors: gateway control-plane extensions that evaluate gateway RPCs such as `CreateSandbox`. This RFC defines supervisor middleware: supervisor data-plane extensions that evaluate supervisor-managed operations such as `HTTP_REQUEST/PRE_CREDENTIALS`. The feature names may differ because the API surfaces and mechanics differ, but the two extension systems should align on shared plumbing where doing so avoids duplicate infrastructure. + +Shared mechanics: + +- **Endpoint exposure and auth.** Both extension systems use gRPC network endpoints. Their stable transport contract requires confidentiality and service authentication. During phase 1 only, supervisor middleware may explicitly opt into plaintext for trusted local or isolated research environments. Endpoint declaration, identity binding, credential material, and rotation should use shared mechanics where practical. +- **Manifest description.** Both extension systems use `Describe` to return a manifest that declares a diagnostic service name, implementation version, and service-owned bindings for supported hook points. +- **Operation phases.** Both systems hook into a named operation plus phase. The phase sets differ by system, but the concept is the same: `method=CreateSandbox, phase=pre_request` for a gateway interceptor, and `HTTP_REQUEST/PRE_CREDENTIALS` for v1 supervisor middleware. +- **Evaluation and result.** Both systems run an evaluate-style request and return a result. Middleware keeps operation-specific methods such as `EvaluateHttpRequest` because inputs and outputs differ by protocol or operation type; interceptor methods and messages are defined by RFC 0010. +- **Failure policy.** Both systems use `on_error: fail_closed|fail_open`, with fail-closed as the safe default for required enforcement. +- **Observability.** Both systems emit OCSF events with the details relevant to the extension point, while preserving the same no-secrets logging rules. +- **Ordering.** Both systems apply multiple configured extensions in deterministic order. + +Intentional differences: + +- **Selection model.** Supervisor middleware is selected per sandbox at runtime through policy and API state. Gateway interceptors are selected for the gateway at deploy time by operators in `gateway.toml`. +- **Method naming.** Gateway interceptors register against RPC method strings that are not themselves part of the interceptor API. Supervisor middleware exposes named operation-specific hook methods such as `EvaluateHttpRequest`; those names are part of the middleware API contract. +- **Control responsibility.** Gateway interceptors may enforce that sandbox requests include approved middleware configuration, but they do not replace the per-sandbox middleware selection model. + +### Contract versioning + +The middleware gRPC contract lives under a major-versioned protobuf package (`openshell.middleware.v1`), the same convention the compute-driver contract uses in [RFC 0001](../0001-core-architecture/README.md). Within a stable major version, changes stay additive and backward compatible - new fields, RPCs, operation phases, and manifest fields can be added - while breaking wire or semantic changes require a new major version. The research preview may still make intentional breaking changes before the contract is declared stable. + +The protobuf package is the wire-version handshake. `Describe` reports a diagnostic service name, implementation version, and stable binding IDs for supported hook points; it does not carry a second API-version field. Manifest validation is mandatory: if OpenShell cannot fetch the manifest, bindings conflict, a service claims the reserved `openshell/` namespace, or policy asks for an unsupported binding or invalid config, the gateway rejects the relevant configuration before traffic can depend on it. Runtime invocation failures are handled through `on_error` and use `fail_closed` by default. + +### Registration and delivery + +The operator registers available external middleware services in gateway configuration under `openshell.supervisor.middleware`. The namespace identifies the subsystem whose behavior is extended, not the process that reads the configuration. The gateway still loads, validates, and distributes these registrations to supervisors. Each entry has a diagnostic name, gRPC endpoint, maximum body size, optional RPC timeout, and transport settings. The diagnostic name identifies the configured connection in logs but is not a policy key. Policy authors select stable binding IDs returned by `Describe`, so they cannot point traffic at an arbitrary endpoint and do not depend on an operator-local registration name. + +The v1 transport is gRPC over a network endpoint reachable from every supervisor across Docker, Podman, VM, and Kubernetes drivers. In local single-player deployments, a loopback endpoint such as `127.0.0.1:1234` may be translated to `host.openshell.internal` so a supervisor can reach a service running on the local host. That loopback shorthand is not an HA deployment model: Kubernetes and other shared deployments should register a routable service DNS name or address that every supervisor can reach directly. Other deployment shapes are deferred until OpenShell has a universal way to make those endpoints reachable from the relevant supervisor environments. + +```toml +[[openshell.supervisor.middleware]] +name = "anonymizer" +grpc_endpoint = "http://127.0.0.1:1234" +max_body_bytes = 4194304 +timeout = "500ms" +allow_insecure = true + +[[openshell.supervisor.middleware]] +name = "agent-traces-exporter" +grpc_endpoint = "https://middleware.example.internal:443" +max_body_bytes = 1048576 +``` + +The stable transport requirement is confidentiality plus authentication of the intended middleware service. Phase 1 may temporarily accept a plaintext `http://` endpoint only when the same entry explicitly sets `allow_insecure = true`. OpenShell rejects plaintext without that opt-in, warns prominently, and records the insecure registration as auditable configuration state. This escape hatch is limited to trusted local development and isolated research environments. Phase 2 removes plaintext support and the `allow_insecure` field, requiring authenticated encrypted transport. That removal is an intentional research-preview breaking change with no long-term compatibility obligation. The exact phase 2 mechanism, such as mTLS or TLS plus explicit caller authentication, is follow-up protocol work (see [appendices/protocol-extensions.md](appendices/protocol-extensions.md#middleware-authentication)). + +For each binding, the operator's `max_body_bytes` must not exceed the binding capability returned by `Describe` or the 4 MiB platform maximum. The gateway rejects an invalid registration rather than silently clamping it. The resulting operator limit applies to every binding exposed by that registration. + +RPC timeouts use an integer with an `ms` or `s` suffix, range from 10 ms through 30 s, and default to 500 ms. A binding may advertise its own timeout through `Describe`; that value overrides the service registration timeout. The service timeout applies to `Describe`, while the effective binding timeout applies to `ValidateConfig` and `EvaluateHttpRequest`. + +The external-service endpoint is trusted operator infrastructure in v1. The auth design must make both directions explicit: the supervisor proves to the middleware that the call is authorized for the specific middleware identity, and the supervisor verifies it is calling the intended middleware service. + +Binding IDs may be bare (`anonymizer`) or namespaced with `/` (`nvidia/anonymizer`, `acme/security/pii-redactor`). Empty path segments are invalid, so `/foo`, `foo/`, and `foo//bar` are rejected. The `openshell/` namespace is reserved for built-in OpenShell middleware, such as `openshell/regex` or `openshell/sigv4`. Policy config map keys remain stable local identities for metadata namespacing and diagnostics; the `middleware` field selects the binding. + +Built-in middleware ships in the supervisor binary and needs no external registration. Supervisors install built-in bindings before attempting external connections. + +At gateway startup, OpenShell connects to every registered service and calls `Describe`. Startup rejects unavailable or invalid services, duplicate binding IDs across services, and external claims in the reserved `openshell/` namespace. Sandbox policy creation and update call the owning service's `ValidateConfig` before persistence. + +Supervisors receive policy plus the external service registrations required by the effective policy through the existing `GetSandboxConfig` response. Built-in registrations are not delivered because they are already installed in-process. The gateway stays off the request hot path; supervisors connect to the required services and invoke them directly. + +Runtime changes are prepared off to the side. Policy and middleware registry swap as one generation only after the complete candidate is ready. A policy-only update reuses an already connected registry. If preparation fails, the supervisor preserves the complete last-known-good runtime and continues retrying. If an external service is unavailable when a supervisor starts or reloads, built-ins remain active, requests use each selected config's `on_error`, and a polling loop retries the service independently of policy revision changes. + +Middleware registration lives in gateway configuration, which is not hot-reloaded ([RFC 0003](../0003-gateway-configuration/README.md) lists this as a non-goal): changing the registered set requires restarting the gateway. Middleware selection is separate from registration. Registration declares what implementations are available to supervisors; per-sandbox policy and API updates decide which middleware configs apply to a given sandbox at runtime. On restart, supervisors re-sync the effective configuration over their existing connection, so running sandboxes pick up a newly added middleware rather than only newly created sandboxes seeing it - there is no per-sandbox snapshot of the registered set. + +Removing a registered middleware that an active policy config still binds to causes those sandboxes to follow the affected config's `on_error`; `fail_closed` is the default. For now, the operator is responsible for removing policy configs before removing the registration. Runtime process or network failures follow the same rule while the supervisor retries the connection. + +V1 does not define a separate health-check RPC. Connection establishment, `Describe`, per-request invocation, timeout, `on_error`, and the registry retry loop provide the required availability behavior. A dedicated health API may improve alerting later but is not required for correctness. + +Multitenancy is handled by OpenShell policy selection, not by giving middleware its own tenant-routing model. A shared middleware service may receive requests from many sandboxes, but the service should treat `sandbox_id`, policy name, and endpoint context as audit context only unless a later OpenShell domain object defines stronger grouping semantics. Middleware-specific tenant grouping is possible but not part of the OpenShell contract. + +### Policy integration + +Policy decides which middleware runs for which traffic, how it is configured, and what happens on failure. Middleware configs live once in the top-level `network_middlewares` map, represented as `map` in `SandboxPolicy`. Each map key is the stable policy-local identity. Each config selects destination hosts directly through `endpoints.include` and `endpoints.exclude`; network policies and endpoints do not carry middleware attachment lists. + +A middleware config may include an optional human-readable `name`, which defaults to the map key and does not replace that key as the config identity. `middleware` is the stable binding ID exposed by a built-in or by an external service's `Describe` response. Different map keys may reference the same binding and run as separate stages with different selectors or configuration. + +Each entry supplies implementation-owned configuration, `on_error` behavior, numeric `order`, and endpoint selectors. `fail_closed` is the default. `order` defaults to `0` and must be unique across the complete policy, even when selectors do not overlap, so policies with multiple configs normally set it explicitly. OpenShell validates the structure and asks the owning implementation to `ValidateConfig` before the gateway persists a policy. + +Selection occurs after network and L7 admission and depends only on the admitted request host. It does not depend on which user-authored, provider-derived, broad, specific, or merged network rule admitted the request. This independence is important because effective policy composition may change the admitting rule without changing the intended content controls. + +Every config requires a non-empty `include` list. `exclude` is optional and takes precedence over `include`. Matching is case-insensitive and uses the same host-pattern implementation as network endpoints: `*` matches exactly one DNS label, `**` matches one or more DNS labels, and intra-label wildcards such as `*-api.example.com` are supported. Brace alternates are rejected; authors list each alternative explicitly. A config accepts at most 32 combined include and exclude patterns. A policy accepts at most 10 middleware configs, and runtime selection defensively rejects a chain longer than 10 stages. + +The hook is a supervisor-side Rust enforcement stage selected by policy data, not a Rego rule. L4 policy admits the connection and, where the endpoint declares a `protocol`, L7 policy admits the parsed request. The supervisor then selects the chain, buffers the bounded body, invokes stages, applies valid results, and re-evaluates body-aware protocol policy after each body replacement. Request bodies do not otherwise become a new general Rego input surface. + +```yaml +network_middlewares: + regex-redactor: + name: Redact sensitive tokens + middleware: openshell/regex + order: 10 + config: + mode: redact + on_error: fail_closed + endpoints: + include: ["*.example.com"] + exclude: ["trusted.example.com"] + + anonymize: + middleware: acme/anonymizer + order: 20 + config: + pii: redact + on_error: fail_closed + endpoints: + include: ["api.example.com"] + + export-traces: + middleware: acme/trace-exporter + order: 30 + config: + exclude_images: true + on_error: fail_open + endpoints: + include: ["api.example.com"] +``` + +With this policy, a request to `api.example.com` runs `regex-redactor`, `anonymize`, and `export-traces` in that order. A request to `trusted.example.com` does not run `regex-redactor` because exclusion wins. `openshell/regex` is a best-effort example that applies a fixed set of regular-expression replacements to UTF-8 bodies; it is not parser-aware and does not guarantee detection or complete removal of sensitive values. If `anonymize` fails, the request is denied. If `export-traces` fails, the stage is bypassed, the rest of the chain continues, and OpenShell emits a detection finding. + +V1 middleware configs are policy-local and are not embedded in provider profiles. Their host selectors run after effective policy assembly, so they cover provider-supplied endpoints without mutating or attaching data to the provider policy. Reusable cross-sandbox middleware profiles and provider-profile opt-ins remain follow-up design work. + +### Middleware ordering + +When more than one middleware config matches a request, the supervisor sorts them by ascending numeric `order`. Order values must be unique across the policy and duplicate values are rejected during validation. `order` defaults to `0`, so policies with multiple configs normally set explicit values. Each matching config runs once. Different map keys that reference the same binding remain separate stages and may therefore run more than once with distinct configuration. + +A later stage sees the earlier stage's accepted body and header mutations. A middleware `deny` short-circuits the chain. A failed `fail_closed` stage also stops and denies. A failed `fail_open` stage leaves the request representation unchanged for that stage, emits a bypass finding, and permits later stages to run. + +`before` and `after` constraints are deferred until reusable middleware profiles or cross-policy composition creates a demonstrated need for partial ordering. Implementation-defined ordering is rejected because middleware can transform request content, so operators require deterministic and reviewable behavior. + +### Metadata and downstream routing + +Beyond allow/deny and transformation, middleware emits string metadata (for example `modalities = "text,image"`, `sensitivity = "restricted"`, `requires_local_model = "true"`) into a request-local metadata bag. The supervisor stores that metadata under the middleware config's stable map key, so `anonymize.sensitivity` and `budget.sensitivity` do not collide even if two services return the same key. V1 metadata is intentionally string-only and never carries raw sensitive values. This gives early middleware a safe annotation surface while deferring routing-grade typed metadata and usage markings to the model-router work; the router itself is out of scope ([#1734](https://github.com/NVIDIA/OpenShell/issues/1734)). + +Because `HTTP_REQUEST/PRE_CREDENTIALS` runs before route selection and credential injection, v1 does not guarantee that metadata visible at this hook includes the final routed model or upstream route. Budget-style middleware that needs post-call status, final route/model, content length, or token usage needs a later metadata-only notification hook such as `HttpResponse/completed`; that hook is listed as a future extension in the [protocol-extensions appendix](appendices/protocol-extensions.md#additional-operation-phases), not part of the v1 request hook. + +The namespace is the policy-local middleware config map key, not the optional human-readable `name` or the binding ID. This means two configs that use the same binding still produce separate metadata buckets, and changing a display label or the registered service behind a binding does not rename downstream annotations. + +### Audit and logging + +A middleware decision is observable sandbox behavior, so it is recorded as an OCSF event, consistent with how the supervisor already logs network and L7 enforcement. This RFC commits to the event categories and the safety rules; exact field mappings are an implementation detail. + +- **Per-invocation decisions** are `HttpActivity` events, since middleware is an L7 enforcement point. Each stage records the policy-local config key, validated binding ID, decision, transformation state, latency, and policy and endpoint context. Allowed requests are `Informational`; denials are `Medium`. +- **Enforcement failures and bypasses** also emit `DetectionFinding` events. Required-stage failures, invalid responses, uninspectable traffic with a required stage, and body-aware policy evaluation failures are `High`. A `fail_open` bypass and uninspectable traffic allowed because every matching stage is `fail_open` are still findings so operators can alert on reduced enforcement. +- **Configuration events** are `ConfigStateChange` events: middleware registration validation, registry reload success or failure, and policy validation outcome. + +These events must never leak the content they describe. The OCSF JSONL may be shipped to external systems, so: + +- Raw request content, matched values, redacted spans, and service-config secrets are never logged. +- Built-ins may preserve contract-defined audit-safe reasons and finding fields. Operator-run reason text, finding text, mutation errors, and diagnostic metadata are untrusted input. OpenShell replaces or omits them in denied responses and security logs, using stable platform-owned messages derived from the validated binding and failure category. +- Events carry only safe summaries: policy-local config keys, validated binding IDs, decisions, latency, platform-owned failure categories, and aggregate counts. + +This mirrors the middleware response contract, which already forbids the service from returning raw matched values. + +## Implementation plan + +Supervisor egress middleware stays opt-in throughout: until a policy declares a matching middleware config, no sandbox invokes one and the proxy hot path is unchanged. The initial usable slice proves built-in and external execution together; the phase boundary is transport hardening, not whether external middleware exists. + +**Phase 1 - research-preview contract and execution.** Define `openshell.middleware.v1` with `Describe`, `ValidateConfig`, and `EvaluateHttpRequest`; ship the example `openshell/regex` built-in; and support statically registered operator-run services. Policy uses a top-level selector-based `network_middlewares` map with stable config keys, unique numeric `order`, per-stage `on_error`, bounded bodies, bounded RPC timeouts, atomic header mutations, post-transformation policy re-evaluation, and OCSF observability. Gateway startup validates external manifests, policy writes validate implementation-owned config, effective sandbox config carries only required external registrations, and supervisors install policy plus registry as one last-known-good runtime generation. Phase 1 requires encrypted authenticated transport for normal use but temporarily permits plaintext `http://` only with explicit `allow_insecure = true` for trusted local development or isolated research. OpenShell warns and emits auditable configuration state whenever that exception is used. + +**Phase 2 - mandatory authenticated encryption.** Remove plaintext middleware transport and remove `allow_insecure`. Every external connection must provide transport confidentiality and authenticate the intended service, with the final mechanism and credential delivery model defined by follow-up protocol work. Because phase 1 is explicitly a research preview, removing its insecure escape hatch is an intentional breaking change and does not create a long-term compatibility obligation. Operator-run service deployment otherwise keeps the same binding, policy, validation, delivery, reload, and invocation model. + +### Backwards compatibility and migration + +Existing sandbox policies and gateway configs that declare no middleware remain valid and pay no per-request cost. Middleware configs that opt into phase 1 plaintext are intentionally temporary: they must migrate to authenticated encrypted endpoints before phase 2 because `allow_insecure` and plaintext support will be removed. The research-preview contract may make other breaking changes before stability. + +### Research preview + +The first release is a research preview. The contract, policy surface, and scope are provisional and may change without the usual compatibility guarantees. Plaintext is a phase 1 exception, not part of the stable design. Production and shared deployments must use authenticated encrypted transport, and phase 2 removes the exception entirely (see [appendices/protocol-extensions.md](appendices/protocol-extensions.md#middleware-authentication)). The goal is to validate the contract and operational model through early experiments with a built-in middleware plus a small number of trusted external services before committing to long-term stability. + +## Risks + +Adding a synchronous, content-aware hook to the egress path has real costs. The most significant: + +- **Hot-path latency and a new per-request dependency.** Each selected external stage makes a synchronous call and blocks on its reply, so middleware latency becomes request latency and the service becomes a new failure surface on the data plane. This is bounded by opt-in host selectors, per-middleware timeouts, and built-ins running in-process with no network hop, but for matching traffic the tax is unavoidable. +- **Fail-closed breaks workloads.** Denying traffic when a required middleware is unavailable, times out, or returns a malformed response is the safe default, but it converts a middleware outage into a sandbox outage. The opposite default leaks the very content the middleware exists to control. There is no choice that is both safe and always available; `on_error` makes the tradeoff explicit per middleware, but operators can still pick a default that surprises them. +- **Body buffering and size limits.** Inspecting content means buffering a bounded request body instead of streaming it, which adds memory cost and interacts badly with growing payloads (for example inference requests whose context expands each turn until it exceeds the cap). An over-cap request is treated as an `on_error` event for the middleware that needs the body, so it follows the same `fail_closed` default: it is denied unless the operator has explicitly set `on_error: fail_open` for that middleware. Passing an over-cap request through unprocessed is therefore never the default - it is an opt-in choice made per middleware, and one a security-critical middleware would deliberately leave off so that oversized content is denied rather than silently egressed. +- **No OpenShell-side rate limiting.** OpenShell does not throttle calls to a middleware. A middleware that is slow, overloaded, or unavailable is handled only by its timeout and `on_error`, so operators must size, scale, and protect the service themselves; a struggling middleware degrades every request routed through it. +- **Trusting an unsandboxed service with raw content.** Middleware receives raw request payloads, and OpenShell does not sandbox it, verify its behavior, or prevent it from mishandling or exfiltrating what it inspects. A buggy or malicious middleware is a direct data-exposure path. Trust in the middleware is the operator's responsibility, the same as trust in a sandbox image, but the blast radius here is in-flight request content. +- **A false sense of coverage.** The hook runs only on traffic OpenShell terminates and parses. Opaque TCP or TLS passthrough, encrypted or otherwise opaque bodies, endpoints outside every selector, and content the middleware fails to detect can still leave without effective inspection. Policy validation rejects selector overlap with `tls: skip`, and runtime uninspectability follows the matching chain's failure policy, but detection correctness and traffic outside the selected host set remain inherent limitations. +- **Phase 1 plaintext is risky.** The research-preview exception permits plaintext gRPC only with explicit `allow_insecure = true`. Because middleware can allow, deny, or transform egress, an impersonated or eavesdropped service is a policy-enforcement bypass, not just an observability gap. The exception is unsuitable for shared or untrusted networks, produces an explicit warning and audit event, and is removed in phase 2. See [appendices/protocol-extensions.md](appendices/protocol-extensions.md#middleware-authentication). +- **Added surface to build, version, and maintain.** A new gRPC contract, policy schema, gateway configuration table, and manifest handshake are all long-lived surfaces with compatibility obligations, and middleware chains add ordering semantics operators must reason about. The research-preview framing keeps the contract provisional for now, but the long-term maintenance cost is real and is the main argument for keeping v1 deliberately small. + +The cost of *not* doing this is leaving content-level egress control entirely outside OpenShell: operators who need to redact, block, or annotate outbound content based on what it contains would have to build bespoke proxies around the sandbox, losing the policy integration, audit, and trust boundary the supervisor already provides. + +## Alternatives + +- **Build content checks into OpenShell directly.** A fixed, built-in set of DLP/redaction rules avoids a contract and an external service. Rejected as the primary model: OpenShell cannot embed every useful detection and transformation approach, and a stable contract lets dedicated tools and research scanners iterate without changing OpenShell. First-party built-in middleware still ships for narrow cases, over the same contract. +- **REST instead of gRPC.** A REST/JSON hook is simpler to call, and with OpenAPI it could still offer a manifest handshake and a typed contract. Rejected because gRPC's typing is stronger, OpenShell already uses gRPC across its service contracts, and gRPC leaves room for future streaming operations if large or incremental payload processing becomes necessary. Staying on a single toolchain avoids a second RPC stack to build, secure, and maintain. +- **Other deployment modes (WASM, sidecar, in-sandbox).** In-process WASM filters or sidecars avoid a network hop and can tighten the trust boundary. Deferred rather than rejected: v1 supports native built-ins and statically registered external services, while other shapes remain open. See [appendices/deployment-options.md](appendices/deployment-options.md). +- **Doing nothing.** The cost of declining is covered at the end of Risks: content-level egress control stays outside OpenShell, and operators must build bespoke proxies that lose the policy integration, audit, and trust boundary the supervisor already provides. + +## Prior art + +Calling an external service from a proxy to inspect, transform, or block in-flight traffic is well-established. The closest analogs: + +- **Envoy `ext_proc` (External Processing).** The primary model for this RFC. Envoy streams request headers and body to an external gRPC service that can mutate the body (for example redaction), allow, or deny, and the proxy and the processing service scale independently. Our `HttpRequest/pre_credentials` hook is a buffered, single-hook v1 of the same boundary; if OpenShell later needs `ext_proc`-style streaming, it should add a separate streaming operation. +- **Envoy `ext_authz` (External Authorization).** A narrower sibling: an external service returns an allow/deny decision per request. It validates the "delegate the per-request decision to an external service in the hot path" pattern, without the content-transformation half that this RFC needs. +- **ICAP (RFC 3507).** HTTP proxies offload content adaptation, virus scanning, DLP, and content filtering to external ICAP servers that can modify or block request/response content. It is the closest *functional* precedent for content-aware egress control. Two details map directly onto our design: ICAP supports **pipelining** multiple servers (our middleware chain) and a **content preview** of the first bytes before full processing (our bounded-body buffering). What we avoid is its dated, text-based wire protocol; gRPC gives us typed contracts and room for future operation-specific streaming if we need it. +- **HashiCorp `go-plugin` (Terraform, Vault).** Third-party plugins run as separate processes and communicate with the core exclusively over gRPC. It shows a strictly typed gRPC contract is a robust way to manage cross-language third-party extensions, which informs our registration plus manifest handshake (`Describe`, `ValidateConfig`). +- **Kubernetes CSI / KMS.** Vendor-specific integrations are offloaded to external gRPC services rather than compiled into the core. Same "core defines the contract; integrators implement it out-of-process" split we use for middleware. +- **Proxy-Wasm (Envoy/Istio Wasm filters).** In-process WebAssembly extensions with strong default-deny sandboxing and no IPC latency. Relevant to the future WASM deployment mode (see the deployment-options appendix); set aside for v1 because it is currently weak for GPU-backed or memory-heavy semantic guards. + +## Decisions and explicit deferrals + +This section closes the current review themes. + +### Decisions + +- **Middleware naming.** Use the feature name "supervisor middleware." The first operation family is egress middleware, but the higher-level feature name stays extensible for future supervisor hooks. The service can inspect, transform, deny, and annotate, so narrower names such as "transformer" or "request processor" describe only part of the contract. +- **Middleware binding IDs.** Services own stable binding IDs and policy selects them through the `middleware` field. Gateway registration names are diagnostic only. Binding IDs use `/` for namespaces, `openshell/` is reserved for built-ins, and empty path segments are invalid. +- **Operation naming.** Use typed operation and phase enums such as `HTTP_REQUEST/PRE_CREDENTIALS`. The operation describes the middleware API payload, and the phase describes the proxy position. Later protocols can add typed operations such as WebSocket message or TCP connect without renaming the v1 hook. +- **HTTP scope of v1.** `HTTP_REQUEST/PRE_CREDENTIALS` applies to every HTTP/1.x request that OpenShell terminates and parses, whether or not the endpoint declares a `protocol`. WebSocket upgrade requests are included; post-upgrade frames, HTTP/2, HTTP/3, opaque TCP, and `tls: skip` traffic are excluded. +- **Route selection and forwarding.** V1 has no `forward_to` decision. Middleware never makes the upstream call. Future route-selection hooks may choose among OpenShell-managed destinations, such as model routes, but must not become arbitrary external endpoint rewrites. +- **SigV4/request signing.** AWS SigV4 belongs to a restricted built-in `HttpRequest/post_credentials` hook, not external `HttpRequest/pre_credentials` middleware. The middleware can be configured by policy, but it must run in-process with supervisor host capabilities so it can strip placeholder signatures and sign with real supervisor-resolved credentials without exposing those credentials over the external middleware contract. +- **Composability and ordering.** Middleware is chainable and ordered by ascending numeric `order`. Order values must be unique across the policy. A stage receives the previous stage's transformed body and header mutations; `deny` short-circuits the chain; and different config map keys may invoke the same binding as separate stages. +- **Header mutation.** Headers preserve duplicates and wire order. External writes are limited to `x-openshell-middleware-*` and support append, overwrite, or skip. Removes may target other visible headers. Credential-bearing, routing, framing, hop-by-hop, and `Connection`-nominated headers remain protected. Each stage's mutations are atomic. +- **Finding shape.** Findings never include matched values or raw content. Built-ins may provide contract-defined audit-safe labels. Operator-run text and metadata are untrusted and are replaced or omitted in security outputs in favor of validated binding IDs, platform labels, and aggregate counts. +- **Actor data.** Actor process data is optional and per-connection. Middleware must treat it as context, not a reliable per-request identity or authorization input. +- **Metadata namespacing.** Metadata is stored under the policy-local middleware config map key rather than the optional human-readable name. This prevents collisions without a central key registry and lets two configs using the same implementation emit independent metadata. +- **Selector-only placement.** V1 uses only config-level `endpoints.include` and `endpoints.exclude` selectors. Policy-level and endpoint-level attachment lists are not part of the schema. Selection is independent of the network rule that admitted the request and therefore remains stable after effective-policy composition. +- **Failure behavior.** Middleware errors, timeouts, malformed responses, and over-cap bodies use `on_error`; `fail_closed` is the default. Passing unprocessed content through is only possible when the operator explicitly sets `on_error: fail_open`. +- **Limits.** V1 caps policies at 10 middleware configs, selectors at 32 combined patterns per config, bodies at 4 MiB, findings at 32 per stage, and all non-body request and result fields at the public envelope limits in the contract section. +- **Delivery and reload.** `GetSandboxConfig` delivers only external registrations required by the effective policy. Built-ins are installed locally. Supervisors prepare candidate policy and registry state off-path, swap them as one generation, reuse connections for policy-only changes, and preserve the complete last-known-good runtime on failure. +- **Chunked and compressed bodies.** V1 operates on bounded bytes OpenShell can buffer safely. Known over-cap content length may fail open before consumption when every affected stage permits it. Chunked overflow after consumption is denied because the raw stream cannot be resumed. Compressed bodies remain opaque unless a binding explicitly supports them. +- **Post-transformation enforcement.** Every body replacement is re-evaluated by body-aware GraphQL, JSON-RPC, or MCP policy before the next stage or upstream. An enforced denial blocks. In audit mode, a denial is logged, the remaining chain stops, and the transformed request is forwarded. Evaluation failure or an unparseable replacement is a hard denial. Middleware deny and `fail_closed` remain blocking regardless of endpoint audit mode. +- **Trust boundary and phases.** Stable external middleware transport requires confidentiality and service authentication. Phase 1 may temporarily allow plaintext only with explicit `allow_insecure = true`, a warning, and an audit event in trusted local or isolated research environments. Phase 2 removes plaintext and `allow_insecure` as an intentional research-preview breaking change. +- **Multitenancy.** OpenShell controls middleware application through policy selection. A middleware may receive sandbox and policy context for audit, but OpenShell does not define a middleware-owned tenant grouping model in v1. +- **API maturity qualifier.** Use `openshell.middleware.v1`, not `v1alpha1`. The project is already alpha-stage; the RFC labels this contract as a research preview, so an additional per-contract alpha package adds little. + +### Explicit deferrals + +- **Provider-profile middleware.** V1 middleware configs live in sandbox policy, not provider profiles. Provider-supplied network policies can be targeted after effective policy assembly. Provider-profile opt-ins for built-in middleware such as `openshell/sigv4`, and reusable cross-sandbox middleware profiles, are follow-up design work. +- **Authenticated transport mechanism.** Phase 2 requires authenticated encrypted transport. The exact choice between mTLS, TLS plus caller authentication, or an equivalent mechanism, including credential delivery and rotation, is follow-up protocol work. +- **Health checks.** V1 relies on connection establishment, `Describe`, per-request invocation, timeout, `on_error`, and registry polling. A dedicated health RPC can improve alerting later but is not required for correctness. +- **Registration ergonomics and ownership.** V1 middleware registration is an operator concern: middleware services are declared in gateway configuration and changing the registered set requires a gateway restart. Runtime user-managed registration, CLI/API helpers, SDK helpers, and an agent skill for scaffolding or registering middleware are useful follow-ups after the policy and service contract stabilize. +- **Post-call budget reconciliation.** Budget-style middleware that needs final route/model, status, content length, or token usage needs a metadata-only hook such as `HttpResponse/completed`. That hook is listed as a future extension and is not part of the v1 request hook. +- **Deployment modes and timelines.** V1 commits to externally managed services plus in-process built-ins. WASM, sidecar, OpenShell-managed image, and in-sandbox middleware have no committed timeline in this RFC. diff --git a/rfc/0009-supervisor-middleware/appendices/deployment-options.md b/rfc/0009-supervisor-middleware/appendices/deployment-options.md new file mode 100644 index 0000000000..cd267195f1 --- /dev/null +++ b/rfc/0009-supervisor-middleware/appendices/deployment-options.md @@ -0,0 +1,41 @@ +# Appendix: Deployment Options + +> This is an appendix to the [RFC](../README.md). Please familiarize yourself with the RFC before reading this. + +This appendix records why the first version of supervisor middleware supports in-process built-ins plus externally managed network service endpoints, and what deployment modes remain open for later evaluation. Supporting every deployment mode is an explicit non-goal of the main RFC; this document preserves the analysis so the decision is not lost. + +## Decision: built-ins and externally managed service endpoints + +The first version runs first-party built-ins inside the supervisor and routes selected external evaluations to operator-run services reachable by the gateway and supervisors. Built-ins need no registration or network transport. For external services, OpenShell holds only the connection details, body limit, transport settings, and operation-specific evaluation/result contract. It does not package, deploy, or manage the service lifecycle. + +Rationale: + +- **Minimal new infrastructure.** Built-ins reuse the supervisor process. External middleware does not require OpenShell to build image packaging, process supervision, or a new runtime. The first iteration can focus on the contract, failure behavior, and supervisor integration. +- **Portable across compute drivers.** A network endpoint is reachable from supervisors regardless of whether the sandbox workload runs as a container, a VM, or a local process. Other endpoint shapes do not have a universal way to be shared with every relevant supervisor environment yet, so a network endpoint is the portable choice that works the same way everywhere. +- **Independent iteration.** The middleware is an integration point with another team. An external service lets them deploy, scale, and update it on their own cadence, without coupling releases to OpenShell. +- **Heavy compute friendly.** Detection work may need GPUs or significant memory. An external service can live wherever those resources are, and can be scaled separately from the sandbox fleet. + +Tradeoffs: + +- The middleware is a trusted component with raw access to request content. As a standalone network service it sits outside OpenShell's isolation boundary, typically with its own connectivity and credentials. The main RFC calls out trust in the middleware as a non-goal; this deployment shape leans on that assumption. +- The operator is responsible for deploying, securing, and maintaining the service. + +## Future options + +These are recorded as directions, not committed designs. They have no committed timeline in this RFC; sequencing depends on the initial external-service implementation, adoption feedback, and the availability of supporting primitives such as sandbox-to-sandbox communication. + +### Middleware running inside its own sandbox + +Package the middleware as a container image and run it inside an OpenShell sandbox, then route egress content to it. The middleware would inherit sandbox isolation: policy-enforced egress, filesystem and syscall constraints, and no open internet access unless explicitly granted. + +This is the most direct answer to the trust concern. Instead of trusting the middleware not to exfiltrate the content it inspects, the operator constrains it the same way any other sandbox is constrained. A PII redactor with no network egress cannot leak what it sees, even if the image is compromised. + +This option depends on sandbox-to-sandbox communication ([#1049](https://github.com/NVIDIA/OpenShell/issues/1049)), which is not available yet. When it lands, this becomes the most attractive shape for untrusted or third-party middleware. + +### WASM middleware + +Run the middleware as a WebAssembly module loaded by the supervisor, in-process with the proxy. This offers strong isolation with low latency and no separate service to operate, at the cost of a constrained runtime (limited libraries, no GPU access). It is a good fit for lightweight checks such as regex-based scanning, and a poor fit for model-backed detection. + +### OpenShell-managed image or sidecar + +OpenShell pulls and runs the middleware image itself, for example as a sidecar of the sandbox. This improves the user experience by removing the need to operate a separate central service, and keeps processing local. In exchange, OpenShell takes on lifecycle management and resource concerns, and on its own it does not provide the isolation benefit of the sandboxed option above unless combined with policy enforcement. diff --git a/rfc/0009-supervisor-middleware/appendices/protocol-extensions.md b/rfc/0009-supervisor-middleware/appendices/protocol-extensions.md new file mode 100644 index 0000000000..924c7bd699 --- /dev/null +++ b/rfc/0009-supervisor-middleware/appendices/protocol-extensions.md @@ -0,0 +1,86 @@ +# Appendix: Protocol Extensions + +> This is an appendix to the [RFC](../README.md). Please familiarize yourself with the RFC before reading this. + +The v1 contract is intentionally minimal: one HTTP request hook, buffered unary calls, an `allow`/`deny` decision plus optional transformed content, findings, and metadata. This appendix records extensions the proto should not preclude, so v1 stays small without painting future work into a corner. None of these are committed; they exist to validate that the v1 shape is forward-compatible. + +## Streaming + +The v1 `EvaluateHttpRequest` RPC is unary. The supervisor buffers the bounded request body, sends one `HttpRequestEvaluation`, and receives one `HttpRequestResult`. Streaming is deliberately left out of that method: if OpenShell later needs chunked payload transport or incremental processing, it should add a separate operation-specific method rather than changing `EvaluateHttpRequest` cardinality. + +This section records what such a future streaming operation would need to consider, and importantly what streaming does and does not buy, since the distinction is easy to get wrong. + +### Transport streaming vs processing streaming + +These are different concepts and are easy to conflate: + +- **Transport streaming** - a separate gRPC operation carries multiple messages (chunks). This is what a service would advertise in its manifest and what the supervisor would negotiate. +- **Processing streaming** - the middleware can act on partial content before it has the whole body. + +The manifest field would govern only the transport. It would not promise the middleware can process incrementally. + +### Full-body guards still buffer + +Many guards need the entire body to do anything: a JSON-aware redactor must parse the whole document, and a PII scan must see all of it. Such a guard, even over a streaming transport, accumulates every chunk internally, then parses, then emits a single response at end-of-stream - the decision still arrives after the last byte. Incremental processing only helps narrower cases such as byte-level regex redaction or secret scanning over a text stream. + +### Why add a streaming operation later + +Even when the middleware must buffer the full body, a separate chunked transport operation would buy two things: + +- It moves the large buffer off the supervisor. The supervisor does not hold a multi-MB body to put in a single message; the middleware, which needs it anyway and can be resourced for it, accumulates it. +- It avoids gRPC's per-message size limit (4 MB by default). A 20 MB inference request cannot fit in one message without raising limits, but it can be chunked. + +This is the strongest reason to keep the door open for a streaming operation, more so than incremental parsing. + +### How it would work + +A service would advertise chunked-transport support (and limits) in `Describe`. When supported, the supervisor could use the streaming operation and send the body as a sequence of messages. When not supported, it would continue to use the unary v1 operation, and a body over the unary cap would use the middleware config's `on_error` behavior. + +The streaming method should have its own messages instead of reusing `HttpRequestEvaluation` directly. Within a single streamed request, the first message would carry the request context plus the first body bytes, and subsequent messages would carry only further body chunks that the middleware appends; stream close would mark end of request. This keeps the v1 unary messages flat and gives streaming its own cleaner shape. + +A cleaner phased design using a `oneof` over `context` and `body_chunk`, in the style of Envoy `ext_proc`, is available for a future streaming operation because it would not need to preserve the unary v1 message shape. V1 keeps the flat unary request because it is simpler for bounded bodies and avoids making every middleware implement streaming mechanics before the need is proven. + +## Additional operation phases + +V1 defines a single typed operation, `HTTP_REQUEST/PRE_CREDENTIALS`, which runs after network and L7 policy admit a request and before credential injection. The same service interface can host more operations, each advertised through the `Describe` manifest and invoked through an operation-specific method such as `EvaluateHttpRequest`. Each operation and phase pair encodes a different position in the proxy flow: + +- `Connection/before_policy` / `HttpRequest/before_policy` - *before* network/L7 policy admits the request, for earlier classification. Riskier, because request content reaches a service before policy has allowed the request. +- `HTTP_REQUEST/PRE_CREDENTIALS` (v1) - after policy admits the request, before credential injection. +- `HttpRequest/post_credentials` - after credential injection, immediately before the relay writes the request upstream. This hook is credential-visible, so it is built-in-only: OpenShell marks it as a restricted hook and rejects any externally registered middleware that advertises it during manifest validation. The motivating use is request signing that must run after credentials are injected - for example a built-in `openshell/sigv4` that strips placeholder-signed AWS headers and signs the finalized request with supervisor-resolved credentials just before it is sent upstream. +- `HttpResponse/completed` - after an upstream request completes, emit metadata such as status, content length, selected route, selected model, and model usage if available. This is notification-only: no body, no transformation, and no allow/deny verdict. It would let reservation-style budget middleware reconcile a pre-dispatch decision without introducing response-body inspection. +- `HttpResponse/before_return` - on the return path, after the upstream responds and before the response reaches the sandbox; inspect or redact upstream responses. +- `WebSocketMessage/before_forward` / `WebSocketMessage/before_return` - after a WebSocket or streaming protocol upgrade, on each forwarded or returned message, well past the one-shot request path. + +Pre-policy phases run earliest, the two request phases bracket credential injection, response notifications and response phases run after the upstream call, and message phases run later, sometimes on a different path entirely. Of these, only `HTTP_REQUEST/PRE_CREDENTIALS` is part of v1. `HttpRequest/post_credentials` is the nearest planned request-path follow-up and is kept built-in-only because it sees injected credentials; `HttpResponse/completed` is a separate future notification hook for metadata-only post-call reconciliation. + +## Semantic context + +v1 sends the full request and lets the middleware interpret it. A future version can carry parsed semantic context (request category, semantic protocol such as OpenAI chat completions or Anthropic messages, and modalities) on `HttpRequestEvaluation`, and let policy target a semantic scope (latest user message, image parts, tool inputs). This also requires corresponding manifest fields so OpenShell can validate that a policy only references scopes and protocols the service supports. + +## Content preview + +ICAP-style previewing: send only the first N bytes so the service can decide whether it needs the full body before OpenShell buffers it. This reduces buffering cost for large requests that turn out not to require processing. + +## Portable feature contracts and binding + +A future version can introduce named feature contracts, such as `pii-redaction`, with a mapping from that portable contract to a concrete service binding. Policy would then stay portable across interchangeable implementations. V1 references a service-owned binding ID directly and defers this additional indirection. + +## Header mutation rules + +V1 preserves duplicate request headers and their wire order. Before an external invocation, OpenShell omits credential-bearing, routing, framing, hop-by-hop, and `Connection`-nominated headers. Results return ordered `write` and `remove` mutations. Writes support append, overwrite, and skip modes but may target only `x-openshell-middleware-*`. Removes may target other visible headers except the protected categories. OpenShell validates and applies a stage's mutations atomically, so one invalid mutation discards the whole set and follows that config's `on_error` behavior. + +## Middleware authentication + +Supervisor middleware exposes gRPC services over network endpoints. The stable transport contract requires confidentiality and authentication of the intended middleware service. Endpoint declaration, identity binding, credential material, and rotation must be explicit rather than left as deployment-specific conventions. + +Phase 1 may temporarily support unauthenticated plaintext gRPC only when the operator explicitly sets `allow_insecure = true` on the middleware entry. A plaintext `http://` endpoint without this opt-in is rejected. OpenShell emits a prominent warning and records auditable configuration state whenever the exception is enabled, so insecure operation is always deliberate and visible. + +This mode is suitable only for trusted local development, loopback services, or isolated research environments where the middleware endpoint is not reachable by untrusted clients. It is not suitable for shared clusters, multi-tenant deployments, public networks, or any environment where inspected request content needs transport confidentiality. + +Without middleware authentication and transport security, network observers can read inspected request content, active attackers can impersonate the middleware service, and unauthorized clients can call the middleware directly if it is reachable. Because the middleware can allow, deny, or transform egress, service impersonation is a policy-enforcement bypass, not just an observability risk. + +Phase 2 removes plaintext endpoint support and removes `allow_insecure`. Every external middleware connection must then provide authenticated encrypted transport. This is an intentional research-preview breaking change, so phase 1 plaintext configurations have no long-term compatibility guarantee and must migrate before phase 2. + +The exact phase 2 mechanism is deferred. Follow-up protocol work should choose and specify mTLS, TLS plus explicit caller authentication, or an equivalent design, including trust roots, client identity, credential delivery, certificate or key rotation, middleware identity binding, and how supervisors receive authentication material. + +Even during the phase 1 plaintext exception, the hook stays before provider credential injection, and OpenShell does not forward original `Authorization`, `Cookie`, or other protected headers to middleware. This preserves the separation between content inspection and upstream credential injection while authenticated transport is completed. From 5402551797585268356d84b2a3a1c99f1031f076 Mon Sep 17 00:00:00 2001 From: Drew Newberry Date: Thu, 16 Jul 2026 16:46:39 -0700 Subject: [PATCH 3/5] test(e2e): run VM suite in CI (#2305) * test(e2e): run VM suite in CI Signed-off-by: Drew Newberry * fix(ci): configure KVM permissions directly Signed-off-by: Drew Newberry * fix(e2e): flush VM overlay before restart Signed-off-by: Drew Newberry * docs: simplify VM test documentation Signed-off-by: Drew Newberry * test(e2e): include gateway resume in VM run Signed-off-by: Drew Newberry --------- Signed-off-by: Drew Newberry --- .github/workflows/e2e-test.yml | 64 +++++++++++++++++++++++++++++ CI.md | 3 +- TESTING.md | 7 ++++ architecture/build.md | 3 +- e2e/rust/e2e-vm.sh | 1 + e2e/rust/tests/vm_gateway_resume.rs | 5 ++- 6 files changed, 80 insertions(+), 3 deletions(-) diff --git a/.github/workflows/e2e-test.yml b/.github/workflows/e2e-test.yml index ea870d98e1..cb7bc67d19 100644 --- a/.github/workflows/e2e-test.yml +++ b/.github/workflows/e2e-test.yml @@ -205,3 +205,67 @@ jobs: - name: Print AppArmor denials if: always() run: sudo dmesg | grep -E 'apparmor=.*DENIED|profile="unprivileged_userns"' | tail -100 || true + + e2e-vm: + name: E2E (rust-vm) + # libkrun needs KVM, so this job must run directly on a GitHub-hosted + # Linux VM. GitHub-hosted macOS runners do not support nested + # virtualization, and a job container would hide the host KVM device. + runs-on: ubuntu-24.04 + timeout-minutes: 90 + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + MISE_GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + steps: + - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + with: + ref: ${{ inputs['checkout-ref'] || github.sha }} + persist-credentials: false + + - name: Enable KVM access + run: | + set -euo pipefail + if [[ ! -c /dev/kvm ]]; then + echo "::error::The GitHub-hosted runner did not expose /dev/kvm" + lscpu + grep -m1 -E '^(flags|Features)' /proc/cpuinfo || true + ls -la /dev + exit 1 + fi + sudo chmod 0666 /dev/kvm + ls -l /dev/kvm + test -r /dev/kvm + test -w /dev/kvm + + - name: Install system dependencies + run: | + sudo apt-get update + sudo apt-get install -y --no-install-recommends \ + build-essential \ + clang \ + cmake \ + libclang-dev \ + libssl-dev \ + libz3-dev \ + openssh-client \ + pkg-config \ + socat \ + zstd + + - name: Install mise + run: | + curl https://mise.run | MISE_VERSION=v2026.4.25 sh + echo "$HOME/.local/bin" >> "$GITHUB_PATH" + echo "$HOME/.local/share/mise/shims" >> "$GITHUB_PATH" + + - name: Install tools + run: mise install --locked + + - name: Cache Rust target and registry + uses: Swatinem/rust-cache@c19371144df3bb44fab255c43d04cbc2ab54d1c4 # v2 + with: + shared-key: e2e-vm-linux-amd64 + cache-on-failure: "true" + + - name: Run VM E2E + run: mise run --no-deps --skip-deps e2e:vm diff --git a/CI.md b/CI.md index e14d5bdb9d..19fad7bd35 100644 --- a/CI.md +++ b/CI.md @@ -14,7 +14,8 @@ Merge queue validation is a second integration gate for `main`. After a PR has p Three opt-in labels enable the long-running E2E suites: -- `test:e2e` runs the standard E2E suite in `Branch E2E Checks` +- `test:e2e` runs the standard Docker, rootless Podman, Kubernetes, and VM E2E + suites in `Branch E2E Checks` - `test:e2e-gpu` runs GPU E2E in `Branch E2E Checks` - `test:e2e-kubernetes` runs Kubernetes E2E with the HA Helm overlay (`replicaCount: 2` and bundled PostgreSQL) in `Branch E2E Checks` diff --git a/TESTING.md b/TESTING.md index d32dc385c2..a032baa5ea 100644 --- a/TESTING.md +++ b/TESTING.md @@ -150,6 +150,7 @@ Suites: - Common suite (`--features e2e`) - driver-neutral CLI behavior, sandbox lifecycle, sync, port forwarding, policy, and provider tests. - Docker suite (`--features e2e-docker`) - common suite plus Docker-only coverage such as Dockerfile image builds, Docker preflight checks, and managed Docker gateway resume. - Docker GPU suite (`--features e2e-docker-gpu`) - Docker suite plus GPU sandbox smoke coverage. +- VM suite (`--features e2e-vm`) - runs e2e tests on a VM. GPU device-selection tests compare OpenShell sandboxes against a plain Docker or Podman container that requests `--device nvidia.com/gpu=all`. The probe image @@ -173,6 +174,12 @@ Run the Podman-backed Rust CLI e2e suite: mise run e2e:podman ``` +Run the VM-backed Rust CLI e2e suite: + +```shell +mise run e2e:vm +``` + Run a single test directly with cargo: ```shell diff --git a/architecture/build.md b/architecture/build.md index e3ac5012e3..63d4e56849 100644 --- a/architecture/build.md +++ b/architecture/build.md @@ -148,7 +148,8 @@ The high-level CI model: 1. PR-context gate jobs publish required statuses for the PR head commit. 2. Standard branch checks run from trusted mirror branches. -3. Label-gated E2E, GPU, and Kubernetes checks run from trusted mirror branches. +3. Label-gated Docker, Podman, VM, GPU, and Kubernetes E2E checks run from + trusted mirror branches. 4. Merge-group checks run against GitHub's temporary queue branch for the final integration state. 5. Gate jobs verify that the mirror branch matches the PR head, or that the merge-group workflow ran for the queued SHA, and that the expected non-gate workflow actually ran. 6. Release workflows rebuild and publish binaries, wheels, images, and docs. diff --git a/e2e/rust/e2e-vm.sh b/e2e/rust/e2e-vm.sh index ef798a8ea9..8005d09bd0 100755 --- a/e2e/rust/e2e-vm.sh +++ b/e2e/rust/e2e-vm.sh @@ -315,4 +315,5 @@ if [ -n "${E2E_TEST_OVERRIDE}" ]; then else run_e2e_test smoke run_e2e_test host_gateway_alias + run_e2e_test vm_gateway_resume fi diff --git a/e2e/rust/tests/vm_gateway_resume.rs b/e2e/rust/tests/vm_gateway_resume.rs index b2ec6c8b57..4c502bb9c9 100644 --- a/e2e/rust/tests/vm_gateway_resume.rs +++ b/e2e/rust/tests/vm_gateway_resume.rs @@ -36,8 +36,11 @@ async fn vm_gateway_restart_resumes_running_sandbox() { .await .expect("gateway should start healthy"); + // The gateway restart terminates the VM process before re-adopting its + // overlay. Flush the marker before reporting readiness so the assertion + // verifies durable overlay state rather than guest page-cache timing. let script = format!( - "echo before-restart > {RESUME_FILE}; echo {READY_MARKER}; while true; do sleep 1; done" + "echo before-restart > {RESUME_FILE}; sync; echo {READY_MARKER}; while true; do sleep 1; done" ); let mut sandbox = SandboxGuard::create_keep(&["sh", "-lc", &script], READY_MARKER) .await From d70adafe5b0cccce2019ffe8a9b00ad1538965cc Mon Sep 17 00:00:00 2001 From: bornav <51048565+bornav@users.noreply.github.com> Date: Fri, 17 Jul 2026 02:28:53 +0200 Subject: [PATCH 4/5] fix(vm-driver): fixes BYOC sandbox creation failing with ext4-fs write access unavailable (#2150) --- .../scripts/openshell-vm-sandbox-init.sh | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/openshell-driver-vm/scripts/openshell-vm-sandbox-init.sh b/crates/openshell-driver-vm/scripts/openshell-vm-sandbox-init.sh index d70e8c3ef5..14dbc0466b 100644 --- a/crates/openshell-driver-vm/scripts/openshell-vm-sandbox-init.sh +++ b/crates/openshell-driver-vm/scripts/openshell-vm-sandbox-init.sh @@ -247,6 +247,10 @@ setup_overlay_root() { if [ "${OPENSHELL_VM_INIT_MODE:-sandbox}" = "image-prep" ]; then prepare_guest_image_rootfs sync + if ! umount /overlay; then + ts "FATAL: failed to unmount /overlay cleanly after image-prep; refusing to produce a dirty image-cache disk" + exit 1 + fi ts "image-prep complete" exit 0 fi @@ -256,7 +260,7 @@ setup_overlay_root() { local lower_root="/lower" if [ -b /dev/vdc ]; then - mount -t ext4 -o ro /dev/vdc /image-cache + mount -t ext4 -o ro,noload /dev/vdc /image-cache if [ -d /image-cache/image-rootfs ]; then lower_root="/image-cache/image-rootfs" ts "using prepared image rootfs lowerdir" From d556748771c41cbbd4e4dd7cd9030c798afe2b7d Mon Sep 17 00:00:00 2001 From: Piotr Mlocek Date: Thu, 16 Jul 2026 17:47:49 -0700 Subject: [PATCH 5/5] feat(supervisor-middleware): add network egress middleware (#2027) Signed-off-by: Piotr Mlocek --- AGENTS.md | 8 + CONTRIBUTING.md | 1 + Cargo.lock | 40 + Cargo.toml | 1 + architecture/gateway.md | 11 + architecture/sandbox.md | 31 +- architecture/security-policy.md | 4 + crates/openshell-cli/src/run.rs | 36 +- crates/openshell-core/Cargo.toml | 1 + crates/openshell-core/README.md | 14 + crates/openshell-core/src/grpc_client.rs | 4 + crates/openshell-core/src/host_pattern.rs | 348 ++ crates/openshell-core/src/lib.rs | 2 + crates/openshell-core/src/middleware.rs | 107 + crates/openshell-core/src/proto/mod.rs | 14 + crates/openshell-core/src/proto_struct.rs | 107 +- crates/openshell-driver-docker/src/tests.rs | 39 +- .../openshell-driver-kubernetes/src/driver.rs | 37 +- .../openshell-driver-podman/src/container.rs | 39 +- crates/openshell-driver-podman/src/driver.rs | 39 +- crates/openshell-ocsf/src/builders/finding.rs | 14 + crates/openshell-ocsf/src/builders/http.rs | 16 + crates/openshell-ocsf/src/format/shorthand.rs | 229 +- crates/openshell-policy/Cargo.toml | 1 + crates/openshell-policy/src/lib.rs | 558 ++- crates/openshell-policy/src/middleware.rs | 312 ++ crates/openshell-sandbox/Cargo.toml | 3 + crates/openshell-sandbox/src/lib.rs | 570 ++- .../openshell-sandbox/src/sidecar_control.rs | 4 +- crates/openshell-sdk/tests/client_mock.rs | 2 +- crates/openshell-server/Cargo.toml | 2 + crates/openshell-server/src/config_file.rs | 65 + crates/openshell-server/src/grpc/policy.rs | 264 +- crates/openshell-server/src/grpc/sandbox.rs | 1 + .../openshell-server/src/grpc/validation.rs | 24 + crates/openshell-server/src/lib.rs | 27 + crates/openshell-server/src/middleware.rs | 80 + .../Cargo.toml | 27 + .../src/lib.rs | 202 + .../src/regex.rs | 132 + .../Cargo.toml | 27 + .../src/headers.rs | 417 ++ .../src/lib.rs | 3514 +++++++++++++++++ .../src/remote.rs | 85 + .../openshell-supervisor-network/Cargo.toml | 5 + .../data/sandbox-policy.rego | 8 +- .../src/l7/middleware.rs | 727 ++++ .../src/l7/mod.rs | 1 + .../src/l7/relay.rs | 2391 ++++++++++- .../src/l7/rest.rs | 1780 ++++++++- .../src/l7/token_grant_injection.rs | 57 +- .../openshell-supervisor-network/src/opa.rs | 1065 ++++- .../openshell-supervisor-network/src/proxy.rs | 1131 +++++- docs/extensibility/supervisor-middleware.mdx | 179 + docs/index.yml | 2 + docs/observability/logging.mdx | 17 +- docs/reference/gateway-config.mdx | 34 + docs/reference/policy-schema.mdx | 39 +- docs/sandboxes/policies.mdx | 44 +- proto/sandbox.proto | 50 + proto/supervisor_middleware.proto | 242 ++ 61 files changed, 14446 insertions(+), 785 deletions(-) create mode 100644 crates/openshell-core/src/host_pattern.rs create mode 100644 crates/openshell-core/src/middleware.rs create mode 100644 crates/openshell-policy/src/middleware.rs create mode 100644 crates/openshell-server/src/middleware.rs create mode 100644 crates/openshell-supervisor-middleware-builtins/Cargo.toml create mode 100644 crates/openshell-supervisor-middleware-builtins/src/lib.rs create mode 100644 crates/openshell-supervisor-middleware-builtins/src/regex.rs create mode 100644 crates/openshell-supervisor-middleware/Cargo.toml create mode 100644 crates/openshell-supervisor-middleware/src/headers.rs create mode 100644 crates/openshell-supervisor-middleware/src/lib.rs create mode 100644 crates/openshell-supervisor-middleware/src/remote.rs create mode 100644 crates/openshell-supervisor-network/src/l7/middleware.rs create mode 100644 docs/extensibility/supervisor-middleware.mdx create mode 100644 proto/supervisor_middleware.proto diff --git a/AGENTS.md b/AGENTS.md index 4d1e6499fe..8bb43f0992 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -42,7 +42,15 @@ These pipelines connect skills into end-to-end workflows. Individual skill files | `crates/openshell-tui/` | Terminal UI | Ratatui-based dashboard for monitoring | | `crates/openshell-driver-kubernetes/` | Kubernetes compute driver | In-process `ComputeDriver` backend for K8s sandbox pods | | `crates/openshell-driver-docker/` | Docker compute driver | In-process `ComputeDriver` backend for local Docker sandbox containers | +| `crates/openshell-driver-podman/` | Podman compute driver | In-process `ComputeDriver` backend for local Podman sandbox containers | | `crates/openshell-driver-vm/` | VM compute driver | Standalone libkrun-backed `ComputeDriver` subprocess (embeds its own rootfs + runtime) | +| `crates/openshell-prover/` | Policy prover | Policy verification and proof generation | +| `crates/openshell-server-macros/` | Server macros | Compile-time helpers for gateway RPC authorization | +| `crates/openshell-supervisor-middleware/` | Middleware runtime | Generic middleware registry, remote service integration, and chain execution | +| `crates/openshell-supervisor-middleware-builtins/` | Built-in middleware | First-party in-process middleware implementations | +| `crates/openshell-supervisor-network/` | Network supervisor | Proxying, L7 enforcement, policy evaluation, and inference routing | +| `crates/openshell-supervisor-process/` | Process supervisor | Process lifecycle, namespace, and bypass monitoring | +| `crates/openshell-vfio/` | VFIO support | PCI and GPU passthrough preparation and lifecycle | | `python/openshell/` | Python SDK | Python bindings and CLI packaging | | `proto/` | Protobuf definitions | gRPC service contracts | | `deploy/` | Docker, Helm, K8s | Dockerfiles, Helm chart, manifests | diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 0a88eabcf5..2e4fb49a69 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -75,6 +75,7 @@ Skills live in `.agents/skills/`. Your agent's harness can discover and load the | Contributing | `create-github-pr` | Create pull requests with proper conventions | | Reviewing | `review-github-pr` | Summarize PR diffs and key design decisions | | Reviewing | `review-security-issue` | Assess security issues for severity and remediation | +| Reviewing | `fix-security-issue` | Implement an approved security remediation plan | | Reviewing | `watch-github-actions` | Monitor CI pipeline status and logs | | Reviewing | `launch-openshell-gator` | Launch and supervise OpenShell gator agents for issue and PR monitoring | | Reviewing | `test-release-canary` | Dispatch and iterate on the Release Canary workflow that smoke-tests published artifacts | diff --git a/Cargo.lock b/Cargo.lock index e507c19bdc..b412467610 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3886,6 +3886,7 @@ version = "0.0.0" dependencies = [ "base64 0.22.1", "chrono", + "glob", "ipnet", "miette", "prost", @@ -4048,6 +4049,7 @@ version = "0.0.0" dependencies = [ "miette", "openshell-core", + "prost-types", "serde", "serde_json", "serde_yml", @@ -4108,9 +4110,12 @@ dependencies = [ "openshell-core", "openshell-ocsf", "openshell-policy", + "openshell-supervisor-middleware", + "openshell-supervisor-middleware-builtins", "openshell-supervisor-network", "openshell-supervisor-process", "prost", + "prost-types", "rustls 0.23.38", "serde", "serde_json", @@ -4191,6 +4196,8 @@ dependencies = [ "openshell-providers", "openshell-router", "openshell-server-macros", + "openshell-supervisor-middleware", + "openshell-supervisor-middleware-builtins", "petname", "pin-project-lite", "prost", @@ -4233,6 +4240,34 @@ dependencies = [ "syn 2.0.117", ] +[[package]] +name = "openshell-supervisor-middleware" +version = "0.0.0" +dependencies = [ + "miette", + "openshell-core", + "openshell-supervisor-middleware-builtins", + "prost", + "prost-types", + "tokio", + "tokio-stream", + "tonic", +] + +[[package]] +name = "openshell-supervisor-middleware-builtins" +version = "0.0.0" +dependencies = [ + "miette", + "openshell-core", + "prost-types", + "regex", + "serde", + "serde_json", + "tokio", + "tonic", +] + [[package]] name = "openshell-supervisor-network" version = "0.0.0" @@ -4255,6 +4290,9 @@ dependencies = [ "openshell-ocsf", "openshell-policy", "openshell-router", + "openshell-supervisor-middleware", + "openshell-supervisor-middleware-builtins", + "prost-types", "rcgen", "regorus", "reqwest 0.12.28", @@ -4272,8 +4310,10 @@ dependencies = [ "tokio", "tokio-rustls 0.26.4", "tokio-tungstenite 0.26.2", + "tonic", "tower-mcp-types", "tracing", + "tracing-subscriber", "uuid", "webpki-roots 1.0.7", ] diff --git a/Cargo.toml b/Cargo.toml index 84e6d1b963..7081fe97e2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -75,6 +75,7 @@ serde_yml = "0.0.12" toml = "0.8" apollo-parser = "0.8.5" tower-mcp-types = "0.12.0" +regex = "1" # HTTP client reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls-native-roots"] } diff --git a/architecture/gateway.md b/architecture/gateway.md index 733ce68c25..cca6599281 100644 --- a/architecture/gateway.md +++ b/architecture/gateway.md @@ -369,6 +369,17 @@ config path. A gateway-global policy can override sandbox-scoped policy. The sandbox supervisor polls for config revisions and hot-reloads dynamic policy when the policy engine accepts the update. +External supervisor middleware registration is operator-owned configuration +under `[[openshell.supervisor.middleware]]`. At startup the gateway connects to +each service and validates its described bindings and operator body limit. +Policies attach a complete external middleware by its operator-owned registration +name. Manifest bindings are identified by operation and phase, and each manifest +may declare at most one binding for an operation and phase pair. +Before persisting a policy, the gateway asks each selected implementation to +validate its config. The effective sandbox config contains only the registered +services required by that policy; supervisors invoke those services directly on +the request path. + Provider credential expiry is enforced during gateway-to-sandbox credential resolution and again by the sandbox placeholder resolver. This keeps expired credentials from resolving even when a running sandbox still has retained diff --git a/architecture/sandbox.md b/architecture/sandbox.md index 30d1bf4783..d2cb44d7b8 100644 --- a/architecture/sandbox.md +++ b/architecture/sandbox.md @@ -66,6 +66,31 @@ matchers; generic JSON-RPC rules match only the method. JSON-RPC responses and server-to-client MCP messages on response or SSE streams are relayed but are not currently parsed for policy enforcement. +For admitted HTTP requests, the proxy can run an ordered supervisor middleware +chain after L7 policy evaluation and before credential injection. Destination +host selectors choose the chain independently of the network rule that admitted +the request. Policy-local map keys identify configs, while built-in names or +operator-owned registration names identify implementations. + +Built-ins run in-process; operator services use the same bounded gRPC contract. +`openshell-policy` validates policy-owned structure, and the active middleware +registry validates implementation-owned config. The generic registry and chain +runner live in `openshell-supervisor-middleware`; first-party implementations +live in `openshell-supervisor-middleware-builtins`. + +The supervisor installs policy and middleware registry changes as one runtime +generation and preserves the last-known-good generation if preparation fails. +Policy-only updates reuse the connected registry, so an external middleware +outage cannot block unrelated policy changes. + +Middleware cannot observe injected credentials or mutate supervisor-owned +credential, routing, or framing headers. Body transformations are re-evaluated +against body-aware L7 policy before later stages or the upstream can observe +them. Requests, results, chain length, execution time, and diagnostics are +bounded; external free-form diagnostic text is not exposed in responses or +security logs. See [Supervisor Middleware](../docs/extensibility/supervisor-middleware.mdx) +for configuration and protocol details. + `https://inference.local` is special. It bypasses OPA network policy and is handled by the inference interception path: @@ -206,8 +231,10 @@ engine with a gateway policy revision. ## Failure Behavior - If gateway config polling fails, the sandbox keeps its last-known-good policy. -- If a live policy update is invalid, the supervisor rejects it and keeps the - current policy. +- If a live policy or middleware-registry update is invalid, the supervisor + rejects the combined update and keeps the current runtime pair. +- If an operator-run middleware call fails, the selected config's `on_error` + behavior decides whether to deny the request or continue without that stage. - Existing raw byte streams are connection scoped. Dynamic policy changes apply to new connections or the next parsed HTTP request where the proxy can safely re-evaluate. diff --git a/architecture/security-policy.md b/architecture/security-policy.md index 10a8400fb9..a4d20b9b0f 100644 --- a/architecture/security-policy.md +++ b/architecture/security-policy.md @@ -194,6 +194,10 @@ Sandbox events that represent observable behavior use OCSF structured logs: Use plain tracing for internal plumbing such as retries, debug state, and intermediate steps where the final observable event is logged separately. +Forward-proxy success is a final observable event: emit it only after +middleware, token grants, credential rewriting, policy-generation checks, and +the HTTP relay have succeeded so a later denial cannot coexist with an allowed +record for the same request. Never log secrets, credentials, bearer tokens, or query parameters in OCSF messages. OCSF JSONL output may be shipped to external systems. diff --git a/crates/openshell-cli/src/run.rs b/crates/openshell-cli/src/run.rs index 0793228f64..e6fe5d5e50 100644 --- a/crates/openshell-cli/src/run.rs +++ b/crates/openshell-cli/src/run.rs @@ -1818,39 +1818,9 @@ fn parse_driver_config_json(value: &str) -> Result { )); }; - Ok(prost_types::Struct { - fields: fields - .into_iter() - .map(|(key, value)| json_to_protobuf_value(value).map(|value| (key, value))) - .collect::>()?, - }) -} - -fn json_to_protobuf_value(value: serde_json::Value) -> Result { - use prost_types::{ListValue, Struct, Value, value::Kind}; - - let kind = match value { - serde_json::Value::Null => Kind::NullValue(0), - serde_json::Value::Bool(value) => Kind::BoolValue(value), - serde_json::Value::Number(value) => Kind::NumberValue(value.as_f64().ok_or_else(|| { - miette!("--driver-config-json contains a number that cannot be represented") - })?), - serde_json::Value::String(value) => Kind::StringValue(value), - serde_json::Value::Array(values) => Kind::ListValue(ListValue { - values: values - .into_iter() - .map(json_to_protobuf_value) - .collect::>()?, - }), - serde_json::Value::Object(fields) => Kind::StructValue(Struct { - fields: fields - .into_iter() - .map(|(key, value)| json_to_protobuf_value(value).map(|value| (key, value))) - .collect::>()?, - }), - }; - - Ok(Value { kind: Some(kind) }) + openshell_core::proto_struct::json_object_to_struct(fields) + .into_diagnostic() + .wrap_err("--driver-config-json contains a value that cannot be represented") } fn validate_cpu_quantity(value: &str) -> Result { diff --git a/crates/openshell-core/Cargo.toml b/crates/openshell-core/Cargo.toml index 0ff6d06d6c..53735a6bb8 100644 --- a/crates/openshell-core/Cargo.toml +++ b/crates/openshell-core/Cargo.toml @@ -11,6 +11,7 @@ license.workspace = true repository.workspace = true [dependencies] +glob = { workspace = true } prost = { workspace = true } prost-types = { workspace = true } tonic = { workspace = true, features = ["channel", "tls-native-roots"] } diff --git a/crates/openshell-core/README.md b/crates/openshell-core/README.md index 51da847b82..b4cdb05f5d 100644 --- a/crates/openshell-core/README.md +++ b/crates/openshell-core/README.md @@ -50,3 +50,17 @@ router agree on provider defaults. Profiles define: Do not duplicate provider-specific inference behavior in callers. Add shared behavior here, then consume it from the gateway, sandbox, and router. + +## Middleware Contracts + +Built-in supervisor middleware identifiers, host-selector matching, and pure +configuration validation live in `openshell_core::middleware`. Policy admission +and the supervisor runtime consume the same contract without introducing a +dependency from the policy crate to the supervisor implementation. + +## Protobuf Struct Conversion + +Use `openshell_core::proto_struct` when crossing between `serde_json` values and +`prost_types::{Struct, Value}`. Both conversion directions live in this module; +JSON-to-protobuf conversion is fallible so callers cannot silently replace an +unrepresentable number. diff --git a/crates/openshell-core/src/grpc_client.rs b/crates/openshell-core/src/grpc_client.rs index 373635ae15..b18cbb1293 100644 --- a/crates/openshell-core/src/grpc_client.rs +++ b/crates/openshell-core/src/grpc_client.rs @@ -573,6 +573,8 @@ pub async fn fetch_policy(endpoint: &str, sandbox_id: &str) -> Result, } fn settings_poll_result(inner: crate::proto::GetSandboxConfigResponse) -> SettingsPollResult { @@ -748,6 +751,7 @@ fn settings_poll_result(inner: crate::proto::GetSandboxConfigResponse) -> Settin settings: inner.settings, global_policy_version: inner.global_policy_version, provider_env_revision: inner.provider_env_revision, + supervisor_middleware_services: inner.supervisor_middleware_services, } } diff --git a/crates/openshell-core/src/host_pattern.rs b/crates/openshell-core/src/host_pattern.rs new file mode 100644 index 0000000000..f5d9a099a0 --- /dev/null +++ b/crates/openshell-core/src/host_pattern.rs @@ -0,0 +1,348 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! DNS-label-aware host patterns and selectors. + +use std::collections::{HashSet, VecDeque}; + +/// A validated, compiled DNS host pattern. +/// +/// Matching is case-insensitive. A `*` wildcard stays within one DNS label, +/// while a label consisting only of `**` consumes one or more labels. These +/// semantics mirror the Rego endpoint glob matching used for network policy +/// admission (`glob.match` with a `.` delimiter), so a pattern copied from a +/// network endpoint selects exactly the hosts that endpoint admits. +#[derive(Clone)] +pub struct HostPattern { + source: String, + labels: Vec, +} + +#[derive(Clone)] +enum HostLabelPattern { + Recursive, + Label { + source: String, + pattern: glob::Pattern, + literal: bool, + }, +} + +/// A validated destination host selector. +/// +/// Includes are evaluated first and exclusions take precedence. Constructing +/// the selector compiles every pattern once, so request-time selection cannot +/// fail due to malformed input. +#[derive(Clone)] +pub struct HostSelector { + includes: Vec, + excludes: Vec, +} + +impl HostSelector { + pub fn new(include: &[String], exclude: &[String]) -> Result { + if include.is_empty() { + return Err("endpoint selector must include at least one host pattern".to_string()); + } + Ok(Self { + includes: include + .iter() + .map(|pattern| HostPattern::new(pattern)) + .collect::>()?, + excludes: exclude + .iter() + .map(|pattern| HostPattern::new(pattern)) + .collect::>()?, + }) + } + + #[must_use] + pub fn matches(&self, host: &str) -> bool { + self.includes.iter().any(|pattern| pattern.matches(host)) + && !self.excludes.iter().any(|pattern| pattern.matches(host)) + } + + /// Conservatively determine whether this selector can match a concrete + /// host admitted by `candidate`. + #[must_use] + pub fn may_match_pattern(&self, candidate: &HostPattern) -> bool { + self.includes.iter().any(|include| { + if !include.overlaps(candidate) { + return false; + } + + let concrete_intersection = candidate.literal().or_else(|| include.literal()); + let excluded = concrete_intersection.map_or_else( + || { + self.excludes.iter().any(|excluded| { + excluded.is_universal() + || excluded.source == include.source + || excluded.source == candidate.source + }) + }, + |host| self.excludes.iter().any(|excluded| excluded.matches(host)), + ); + !excluded + }) + } +} + +impl HostPattern { + pub fn new(pattern: &str) -> Result { + if pattern.is_empty() { + return Err("host pattern must not be empty".to_string()); + } + if pattern.chars().any(char::is_whitespace) { + return Err("host pattern must not contain whitespace".to_string()); + } + // The glob crate treats braces as literal characters while endpoint + // glob matching expands them, so a brace pattern would silently never + // match a real host. Fail loud instead. + if pattern.chars().any(|ch| matches!(ch, '{' | '}')) { + return Err( + "host pattern must not contain brace alternates; list each host pattern separately" + .to_string(), + ); + } + + let source = pattern.to_ascii_lowercase(); + if source.split('.').any(str::is_empty) { + return Err("host pattern must not contain empty DNS labels".to_string()); + } + let labels = source + .split('.') + .map(|label| { + if label == "**" { + return Ok(HostLabelPattern::Recursive); + } + let pattern = glob::Pattern::new(label) + .map_err(|error| format!("invalid host pattern: {error}"))?; + Ok(HostLabelPattern::Label { + source: label.to_string(), + pattern, + literal: !label.chars().any(|ch| matches!(ch, '*' | '?' | '[')), + }) + }) + .collect::, String>>()?; + Ok(Self { source, labels }) + } + + #[must_use] + pub fn matches(&self, host: &str) -> bool { + let host = host.to_ascii_lowercase(); + if host.split('.').any(str::is_empty) { + return false; + } + self.matches_labels(&host.split('.').collect::>()) + } + + fn matches_labels(&self, host: &[&str]) -> bool { + let mut pending = vec![(0, 0)]; + let mut visited = HashSet::new(); + while let Some((pattern_idx, host_idx)) = pending.pop() { + if !visited.insert((pattern_idx, host_idx)) { + continue; + } + if pattern_idx == self.labels.len() && host_idx == host.len() { + return true; + } + match self.labels.get(pattern_idx) { + Some(HostLabelPattern::Recursive) if host_idx < host.len() => { + pending.push((pattern_idx + 1, host_idx + 1)); + pending.push((pattern_idx, host_idx + 1)); + } + Some(HostLabelPattern::Label { pattern, .. }) if host_idx < host.len() => { + if pattern.matches(host[host_idx]) { + pending.push((pattern_idx + 1, host_idx + 1)); + } + } + Some(_) | None => {} + } + } + false + } + + fn literal(&self) -> Option<&str> { + self.labels + .iter() + .all(|label| matches!(label, HostLabelPattern::Label { literal: true, .. })) + .then_some(self.source.as_str()) + } + + fn is_universal(&self) -> bool { + matches!(self.labels.as_slice(), [HostLabelPattern::Recursive]) + } + + fn overlaps(&self, other: &Self) -> bool { + let mut pending = VecDeque::from([(0, 0)]); + let mut visited = HashSet::new(); + while let Some((left_idx, right_idx)) = pending.pop_front() { + if !visited.insert((left_idx, right_idx)) { + continue; + } + if left_idx == self.labels.len() && right_idx == other.labels.len() { + return true; + } + + let (Some(left), Some(right)) = + (self.labels.get(left_idx), other.labels.get(right_idx)) + else { + continue; + }; + + // Every transition consumes exactly one shared host label, so a + // `**` on either side must consume at least one label before it + // can complete — the same minimum the matcher enforces. + match (left, right) { + (HostLabelPattern::Recursive, HostLabelPattern::Recursive) => { + pending.push_back((left_idx + 1, right_idx + 1)); + pending.push_back((left_idx, right_idx + 1)); + pending.push_back((left_idx + 1, right_idx)); + } + (HostLabelPattern::Recursive, HostLabelPattern::Label { .. }) => { + pending.push_back((left_idx + 1, right_idx + 1)); + pending.push_back((left_idx, right_idx + 1)); + } + (HostLabelPattern::Label { .. }, HostLabelPattern::Recursive) => { + pending.push_back((left_idx + 1, right_idx + 1)); + pending.push_back((left_idx + 1, right_idx)); + } + (left, right) if label_patterns_may_overlap(left, right) => { + pending.push_back((left_idx + 1, right_idx + 1)); + } + _ => {} + } + } + false + } +} + +/// Match a host using DNS-label-aware glob semantics. +/// +/// Matching is case-insensitive. `*` cannot cross a `.` label boundary, while +/// a label consisting of `**` consumes one or more labels. Invalid or empty +/// patterns return an error instead of silently becoming a non-match. +pub fn host_matches(pattern: &str, host: &str) -> Result { + Ok(HostPattern::new(pattern)?.matches(host)) +} + +/// Conservatively determine whether two DNS host patterns can match the same +/// concrete host. +pub fn host_patterns_overlap(left: &str, right: &str) -> Result { + let left = HostPattern::new(left)?; + let right = HostPattern::new(right)?; + Ok(left.overlaps(&right)) +} + +/// Determine whether a selector can match any concrete host admitted by a host +/// pattern. +/// +/// This is conservative for intersections between two non-literal globs: +/// exclusions suppress a conflict only when they cover a known concrete +/// intersection or exactly cover one of the intersecting patterns. +pub fn selector_may_match_pattern( + include: &[String], + exclude: &[String], + candidate: &str, +) -> Result { + let selector = HostSelector::new(include, exclude)?; + let candidate = HostPattern::new(candidate)?; + Ok(selector.may_match_pattern(&candidate)) +} + +fn label_patterns_may_overlap(left: &HostLabelPattern, right: &HostLabelPattern) -> bool { + let ( + HostLabelPattern::Label { + source: left_source, + pattern: left_pattern, + literal: left_literal, + }, + HostLabelPattern::Label { + source: right_source, + pattern: right_pattern, + literal: right_literal, + }, + ) = (left, right) + else { + return true; + }; + + match (*left_literal, *right_literal) { + (true, true) => left_source == right_source, + (true, false) => right_pattern.matches(left_source), + (false, true) => left_pattern.matches(right_source), + (false, false) => true, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn host_matching_is_case_insensitive() { + assert!(host_matches("*.Example.COM", "API.example.com").unwrap()); + assert!(!host_matches("*.example.com", "example.com").unwrap()); + assert!(!host_matches("*.example.com", "deep.api.example.com").unwrap()); + assert!(host_matches("**.example.com", "deep.api.example.com").unwrap()); + assert!(host_matches("*-api.example.com", "tenant-api.example.com").unwrap()); + assert!(!host_matches("*", "deep.api.example.com").unwrap()); + } + + #[test] + fn host_matching_rejects_invalid_patterns() { + assert!(host_matches("", "api.example.com").is_err()); + assert!(host_matches("api .example.com", "api.example.com").is_err()); + assert!(host_matches("api[.example.com", "api.example.com").is_err()); + assert!(host_matches("*.{prod,staging}.example.com", "api.prod.example.com").is_err()); + assert!(host_matches("api**.example.com", "apix.example.com").is_err()); + } + + #[test] + fn recursive_wildcard_requires_at_least_one_label() { + assert!(host_matches("**.example.com", "api.example.com").unwrap()); + assert!(!host_matches("**.example.com", "example.com").unwrap()); + assert!(host_matches("api.**.com", "api.x.y.com").unwrap()); + assert!(!host_matches("api.**.com", "api.com").unwrap()); + } + + #[test] + fn universal_wildcard_matches_any_host() { + for host in [ + "com", + "localhost", + "example.com", + "deep.api.example.com", + "xn--bcher-kva.example", + "tenant-api.internal", + "192.168.1.1", + "[::1]", + ] { + assert!(host_matches("**", host).unwrap(), "** must match {host}"); + } + + // Hosts with empty labels are invalid and never match, even for `**`. + assert!(!host_matches("**", "").unwrap()); + assert!(!host_matches("**", "api.example.com.").unwrap()); + assert!(!host_matches("**", "api..example.com").unwrap()); + } + + #[test] + fn host_pattern_overlap_handles_concrete_and_wildcard_hosts() { + assert!(host_patterns_overlap("*.example.com", "api.example.com").unwrap()); + assert!(host_patterns_overlap("**.example.com", "deep.api.example.com").unwrap()); + assert!(!host_patterns_overlap("*.example.com", "deep.api.example.com").unwrap()); + assert!(!host_patterns_overlap("*.example.com", "*.other.com").unwrap()); + assert!(host_patterns_overlap("**.example.com", "*.api.example.com").unwrap()); + assert!(!host_patterns_overlap("**.example.com", "example.com").unwrap()); + } + + #[test] + fn selector_pattern_overlap_honors_concrete_exclusions() { + let include = vec!["*.example.com".to_string()]; + let exclude = vec!["api.example.com".to_string()]; + + assert!(!selector_may_match_pattern(&include, &exclude, "api.example.com").unwrap()); + assert!(selector_may_match_pattern(&include, &exclude, "*.example.com").unwrap()); + } +} diff --git a/crates/openshell-core/src/lib.rs b/crates/openshell-core/src/lib.rs index bb61e1f56f..a57acb0065 100644 --- a/crates/openshell-core/src/lib.rs +++ b/crates/openshell-core/src/lib.rs @@ -20,10 +20,12 @@ pub mod forward; pub mod google_cloud; pub mod gpu; pub mod grpc_client; +pub mod host_pattern; pub mod image; pub mod inference; pub mod jwt; pub mod metadata; +pub mod middleware; pub mod net; pub mod paths; pub mod policy; diff --git a/crates/openshell-core/src/middleware.rs b/crates/openshell-core/src/middleware.rs new file mode 100644 index 0000000000..75ed66003b --- /dev/null +++ b/crates/openshell-core/src/middleware.rs @@ -0,0 +1,107 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Platform-wide supervisor middleware limits. + +use std::time::Duration; + +/// Default timeout for one supervisor middleware RPC. +pub const DEFAULT_MIDDLEWARE_TIMEOUT: Duration = Duration::from_millis(500); +/// Smallest operator-configured supervisor middleware RPC timeout. +pub const MIN_MIDDLEWARE_TIMEOUT: Duration = Duration::from_millis(10); +/// Largest operator-configured supervisor middleware RPC timeout. +pub const MAX_MIDDLEWARE_TIMEOUT: Duration = Duration::from_secs(30); + +/// Largest number of middleware configurations accepted in one sandbox policy. +pub const MAX_MIDDLEWARE_CONFIGS: usize = 10; +/// Largest number of middleware stages selected for one request. +pub const MAX_MIDDLEWARE_CHAIN_STAGES: usize = MAX_MIDDLEWARE_CONFIGS; +/// Largest combined number of include and exclude patterns in one selector. +pub const MAX_MIDDLEWARE_SELECTOR_PATTERNS: usize = 32; +/// Largest number of findings accepted from one middleware stage. +pub const MAX_MIDDLEWARE_FINDINGS_PER_STAGE: usize = 32; +/// Largest number of findings retained and emitted for one complete chain. +pub const MAX_MIDDLEWARE_CHAIN_FINDINGS: usize = + MAX_MIDDLEWARE_CHAIN_STAGES * MAX_MIDDLEWARE_FINDINGS_PER_STAGE; + +/// Parse the middleware timeout syntax shared by gateway configuration and +/// supervisor runtime registrations. +/// +/// Values use the same compact duration form as gateway interceptors: an +/// integer followed by `ms` or `s`. +pub fn parse_middleware_timeout(value: &str) -> Result { + let value = value.trim(); + if value.is_empty() { + return Err("timeout must not be empty".to_string()); + } + let timeout = if let Some(milliseconds) = value.strip_suffix("ms") { + let milliseconds = milliseconds + .parse::() + .map_err(|_| format!("invalid timeout '{value}'"))?; + Duration::from_millis(milliseconds) + } else if let Some(seconds) = value.strip_suffix('s') { + let seconds = seconds + .parse::() + .map_err(|_| format!("invalid timeout '{value}'"))?; + Duration::from_secs(seconds) + } else { + return Err(format!( + "invalid timeout '{value}'; expected suffix ms or s" + )); + }; + + if timeout < MIN_MIDDLEWARE_TIMEOUT || timeout > MAX_MIDDLEWARE_TIMEOUT { + return Err(format!("timeout '{value}' must be between 10ms and 30s")); + } + Ok(timeout) +} + +/// Resolve an optional wire/config timeout, using the platform default when +/// the value is empty. +pub fn middleware_timeout_or_default(value: &str) -> Result { + if value.trim().is_empty() { + Ok(DEFAULT_MIDDLEWARE_TIMEOUT) + } else { + parse_middleware_timeout(value) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn timeout_parser_matches_gateway_interceptor_duration_syntax() { + assert_eq!( + parse_middleware_timeout("500ms").unwrap(), + Duration::from_millis(500) + ); + assert_eq!( + parse_middleware_timeout("2s").unwrap(), + Duration::from_secs(2) + ); + assert!(parse_middleware_timeout("2").is_err()); + } + + #[test] + fn timeout_parser_enforces_inclusive_platform_bounds() { + assert_eq!( + parse_middleware_timeout("10ms").unwrap(), + MIN_MIDDLEWARE_TIMEOUT + ); + assert_eq!( + parse_middleware_timeout("30s").unwrap(), + MAX_MIDDLEWARE_TIMEOUT + ); + assert!(parse_middleware_timeout("9ms").is_err()); + assert!(parse_middleware_timeout("30001ms").is_err()); + } + + #[test] + fn empty_wire_timeout_uses_platform_default() { + assert_eq!( + middleware_timeout_or_default(""), + Ok(DEFAULT_MIDDLEWARE_TIMEOUT) + ); + } +} diff --git a/crates/openshell-core/src/proto/mod.rs b/crates/openshell-core/src/proto/mod.rs index 96424056fd..ebdbd380c1 100644 --- a/crates/openshell-core/src/proto/mod.rs +++ b/crates/openshell-core/src/proto/mod.rs @@ -87,6 +87,19 @@ pub mod inference { } } +#[allow( + clippy::all, + clippy::pedantic, + clippy::nursery, + unused_qualifications, + rust_2018_idioms +)] +pub mod middleware { + pub mod v1 { + include!(concat!(env!("OUT_DIR"), "/openshell.middleware.v1.rs")); + } +} + #[allow( clippy::all, clippy::pedantic, @@ -106,6 +119,7 @@ pub mod gateway_interceptor { pub use datamodel::v1::*; pub use gateway_interceptor::v1::*; pub use inference::v1::*; +pub use middleware::v1::*; pub use openshell::*; pub use sandbox::v1::*; pub use test::ObjectForTest; diff --git a/crates/openshell-core/src/proto_struct.rs b/crates/openshell-core/src/proto_struct.rs index 8871d6f6a7..ce95c65f0c 100644 --- a/crates/openshell-core/src/proto_struct.rs +++ b/crates/openshell-core/src/proto_struct.rs @@ -1,10 +1,74 @@ // SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -//! Helpers for decoding `google.protobuf.Struct` values. +//! Helpers for converting `google.protobuf.Struct` values to and from JSON. use serde::{Deserialize, Deserializer, de::Error as _}; +/// Errors converting JSON values into protobuf well-known types. +#[derive(Debug, thiserror::Error)] +pub enum ProtoStructError { + /// A JSON number cannot be represented exactly by protobuf's double value. + #[error("JSON number {0} cannot be represented exactly as a protobuf double")] + UnrepresentableNumber(serde_json::Number), +} + +/// Convert a JSON object into a protobuf Struct. +pub fn json_object_to_struct( + object: serde_json::Map, +) -> Result { + Ok(prost_types::Struct { + fields: object + .into_iter() + .map(|(key, value)| json_value_to_proto(value).map(|value| (key, value))) + .collect::>()?, + }) +} + +/// Convert a JSON value into a protobuf Value. +pub fn json_value_to_proto( + value: serde_json::Value, +) -> Result { + use prost_types::{ListValue, Value, value::Kind}; + + let kind = match value { + serde_json::Value::Null => Kind::NullValue(0), + serde_json::Value::Bool(value) => Kind::BoolValue(value), + serde_json::Value::Number(value) => Kind::NumberValue(number_to_f64_exact(&value)?), + serde_json::Value::String(value) => Kind::StringValue(value), + serde_json::Value::Array(values) => Kind::ListValue(ListValue { + values: values + .into_iter() + .map(json_value_to_proto) + .collect::>()?, + }), + serde_json::Value::Object(object) => Kind::StructValue(json_object_to_struct(object)?), + }; + + Ok(Value { kind: Some(kind) }) +} + +fn number_to_f64_exact(value: &serde_json::Number) -> Result { + let number = value + .as_f64() + .ok_or_else(|| ProtoStructError::UnrepresentableNumber(value.clone()))?; + + let exact = value.as_i64().map_or_else( + || value.as_u64().is_none_or(integer_is_exact_in_f64), + |integer| integer_is_exact_in_f64(integer.unsigned_abs()), + ); + + exact + .then_some(number) + .ok_or_else(|| ProtoStructError::UnrepresentableNumber(value.clone())) +} + +fn integer_is_exact_in_f64(integer: u64) -> bool { + integer == 0 + || (u64::BITS - integer.leading_zeros()).saturating_sub(integer.trailing_zeros()) + <= f64::MANTISSA_DIGITS +} + /// Convert a protobuf Struct into a JSON object for typed serde decoding. #[must_use] pub fn struct_to_json_object( @@ -72,6 +136,47 @@ where mod tests { use super::*; + #[test] + fn json_and_proto_values_round_trip() { + let json = serde_json::json!({ + "null": null, + "bool": true, + "number": 42.5, + "string": "value", + "list": [1.0, {"nested": "value"}], + }); + let serde_json::Value::Object(object) = json.clone() else { + unreachable!(); + }; + + let proto = json_object_to_struct(object).unwrap(); + + assert_eq!(struct_to_json_value(&proto), json); + } + + #[test] + fn rejects_integer_that_cannot_round_trip_through_protobuf_double() { + let value = serde_json::json!(9_007_199_254_740_993_u64); + + let err = json_value_to_proto(value).expect_err("lossy integer must be rejected"); + + assert!(err.to_string().contains("9007199254740993")); + assert!(err.to_string().contains("exactly")); + } + + #[test] + fn accepts_integer_that_round_trips_through_protobuf_double() { + let value = serde_json::json!(9_007_199_254_740_992_u64); + + let proto = json_value_to_proto(value.clone()).expect("integer should be exact"); + + assert_eq!( + value_to_json(&proto).as_f64(), + value.as_f64(), + "protobuf Struct stores all numbers as doubles" + ); + } + #[derive(Debug, Default, Deserialize)] #[serde(default)] struct TestConfig { diff --git a/crates/openshell-driver-docker/src/tests.rs b/crates/openshell-driver-docker/src/tests.rs index 594308bce5..7ca3405251 100644 --- a/crates/openshell-driver-docker/src/tests.rs +++ b/crates/openshell-driver-docker/src/tests.rs @@ -118,40 +118,11 @@ fn runtime_config() -> DockerDriverRuntimeConfig { } fn json_struct(value: serde_json::Value) -> prost_types::Struct { - match json_value(value).kind { - Some(prost_types::value::Kind::StructValue(value)) => value, - _ => panic!("expected JSON object"), - } -} - -fn json_value(value: serde_json::Value) -> prost_types::Value { - match value { - serde_json::Value::Null => prost_types::Value { kind: None }, - serde_json::Value::Bool(value) => prost_types::Value { - kind: Some(prost_types::value::Kind::BoolValue(value)), - }, - serde_json::Value::Number(value) => prost_types::Value { - kind: value.as_f64().map(prost_types::value::Kind::NumberValue), - }, - serde_json::Value::String(value) => prost_types::Value { - kind: Some(prost_types::value::Kind::StringValue(value)), - }, - serde_json::Value::Array(values) => prost_types::Value { - kind: Some(prost_types::value::Kind::ListValue( - prost_types::ListValue { - values: values.into_iter().map(json_value).collect(), - }, - )), - }, - serde_json::Value::Object(values) => prost_types::Value { - kind: Some(prost_types::value::Kind::StructValue(prost_types::Struct { - fields: values - .into_iter() - .map(|(key, value)| (key, json_value(value))) - .collect(), - })), - }, - } + let serde_json::Value::Object(object) = value else { + panic!("expected JSON object"); + }; + openshell_core::proto_struct::json_object_to_struct(object) + .expect("test JSON must convert to a protobuf Struct") } fn inspected_volume(driver: &str, options: HashMap) -> bollard::models::Volume { diff --git a/crates/openshell-driver-kubernetes/src/driver.rs b/crates/openshell-driver-kubernetes/src/driver.rs index 5315d30409..063bdfd45d 100644 --- a/crates/openshell-driver-kubernetes/src/driver.rs +++ b/crates/openshell-driver-kubernetes/src/driver.rs @@ -3010,38 +3010,11 @@ mod tests { std::sync::LazyLock::new(|| std::sync::Mutex::new(())); fn json_struct(value: serde_json::Value) -> Struct { - match json_value(value).kind { - Some(Kind::StructValue(value)) => value, - _ => panic!("expected JSON object"), - } - } - - fn json_value(value: serde_json::Value) -> Value { - match value { - serde_json::Value::Null => Value { kind: None }, - serde_json::Value::Bool(value) => Value { - kind: Some(Kind::BoolValue(value)), - }, - serde_json::Value::Number(value) => Value { - kind: value.as_f64().map(Kind::NumberValue), - }, - serde_json::Value::String(value) => Value { - kind: Some(Kind::StringValue(value)), - }, - serde_json::Value::Array(values) => Value { - kind: Some(Kind::ListValue(prost_types::ListValue { - values: values.into_iter().map(json_value).collect(), - })), - }, - serde_json::Value::Object(values) => Value { - kind: Some(Kind::StructValue(Struct { - fields: values - .into_iter() - .map(|(key, value)| (key, json_value(value))) - .collect(), - })), - }, - } + let serde_json::Value::Object(object) = value else { + panic!("expected JSON object"); + }; + openshell_core::proto_struct::json_object_to_struct(object) + .expect("test JSON must convert to a protobuf Struct") } fn sandbox_to_k8s_spec_for_test( diff --git a/crates/openshell-driver-podman/src/container.rs b/crates/openshell-driver-podman/src/container.rs index e4a0b79189..9ee26c0735 100644 --- a/crates/openshell-driver-podman/src/container.rs +++ b/crates/openshell-driver-podman/src/container.rs @@ -1155,40 +1155,11 @@ mod tests { std::sync::LazyLock::new(|| std::sync::Mutex::new(())); fn json_struct(value: Value) -> prost_types::Struct { - match json_value(value).kind { - Some(prost_types::value::Kind::StructValue(value)) => value, - _ => panic!("expected JSON object"), - } - } - - fn json_value(value: Value) -> prost_types::Value { - match value { - Value::Null => prost_types::Value { kind: None }, - Value::Bool(value) => prost_types::Value { - kind: Some(prost_types::value::Kind::BoolValue(value)), - }, - Value::Number(value) => prost_types::Value { - kind: value.as_f64().map(prost_types::value::Kind::NumberValue), - }, - Value::String(value) => prost_types::Value { - kind: Some(prost_types::value::Kind::StringValue(value)), - }, - Value::Array(values) => prost_types::Value { - kind: Some(prost_types::value::Kind::ListValue( - prost_types::ListValue { - values: values.into_iter().map(json_value).collect(), - }, - )), - }, - Value::Object(values) => prost_types::Value { - kind: Some(prost_types::value::Kind::StructValue(prost_types::Struct { - fields: values - .into_iter() - .map(|(key, value)| (key, json_value(value))) - .collect(), - })), - }, - } + let Value::Object(object) = value else { + panic!("expected JSON object"); + }; + proto_struct::json_object_to_struct(object) + .expect("test JSON must convert to a protobuf Struct") } fn gpu_resources(count: Option) -> ResourceRequirements { diff --git a/crates/openshell-driver-podman/src/driver.rs b/crates/openshell-driver-podman/src/driver.rs index cf639fa265..a86d58dee0 100644 --- a/crates/openshell-driver-podman/src/driver.rs +++ b/crates/openshell-driver-podman/src/driver.rs @@ -1256,41 +1256,12 @@ mod tests { PodmanComputeDriver::for_tests(config) } - fn json_value(value: serde_json::Value) -> prost_types::Value { - match value { - serde_json::Value::Null => prost_types::Value { kind: None }, - serde_json::Value::Bool(value) => prost_types::Value { - kind: Some(prost_types::value::Kind::BoolValue(value)), - }, - serde_json::Value::Number(value) => prost_types::Value { - kind: value.as_f64().map(prost_types::value::Kind::NumberValue), - }, - serde_json::Value::String(value) => prost_types::Value { - kind: Some(prost_types::value::Kind::StringValue(value)), - }, - serde_json::Value::Array(values) => prost_types::Value { - kind: Some(prost_types::value::Kind::ListValue( - prost_types::ListValue { - values: values.into_iter().map(json_value).collect(), - }, - )), - }, - serde_json::Value::Object(values) => prost_types::Value { - kind: Some(prost_types::value::Kind::StructValue(prost_types::Struct { - fields: values - .into_iter() - .map(|(key, value)| (key, json_value(value))) - .collect(), - })), - }, - } - } - fn json_struct(value: serde_json::Value) -> prost_types::Struct { - match json_value(value).kind { - Some(prost_types::value::Kind::StructValue(value)) => value, - _ => panic!("expected JSON object"), - } + let serde_json::Value::Object(object) = value else { + panic!("expected JSON object"); + }; + openshell_core::proto_struct::json_object_to_struct(object) + .expect("test JSON must convert to a protobuf Struct") } fn sandbox_with_volume_mount(volume: &str) -> DriverSandbox { diff --git a/crates/openshell-ocsf/src/builders/finding.rs b/crates/openshell-ocsf/src/builders/finding.rs index 177c9159df..fecb1e9275 100644 --- a/crates/openshell-ocsf/src/builders/finding.rs +++ b/crates/openshell-ocsf/src/builders/finding.rs @@ -25,6 +25,7 @@ pub struct DetectionFindingBuilder<'a> { risk_level: Option, message: Option, log_source: Option, + unmapped: serde_json::Map, } impl<'a> DetectionFindingBuilder<'a> { @@ -45,6 +46,7 @@ impl<'a> DetectionFindingBuilder<'a> { risk_level: None, message: None, log_source: None, + unmapped: serde_json::Map::new(), } } @@ -74,6 +76,13 @@ impl<'a> DetectionFindingBuilder<'a> { self } + /// Add a source-specific attribute that is not defined by the OCSF class. + #[must_use] + pub fn unmapped(mut self, key: &str, value: impl Into) -> Self { + self.unmapped.insert(key.to_string(), value.into()); + self + } + /// Add a remediation description. #[must_use] pub fn remediation(mut self, desc: &str) -> Self { @@ -122,6 +131,9 @@ impl<'a> DetectionFindingBuilder<'a> { self.severity, metadata, ); + if !self.unmapped.is_empty() { + base.unmapped = Some(serde_json::Value::Object(self.unmapped)); + } self.ctx.apply_common_fields(&mut base, None, self.message); OcsfEvent::DetectionFinding(DetectionFindingEvent { @@ -169,6 +181,7 @@ mod tests { .is_alert(true) .confidence(ConfidenceId::High) .risk_level(RiskLevelId::High) + .unmapped("source_rule", "nonce_replay") .finding_info( FindingInfo::new("nssh1-replay-abc", "NSSH1 Nonce Replay Attack") .with_desc("A nonce was replayed."), @@ -188,5 +201,6 @@ mod tests { assert_eq!(json["finding_info"]["title"], "NSSH1 Nonce Replay Attack"); assert_eq!(json["is_alert"], true); assert_eq!(json["confidence"], "High"); + assert_eq!(json["unmapped"]["source_rule"], "nonce_replay"); } } diff --git a/crates/openshell-ocsf/src/builders/http.rs b/crates/openshell-ocsf/src/builders/http.rs index 4fa33eb1ca..ae91cf7c41 100644 --- a/crates/openshell-ocsf/src/builders/http.rs +++ b/crates/openshell-ocsf/src/builders/http.rs @@ -25,6 +25,7 @@ pub struct HttpActivityBuilder<'a> { firewall_rule: Option, message: Option, status_detail: Option, + unmapped: serde_json::Map, } impl<'a> HttpActivityBuilder<'a> { @@ -45,6 +46,7 @@ impl<'a> HttpActivityBuilder<'a> { firewall_rule: None, message: None, status_detail: None, + unmapped: serde_json::Map::new(), } } @@ -69,6 +71,13 @@ impl<'a> HttpActivityBuilder<'a> { self } + /// Add a source-specific attribute that is not defined by the OCSF class. + #[must_use] + pub fn unmapped(mut self, key: &str, value: impl Into) -> Self { + self.unmapped.insert(key.to_string(), value.into()); + self + } + #[must_use] pub fn build(self) -> OcsfEvent { let activity_name = self.activity.http_label().to_string(); @@ -86,6 +95,9 @@ impl<'a> HttpActivityBuilder<'a> { if let Some(detail) = self.status_detail { base.set_status_detail(detail); } + if !self.unmapped.is_empty() { + base.unmapped = Some(serde_json::Value::Object(self.unmapped)); + } self.ctx .apply_common_fields(&mut base, self.status, self.message); @@ -157,11 +169,15 @@ mod tests { .firewall_rule("aws_iam", "ssrf") .message("FORWARD blocked: allowed_ips check failed") .status_detail("resolves to always-blocked address") + .unmapped("attempt", 2) + .unmapped("cached", true) .build(); let json = event.to_json().unwrap(); assert_eq!(json["class_uid"], 4002); assert_eq!(json["status_detail"], "resolves to always-blocked address"); + assert_eq!(json["unmapped"]["attempt"], 2); + assert_eq!(json["unmapped"]["cached"], true); assert_eq!(json["action_id"], 2); // Denied } } diff --git a/crates/openshell-ocsf/src/format/shorthand.rs b/crates/openshell-ocsf/src/format/shorthand.rs index 0cb5d906c3..60df77639f 100644 --- a/crates/openshell-ocsf/src/format/shorthand.rs +++ b/crates/openshell-ocsf/src/format/shorthand.rs @@ -82,22 +82,93 @@ fn truncate_with_ellipsis(text: &str, max: usize) -> String { format!("{}...", &text[..end]) } -/// Format a `[reason:...]` tag from `status_detail` (or `message` fallback) -/// for denied events. Returns an empty string if neither field is set. -fn reason_tag(base: &BaseEventData) -> String { - let text = base - .status_detail - .as_deref() - .or(base.message.as_deref()) - .unwrap_or(""); +fn escape_quoted_field(text: &str) -> String { + let mut escaped = String::with_capacity(text.len()); + for character in text.chars() { + match character { + '\\' => escaped.push_str("\\\\"), + '"' => escaped.push_str("\\\""), + '\n' => escaped.push_str("\\n"), + '\r' => escaped.push_str("\\r"), + '\t' => escaped.push_str("\\t"), + character if character.is_control() => { + use std::fmt::Write as _; + let _ = write!(escaped, "\\u{{{:x}}}", u32::from(character)); + } + character => escaped.push(character), + } + } + escaped +} + +fn escape_context_field(text: &str) -> String { + let mut escaped = String::with_capacity(text.len()); + for character in text.chars() { + match character { + '\\' => escaped.push_str("\\\\"), + '[' => escaped.push_str("\\["), + ']' => escaped.push_str("\\]"), + character if character.is_whitespace() || character.is_control() => { + use std::fmt::Write as _; + let _ = write!(escaped, "\\u{{{:x}}}", u32::from(character)); + } + character => escaped.push(character), + } + } + escaped +} + +fn reason_text(text: Option<&str>) -> Option { + let text = text?; if text.is_empty() { - return String::new(); + return None; } let text = text.replace(['\n', '\r'], " "); - format!( - " [reason:{}]", - truncate_with_ellipsis(&text, MAX_REASON_LEN) - ) + Some(truncate_with_ellipsis(&text, MAX_REASON_LEN)) +} + +/// Format a `[reason:...]` tag from `status_detail` (or `message` fallback) +/// for denied events. Returns an empty string if neither field is set. +fn reason_tag(base: &BaseEventData) -> String { + reason_text(base.status_detail.as_deref().or(base.message.as_deref())) + .map_or_else(String::new, |text| format!(" [reason:{text}]")) +} + +fn unmapped_fields(base: &BaseEventData) -> Vec { + base.unmapped + .as_ref() + .and_then(serde_json::Value::as_object) + .into_iter() + .flatten() + .filter_map(|(key, value)| { + let value = match value { + serde_json::Value::Bool(value) => value.to_string(), + serde_json::Value::Number(value) => value.to_string(), + serde_json::Value::String(value) => { + let value = truncate_with_ellipsis(value, MAX_REASON_LEN); + escape_context_field(&value) + } + _ => return None, + }; + Some(format!("{}:{value}", escape_context_field(key))) + }) + .collect() +} + +fn unmapped_context(base: &BaseEventData, include_reason: bool) -> String { + let mut fields = unmapped_fields(base); + + if include_reason + && let Some(reason) = reason_text(base.status_detail.as_deref().or(base.message.as_deref())) + { + fields.push(format!("reason:{reason}")); + } + + if fields.is_empty() { + String::new() + } else { + format!(" [{}]", fields.join(" ")) + } } fn message_tag(base: &BaseEventData) -> String { @@ -200,12 +271,7 @@ impl OcsfEvent { .as_ref() .map(|r| format!(" [policy:{} engine:{}]", r.name, r.rule_type)) .unwrap_or_default(); - // For denied events, surface the reason from status_detail - let reason_ctx = if action == "DENIED" { - reason_tag(&e.base) - } else { - String::new() - }; + let outcome_ctx = unmapped_context(&e.base, action == "DENIED"); let arrow = if actor_str.is_empty() { format!(" {method} {url_str}") } else { @@ -218,7 +284,7 @@ impl OcsfEvent { (false, true) => format!(" {action}"), (false, false) => format!(" {action}{arrow}"), }; - // Denied HTTP events surface their message through reason_ctx. + // Denied HTTP events surface their message through outcome_ctx. // Allowed MCP decisions also need the JSON-RPC message so the // selected tool name is visible in the shorthand log stream. let message_ctx = if action != "DENIED" @@ -230,7 +296,7 @@ impl OcsfEvent { } else { String::new() }; - format!("HTTP:{method} {sev}{detail}{rule_ctx}{reason_ctx}{message_ctx}") + format!("HTTP:{method} {sev}{detail}{rule_ctx}{outcome_ctx}{message_ctx}") } Self::SshActivity(e) => { @@ -292,16 +358,25 @@ impl OcsfEvent { } Self::DetectionFinding(e) => { - let disposition = e - .disposition - .map_or_else(|| "UNKNOWN".to_string(), |d| d.label().to_uppercase()); - let title = &e.finding_info.title; - let confidence_ctx = e - .confidence - .map(|c| format!(" [confidence:{}]", c.label().to_lowercase())) - .unwrap_or_default(); - - format!("FINDING:{disposition} {sev} \"{title}\"{confidence_ctx}") + let disposition = e.disposition.map_or_else( + || e.base.activity_name.to_uppercase(), + |d| d.label().to_uppercase(), + ); + let title = escape_quoted_field(&truncate_with_ellipsis( + &e.finding_info.title, + MAX_MESSAGE_LEN, + )); + let mut context = vec![format!( + "type:{}", + escape_context_field(&e.finding_info.uid) + )]; + context.extend(unmapped_fields(&e.base)); + if let Some(confidence) = e.confidence { + context.push(format!("confidence:{}", confidence.label().to_lowercase())); + } + let context = format!(" [{}]", context.join(" ")); + + format!("FINDING:{disposition} {sev} \"{title}\"{context}") } Self::ApplicationLifecycle(e) => { @@ -546,6 +621,36 @@ mod tests { ); } + #[test] + fn test_http_activity_shorthand_includes_unmapped_attributes() { + let mut base = base(4002, "HTTP Activity", 4, "Network Activity", 99, "Other"); + base.add_unmapped("attempt", serde_json::json!(2)); + base.add_unmapped("cached", serde_json::json!(true)); + let event = OcsfEvent::HttpActivity(HttpActivityEvent { + base, + http_request: Some(HttpRequest::new( + "POST", + Url::new("http", "httpbin.org", "/anything", 443), + )), + http_response: None, + src_endpoint: None, + dst_endpoint: None, + proxy_endpoint: None, + actor: None, + firewall_rule: Some(FirewallRule::new("httpbin", "extension")), + action: Some(ActionId::Allowed), + disposition: Some(DispositionId::Allowed), + observation_point_id: None, + is_src_dst_assignment_known: None, + }); + + let shorthand = event.format_shorthand(); + assert_eq!( + shorthand, + "HTTP:POST [INFO] ALLOWED POST http://httpbin.org:443/anything [policy:httpbin engine:extension] [attempt:2 cached:true]" + ); + } + #[test] fn test_http_activity_shorthand_mcp_shows_tool_for_allow_and_deny() { let mut event_base = base(4002, "HTTP Activity", 4, "Network Activity", 0, "Other"); @@ -931,10 +1036,70 @@ mod tests { let shorthand = event.format_shorthand(); assert_eq!( shorthand, - "FINDING:BLOCKED [HIGH] \"NSSH1 Nonce Replay Attack\" [confidence:high]" + "FINDING:BLOCKED [HIGH] \"NSSH1 Nonce Replay Attack\" [type:nssh1-replay-abc confidence:high]" ); } + #[test] + fn test_detection_finding_shorthand_uses_activity_and_safe_unmapped_attributes() { + let mut base = base(2004, "Detection Finding", 2, "Findings", 1, "Create"); + base.add_unmapped("count", serde_json::json!(1)); + base.add_unmapped("source", serde_json::json!("content_guard")); + let event = OcsfEvent::DetectionFinding(DetectionFindingEvent { + base, + finding_info: FindingInfo::new("content_guard.match", "configured content matched"), + evidences: Some(vec![Evidence::from_pairs(&[( + "matched_content", + "must-not-appear", + )])]), + attacks: None, + remediation: None, + is_alert: None, + confidence: None, + risk_level: None, + action: None, + disposition: None, + }); + + let shorthand = event.format_shorthand(); + assert_eq!( + shorthand, + "FINDING:CREATE [INFO] \"configured content matched\" [type:content_guard.match count:1 source:content_guard]" + ); + assert!(!shorthand.contains("must-not-appear")); + } + + #[test] + fn detection_finding_shorthand_escapes_control_characters_and_delimiters() { + let mut base = base(2004, "Detection Finding", 2, "Findings", 1, "Create"); + base.add_unmapped( + "source\nforged", + serde_json::json!("guard]\nFINDING:FORGED"), + ); + let event = OcsfEvent::DetectionFinding(DetectionFindingEvent { + base, + finding_info: FindingInfo::new( + "content_guard\nforged", + "matched \"value\"\nFINDING:FORGED", + ), + evidences: None, + attacks: None, + remediation: None, + is_alert: None, + confidence: None, + risk_level: None, + action: None, + disposition: None, + }); + + let shorthand = event.format_shorthand(); + + assert_eq!(shorthand.lines().count(), 1); + assert!(shorthand.contains("matched \\\"value\\\"\\nFINDING:FORGED")); + assert!(shorthand.contains("type:content_guard\\u{a}forged")); + assert!(shorthand.contains("source\\u{a}forged:guard\\]\\u{a}FINDING:FORGED")); + } + #[test] fn test_lifecycle_shorthand() { let mut b = base( diff --git a/crates/openshell-policy/Cargo.toml b/crates/openshell-policy/Cargo.toml index 16719de13d..b69da8d2b5 100644 --- a/crates/openshell-policy/Cargo.toml +++ b/crates/openshell-policy/Cargo.toml @@ -16,6 +16,7 @@ serde = { workspace = true } serde_json = { workspace = true } serde_yml = { workspace = true } miette = { workspace = true } +prost-types = { workspace = true } [lints] workspace = true diff --git a/crates/openshell-policy/src/lib.rs b/crates/openshell-policy/src/lib.rs index 8caf7de3ac..3c72b19b32 100644 --- a/crates/openshell-policy/src/lib.rs +++ b/crates/openshell-policy/src/lib.rs @@ -11,6 +11,7 @@ mod compose; mod merge; +mod middleware; use std::collections::{BTreeMap, HashMap}; use std::fmt; @@ -32,6 +33,9 @@ pub use merge::{ PolicyMergeError, PolicyMergeOp, PolicyMergeResult, PolicyMergeWarning, generated_rule_name, merge_policy, policy_covers_rule, }; +pub use middleware::middleware_host_matches; +pub use middleware::validate_json as validate_network_middleware_json; +pub use middleware::validate_json_with_config as validate_network_middleware_json_with_config; // --------------------------------------------------------------------------- // YAML serde types (canonical — used for both parsing and serialization) @@ -49,6 +53,8 @@ struct PolicyFile { process: Option, #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] network_policies: BTreeMap, + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + network_middlewares: BTreeMap, } #[derive(Debug, Serialize, Deserialize)] @@ -671,7 +677,11 @@ fn yaml_mcp_method( method.to_string() } -fn to_proto(raw: PolicyFile) -> SandboxPolicy { +fn to_proto(raw: PolicyFile) -> Result { + let network_middlewares = middleware::into_proto(raw.network_middlewares) + .into_diagnostic() + .wrap_err("failed to convert network middleware config")?; + let network_policies = raw .network_policies .into_iter() @@ -761,7 +771,7 @@ fn to_proto(raw: PolicyFile) -> SandboxPolicy { }) .collect(); - SandboxPolicy { + Ok(SandboxPolicy { version: raw.version, filesystem: raw.filesystem_policy.map(|fs| FilesystemPolicy { include_workdir: fs.include_workdir, @@ -776,7 +786,8 @@ fn to_proto(raw: PolicyFile) -> SandboxPolicy { run_as_group: p.run_as_group, }), network_policies, - } + network_middlewares, + }) } // --------------------------------------------------------------------------- @@ -908,12 +919,15 @@ fn from_proto(policy: &SandboxPolicy) -> PolicyFile { }) .collect(); + let network_middlewares = middleware::from_proto(&policy.network_middlewares); + PolicyFile { version: policy.version, filesystem_policy, landlock, process, network_policies, + network_middlewares, } } @@ -961,7 +975,7 @@ pub fn parse_sandbox_policy(yaml: &str) -> Result { let raw: PolicyFile = serde_yml::from_str(yaml) .into_diagnostic() .wrap_err("failed to parse sandbox policy YAML")?; - Ok(to_proto(raw)) + to_proto(raw) } /// Serialize a proto sandbox policy to a YAML string. @@ -1064,6 +1078,7 @@ pub fn restrictive_default_policy() -> SandboxPolicy { run_as_group: "sandbox".into(), }), network_policies: HashMap::new(), + network_middlewares: HashMap::default(), } } @@ -1121,6 +1136,24 @@ pub enum PolicyViolation { }, /// `credential_signing` and `request_body_credential_rewrite` are both set. CredentialSigningWithBodyRewrite { policy_name: String, host: String }, + /// A middleware configuration is structurally invalid. + InvalidMiddlewareConfig { name: String, reason: String }, + /// Too many middleware configurations are attached to one policy. + TooManyMiddlewareConfigs { count: usize }, + /// Two middleware configurations use the same execution order. + DuplicateMiddlewareOrder { + order: i32, + first_name: String, + second_name: String, + }, + /// Too many include and exclude patterns are attached to one middleware. + TooManyMiddlewareSelectorPatterns { name: String, count: usize }, + /// A middleware selector conflicts with an endpoint that skips TLS inspection. + MiddlewareTlsSkipConflict { + middleware_name: String, + policy_name: String, + host: String, + }, } impl fmt::Display for PolicyViolation { @@ -1193,6 +1226,44 @@ impl fmt::Display for PolicyViolation { and request_body_credential_rewrite set; these options are mutually exclusive" ) } + Self::InvalidMiddlewareConfig { name, reason } => { + write!(f, "middleware config '{name}' is invalid: {reason}") + } + Self::TooManyMiddlewareConfigs { count } => { + write!( + f, + "too many middleware configs ({count} > {})", + openshell_core::middleware::MAX_MIDDLEWARE_CONFIGS + ) + } + Self::DuplicateMiddlewareOrder { + order, + first_name, + second_name, + } => { + write!( + f, + "middleware configs '{first_name}' and '{second_name}' use duplicate order {order}" + ) + } + Self::TooManyMiddlewareSelectorPatterns { name, count } => { + write!( + f, + "middleware config '{name}' has too many selector patterns ({count} > {})", + openshell_core::middleware::MAX_MIDDLEWARE_SELECTOR_PATTERNS + ) + } + Self::MiddlewareTlsSkipConflict { + middleware_name, + policy_name, + host, + } => { + write!( + f, + "middleware config '{middleware_name}' selects network policy \ + '{policy_name}' tls: skip endpoint '{host}'" + ) + } } } } @@ -1211,6 +1282,9 @@ impl fmt::Display for PolicyViolation { /// - Individual path lengths must not exceed [`MAX_PATH_LENGTH`] /// - Total path count must not exceed [`MAX_FILESYSTEM_PATHS`] /// - Network endpoint hosts must not use TLD wildcards (e.g. `*.com`) +/// - Middleware names, implementations, failure modes, selectors, and built-in +/// configurations must be valid +/// - Middleware selectors must not match endpoints that skip TLS inspection pub fn validate_sandbox_policy( policy: &SandboxPolicy, ) -> std::result::Result<(), Vec> { @@ -1331,6 +1405,8 @@ pub fn validate_sandbox_policy( } } + violations.extend(middleware::validate(policy)); + if violations.is_empty() { Ok(()) } else { @@ -1473,6 +1549,69 @@ network_policies: assert_eq!(proto2.network_policies["my_api"].name, "my-custom-api-name"); } + #[test] + fn round_trip_preserves_network_middlewares() { + let yaml = r#" +version: 1 +network_middlewares: + global-redactor: + name: Global redactor + middleware: openshell/regex + order: 20 + on_error: fail_open + endpoints: + include: ["api.example.com", "*.service.test"] + exclude: ["internal.example.com"] + config: + mode: redact + secondary-redactor: + middleware: openshell/regex + endpoints: + include: ["api.example.com"] +network_policies: + api: + name: api + endpoints: + - host: api.example.com + port: 443 + protocol: rest + binaries: + - path: /usr/bin/curl +"#; + let proto = parse_sandbox_policy(yaml).expect("parse failed"); + assert_eq!(proto.network_middlewares.len(), 2); + let redactor = &proto.network_middlewares["global-redactor"]; + assert_eq!(redactor.name, "Global redactor"); + assert_eq!(redactor.middleware, "openshell/regex"); + assert_eq!(redactor.order, 20); + assert_eq!(redactor.on_error, "fail_open"); + assert_eq!( + redactor.endpoints.as_ref().expect("selector").include, + vec!["api.example.com", "*.service.test"] + ); + assert_eq!( + redactor.endpoints.as_ref().expect("selector").exclude, + vec!["internal.example.com"] + ); + assert_eq!( + redactor + .config + .as_ref() + .expect("config") + .fields + .get("mode") + .and_then(|value| value.kind.as_ref()), + Some(&prost_types::value::Kind::StringValue("redact".into())) + ); + assert_eq!( + proto.network_middlewares["secondary-redactor"].name, + "secondary-redactor" + ); + let yaml_out = serialize_sandbox_policy(&proto).expect("serialize failed"); + let reparsed = parse_sandbox_policy(&yaml_out).expect("re-parse failed"); + assert_eq!(reparsed.network_middlewares, proto.network_middlewares); + } + #[test] fn restrictive_default_has_no_network_policies() { let policy = restrictive_default_policy(); @@ -1603,6 +1742,31 @@ network_policies: assert!(parse_sandbox_policy(yaml).is_err()); } + #[test] + fn parse_rejects_middleware_attachments_on_network_policies_and_endpoints() { + let policy_attachment = r" +version: 1 +network_policies: + api: + middleware: [redact] + endpoints: + - host: api.example.com + port: 443 +"; + assert!(parse_sandbox_policy(policy_attachment).is_err()); + + let endpoint_attachment = r" +version: 1 +network_policies: + api: + endpoints: + - host: api.example.com + port: 443 + middleware: [redact] +"; + assert!(parse_sandbox_policy(endpoint_attachment).is_err()); + } + #[test] fn l7_config_stanza_runtime_fields_use_canonical_schema() { let fields = l7_config_alias_runtime_fields( @@ -1676,6 +1840,101 @@ network_policies: // ---- Policy validation tests ---- + fn middleware_config(implementation: &str) -> openshell_core::proto::NetworkMiddlewareConfig { + openshell_core::proto::NetworkMiddlewareConfig { + name: String::new(), + middleware: implementation.into(), + order: 0, + config: None, + on_error: String::new(), + endpoints: Some(openshell_core::proto::MiddlewareEndpointSelector { + include: vec!["api.example.com".into()], + exclude: Vec::new(), + }), + } + } + + fn add_middleware( + policy: &mut SandboxPolicy, + name: &str, + config: openshell_core::proto::NetworkMiddlewareConfig, + ) { + policy.network_middlewares.insert(name.into(), config); + } + + #[test] + fn structural_validation_defers_implementation_owned_config() { + let mut policy = restrictive_default_policy(); + let mut middleware = middleware_config("openshell/future"); + middleware.config = Some( + openshell_core::proto_struct::json_object_to_struct( + std::iter::once(("implementation_field".into(), serde_json::json!(42))).collect(), + ) + .unwrap(), + ); + policy + .network_middlewares + .insert("future".into(), middleware); + + validate_sandbox_policy(&policy) + .expect("generic policy validation must not select installed implementations"); + } + + #[test] + fn json_validation_delegates_implementation_owned_config() { + let data = serde_json::json!({ + "network_middlewares": { + "future": { + "middleware": "openshell/future", + "config": {"implementation_field": 42}, + "endpoints": {"include": ["api.example.com"]} + } + } + }); + + let violations = + validate_network_middleware_json_with_config(&data, |implementation, _config| { + Err(format!("{implementation} is not installed")) + }) + .expect("parse middleware policy"); + assert!(violations.iter().any(|violation| matches!( + violation, + PolicyViolation::InvalidMiddlewareConfig { name, reason } + if name == "future" && reason.contains("not installed") + ))); + } + + #[test] + fn json_validation_skips_config_callbacks_when_middleware_count_is_invalid() { + let configs: serde_json::Map = (0 + ..=openshell_core::middleware::MAX_MIDDLEWARE_CONFIGS) + .map(|index| { + ( + format!("middleware-{index}"), + serde_json::json!({ + "middleware": "openshell/regex", + "endpoints": {"include": ["api.example.com"]} + }), + ) + }) + .collect(); + let data = serde_json::json!({"network_middlewares": configs}); + let calls = std::cell::Cell::new(0usize); + + let violations = validate_network_middleware_json_with_config(&data, |_, _| { + calls.set(calls.get() + 1); + Ok(()) + }) + .expect("parse middleware policy"); + + assert_eq!(calls.get(), 0, "invalid policy must not invoke services"); + assert!(violations.iter().any(|violation| matches!( + violation, + PolicyViolation::TooManyMiddlewareConfigs { count } + if *count == openshell_core::middleware::MAX_MIDDLEWARE_CONFIGS + 1 + ))); + } + #[test] fn validate_rejects_root_run_as_user() { let mut policy = restrictive_default_policy(); @@ -1704,6 +1963,293 @@ network_policies: assert_eq!(violations.len(), 2); } + #[test] + fn validate_rejects_invalid_middleware_control_fields() { + let cases = [ + ( + "", + middleware_config("openshell/regex"), + "name must not be empty", + ), + ( + "redactor", + middleware_config(""), + "middleware must not be empty", + ), + ( + "redactor", + { + let mut middleware = middleware_config("openshell/regex"); + middleware.on_error = "maybe".into(); + middleware + }, + "invalid on_error", + ), + ( + "redactor", + { + let mut middleware = middleware_config("openshell/regex"); + middleware.endpoints = None; + middleware + }, + "endpoint selector is required", + ), + ( + "redactor", + { + let mut middleware = middleware_config("openshell/regex"); + middleware.endpoints.as_mut().unwrap().include.clear(); + middleware + }, + "must include at least one host pattern", + ), + ]; + + for (name, middleware, expected) in cases { + let mut policy = restrictive_default_policy(); + add_middleware(&mut policy, name, middleware); + let errors = validate_sandbox_policy(&policy) + .expect_err("invalid middleware must be rejected") + .into_iter() + .map(|violation| violation.to_string()) + .collect::>() + .join("; "); + assert!( + errors.contains(expected), + "expected {expected:?} in {errors:?}" + ); + } + } + + #[test] + fn validate_rejects_duplicate_middleware_orders() { + let mut policy = restrictive_default_policy(); + let mut alpha = middleware_config("openshell/regex"); + alpha.order = 10; + add_middleware(&mut policy, "alpha", alpha); + let mut beta = middleware_config("openshell/regex"); + beta.order = 10; + add_middleware(&mut policy, "beta", beta); + + let violations = validate_sandbox_policy(&policy).expect_err("duplicate order"); + assert!(violations.iter().any(|violation| matches!( + violation, + PolicyViolation::DuplicateMiddlewareOrder { + order: 10, + first_name, + second_name, + } if first_name == "alpha" && second_name == "beta" + ))); + } + + #[test] + fn validate_accepts_maximum_middleware_configs() { + let mut policy = restrictive_default_policy(); + for index in 0..openshell_core::middleware::MAX_MIDDLEWARE_CONFIGS { + let name = format!("middleware-{index}"); + let mut config = middleware_config("openshell/regex"); + config.order = i32::try_from(index).unwrap(); + add_middleware(&mut policy, &name, config); + } + + validate_sandbox_policy(&policy).expect("maximum middleware config count"); + } + + #[test] + fn validate_rejects_middleware_config_over_capacity() { + let mut policy = restrictive_default_policy(); + for index in 0..=openshell_core::middleware::MAX_MIDDLEWARE_CONFIGS { + let name = format!("middleware-{index}"); + let mut config = middleware_config("openshell/regex"); + config.order = i32::try_from(index).unwrap(); + add_middleware(&mut policy, &name, config); + } + + let violations = validate_sandbox_policy(&policy).expect_err("config count over capacity"); + assert!(violations.iter().any(|violation| matches!( + violation, + PolicyViolation::TooManyMiddlewareConfigs { count } + if *count == openshell_core::middleware::MAX_MIDDLEWARE_CONFIGS + 1 + ))); + } + + #[test] + fn validate_accepts_maximum_middleware_selector_patterns() { + let mut policy = restrictive_default_policy(); + let mut middleware = middleware_config("openshell/regex"); + let selector = middleware.endpoints.as_mut().expect("selector"); + selector.exclude = vec![ + "excluded.example.com".into(); + openshell_core::middleware::MAX_MIDDLEWARE_SELECTOR_PATTERNS - 1 + ]; + add_middleware(&mut policy, "redactor", middleware); + + validate_sandbox_policy(&policy).expect("maximum selector pattern count"); + } + + #[test] + fn validate_rejects_middleware_selector_patterns_over_capacity() { + let mut policy = restrictive_default_policy(); + let mut middleware = middleware_config("openshell/regex"); + let selector = middleware.endpoints.as_mut().expect("selector"); + selector.exclude = vec![ + "excluded.example.com".into(); + openshell_core::middleware::MAX_MIDDLEWARE_SELECTOR_PATTERNS + ]; + add_middleware(&mut policy, "redactor", middleware); + + let violations = + validate_sandbox_policy(&policy).expect_err("selector patterns over capacity"); + assert!(violations.iter().any(|violation| matches!( + violation, + PolicyViolation::TooManyMiddlewareSelectorPatterns { name, count } + if name == "redactor" + && *count + == openshell_core::middleware::MAX_MIDDLEWARE_SELECTOR_PATTERNS + 1 + ))); + } + + #[test] + fn validate_rejects_malformed_middleware_selector_patterns() { + let mut policy = restrictive_default_policy(); + let mut middleware = middleware_config("openshell/regex"); + middleware.endpoints.as_mut().unwrap().include = vec!["api[.example.com".into()]; + add_middleware(&mut policy, "redactor", middleware); + + let errors = validate_sandbox_policy(&policy) + .expect_err("malformed selector") + .into_iter() + .map(|violation| violation.to_string()) + .collect::>() + .join("; "); + assert!(errors.contains("invalid host pattern"), "{errors}"); + } + + #[test] + fn middleware_host_selector_matching_is_case_insensitive() { + assert!(middleware_host_matches("*.Example.COM", "API.example.com").unwrap()); + assert!(!middleware_host_matches("*.example.com", "example.com").unwrap()); + assert!(!middleware_host_matches("*.example.com", "deep.api.example.com").unwrap()); + assert!(middleware_host_matches("**.example.com", "deep.api.example.com").unwrap()); + assert!(!middleware_host_matches("**.example.com", "example.com").unwrap()); + } + + #[test] + fn validate_rejects_middleware_selector_matching_tls_skip_endpoint() { + let mut policy = restrictive_default_policy(); + add_middleware( + &mut policy, + "redactor", + middleware_config("openshell/regex"), + ); + policy.network_policies.insert( + "api".into(), + NetworkPolicyRule { + name: "api".into(), + endpoints: vec![NetworkEndpoint { + host: "api.example.com".into(), + port: 443, + tls: "skip".into(), + ..Default::default() + }], + binaries: Vec::new(), + }, + ); + + let violations = validate_sandbox_policy(&policy).expect_err("tls skip conflict"); + assert!(violations.iter().any(|violation| matches!( + violation, + PolicyViolation::MiddlewareTlsSkipConflict { + middleware_name, + policy_name, + host, + } if middleware_name == "redactor" && policy_name == "api" && host == "api.example.com" + ))); + } + + #[test] + fn validate_accepts_fail_open_middleware_selector_matching_tls_skip_endpoint() { + let mut policy = restrictive_default_policy(); + let mut middleware = middleware_config("openshell/regex"); + middleware.on_error = "fail_open".into(); + add_middleware(&mut policy, "redactor", middleware); + policy.network_policies.insert( + "api".into(), + NetworkPolicyRule { + name: "api".into(), + endpoints: vec![NetworkEndpoint { + host: "api.example.com".into(), + port: 443, + tls: "skip".into(), + ..Default::default() + }], + binaries: Vec::new(), + }, + ); + + validate_sandbox_policy(&policy) + .expect("fail-open middleware may select uninspectable tls: skip traffic"); + } + + #[test] + fn validate_rejects_explicit_fail_closed_middleware_on_tls_skip_endpoint() { + let mut policy = restrictive_default_policy(); + let mut middleware = middleware_config("openshell/regex"); + middleware.on_error = "fail_closed".into(); + add_middleware(&mut policy, "redactor", middleware); + policy.network_policies.insert( + "api".into(), + NetworkPolicyRule { + name: "api".into(), + endpoints: vec![NetworkEndpoint { + host: "api.example.com".into(), + port: 443, + tls: "skip".into(), + ..Default::default() + }], + binaries: Vec::new(), + }, + ); + + let violations = validate_sandbox_policy(&policy).expect_err("tls skip conflict"); + assert!(violations.iter().any(|violation| matches!( + violation, + PolicyViolation::MiddlewareTlsSkipConflict { middleware_name, .. } + if middleware_name == "redactor" + ))); + } + + #[test] + fn validate_rejects_concrete_selector_overlapping_tls_skip_wildcard() { + let mut policy = restrictive_default_policy(); + let mut middleware = middleware_config("openshell/regex"); + middleware.endpoints.as_mut().unwrap().include = vec!["api.example.com".into()]; + add_middleware(&mut policy, "redactor", middleware); + policy.network_policies.insert( + "api".into(), + NetworkPolicyRule { + name: "api".into(), + endpoints: vec![NetworkEndpoint { + host: "*.example.com".into(), + port: 443, + tls: "skip".into(), + ..Default::default() + }], + binaries: Vec::new(), + }, + ); + + let violations = validate_sandbox_policy(&policy).expect_err("tls skip conflict"); + assert!(violations.iter().any(|violation| matches!( + violation, + PolicyViolation::MiddlewareTlsSkipConflict { + middleware_name, + policy_name, + host, + } if middleware_name == "redactor" && policy_name == "api" && host == "*.example.com" + ))); + } + #[test] fn validate_rejects_non_sandbox_user() { let mut policy = restrictive_default_policy(); @@ -1788,6 +2334,7 @@ network_policies: filesystem: None, landlock: None, network_policies: HashMap::new(), + network_middlewares: HashMap::default(), }; assert!(validate_sandbox_policy(&policy).is_ok()); } @@ -2237,6 +2784,7 @@ network_policies: filesystem: None, landlock: None, network_policies: HashMap::new(), + network_middlewares: HashMap::default(), }; assert!(validate_sandbox_policy(&policy).is_ok()); } @@ -2252,6 +2800,7 @@ network_policies: filesystem: None, landlock: None, network_policies: HashMap::new(), + network_middlewares: HashMap::default(), }; assert!(validate_sandbox_policy(&policy).is_ok()); } @@ -2330,6 +2879,7 @@ network_policies: filesystem: None, landlock: None, network_policies: HashMap::new(), + network_middlewares: HashMap::default(), }; assert!(validate_sandbox_policy(&policy).is_ok()); } diff --git a/crates/openshell-policy/src/middleware.rs b/crates/openshell-policy/src/middleware.rs new file mode 100644 index 0000000000..9e323e6de0 --- /dev/null +++ b/crates/openshell-policy/src/middleware.rs @@ -0,0 +1,312 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! YAML schema and protobuf conversion for supervisor middleware policies. + +use std::collections::{BTreeMap, HashMap}; + +use openshell_core::middleware::{MAX_MIDDLEWARE_CONFIGS, MAX_MIDDLEWARE_SELECTOR_PATTERNS}; +use openshell_core::proto::{ + MiddlewareEndpointSelector, NetworkEndpoint, NetworkMiddlewareConfig, NetworkPolicyRule, + SandboxPolicy, +}; +use openshell_core::proto_struct::{ + ProtoStructError, json_object_to_struct, struct_to_json_object, +}; +use serde::{Deserialize, Serialize}; + +use super::PolicyViolation; + +pub use openshell_core::host_pattern::host_matches as middleware_host_matches; +use openshell_core::host_pattern::{HostPattern, HostSelector}; + +#[derive(Debug, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct NetworkMiddlewareConfigDef { + #[serde(default, skip_serializing_if = "String::is_empty")] + name: String, + middleware: String, + #[serde(default, skip_serializing_if = "is_default")] + order: i32, + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + config: BTreeMap, + #[serde(default, skip_serializing_if = "String::is_empty")] + on_error: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + endpoints: Option, +} + +fn is_default(value: &T) -> bool { + value == &T::default() +} + +#[derive(Debug, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct MiddlewareEndpointSelectorDef { + #[serde(default, skip_serializing_if = "Vec::is_empty")] + include: Vec, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + exclude: Vec, +} + +/// Middleware-relevant projection of the runtime policy JSON accepted by the +/// supervisor's local-file mode. Unrelated network and L7 fields are ignored; +/// middleware entries retain their strict canonical schema. +#[derive(Debug, Default, Deserialize)] +struct MiddlewareValidationPolicyDef { + #[serde(default)] + network_middlewares: BTreeMap, + #[serde(default)] + network_policies: BTreeMap, +} + +#[derive(Debug, Default, Deserialize)] +struct MiddlewareValidationNetworkPolicyDef { + #[serde(default)] + name: String, + #[serde(default)] + endpoints: Vec, +} + +#[derive(Debug, Default, Deserialize)] +struct MiddlewareValidationEndpointDef { + #[serde(default)] + host: String, + #[serde(default)] + tls: String, +} + +pub fn into_proto( + definitions: BTreeMap, +) -> Result, ProtoStructError> { + definitions + .into_iter() + .map(|(key, definition)| { + Ok(( + key.clone(), + NetworkMiddlewareConfig { + name: if definition.name.is_empty() { + key + } else { + definition.name + }, + middleware: definition.middleware, + order: definition.order, + config: Some(json_object_to_struct( + definition.config.into_iter().collect(), + )?), + on_error: definition.on_error, + endpoints: definition + .endpoints + .map(|selector| MiddlewareEndpointSelector { + include: selector.include, + exclude: selector.exclude, + }), + }, + )) + }) + .collect() +} + +pub fn from_proto( + middlewares: &HashMap, +) -> BTreeMap { + middlewares + .iter() + .map(|(name, middleware)| { + ( + name.clone(), + NetworkMiddlewareConfigDef { + name: middleware.name.clone(), + middleware: middleware.middleware.clone(), + order: middleware.order, + config: middleware + .config + .as_ref() + .map(struct_to_json_object) + .unwrap_or_default() + .into_iter() + .collect(), + on_error: middleware.on_error.clone(), + endpoints: middleware.endpoints.as_ref().map(|selector| { + MiddlewareEndpointSelectorDef { + include: selector.include.clone(), + exclude: selector.exclude.clone(), + } + }), + }, + ) + }) + .collect() +} + +/// Validate middleware configuration from the supervisor's runtime policy +/// JSON through the same typed validator used for protobuf policies. +pub fn validate_json(data: &serde_json::Value) -> Result, String> { + validate_json_with_config(data, |_implementation, _config| Ok(())) +} + +/// Validate middleware policy structure and delegate implementation-owned +/// configuration to the supplied registry or catalog. +pub fn validate_json_with_config( + data: &serde_json::Value, + validate_config: F, +) -> Result, String> +where + F: Fn(&str, &prost_types::Struct) -> Result<(), String>, +{ + let definition: MiddlewareValidationPolicyDef = serde_json::from_value(data.clone()) + .map_err(|error| format!("failed to parse network middleware policy: {error}"))?; + let network_middlewares = into_proto(definition.network_middlewares) + .map_err(|error| format!("failed to convert network middleware config: {error}"))?; + let network_policies = definition + .network_policies + .into_iter() + .map(|(key, rule)| { + let rule = NetworkPolicyRule { + name: rule.name, + endpoints: rule + .endpoints + .into_iter() + .map(|endpoint| NetworkEndpoint { + host: endpoint.host, + tls: endpoint.tls, + ..Default::default() + }) + .collect(), + ..Default::default() + }; + (key, rule) + }) + .collect(); + let policy = SandboxPolicy { + network_middlewares, + network_policies, + ..Default::default() + }; + let mut violations = validate(&policy); + if policy.network_middlewares.len() <= MAX_MIDDLEWARE_CONFIGS { + for (name, middleware) in &policy.network_middlewares { + let config = middleware.config.clone().unwrap_or_default(); + if let Err(reason) = validate_config(&middleware.middleware, &config) { + violations.push(PolicyViolation::InvalidMiddlewareConfig { + name: name.clone(), + reason, + }); + } + } + } + Ok(violations) +} + +pub fn validate(policy: &SandboxPolicy) -> Vec { + let mut violations = Vec::new(); + let mut orders = BTreeMap::new(); + if policy.network_middlewares.len() > MAX_MIDDLEWARE_CONFIGS { + violations.push(PolicyViolation::TooManyMiddlewareConfigs { + count: policy.network_middlewares.len(), + }); + } + + let mut middlewares: Vec<_> = policy.network_middlewares.iter().collect(); + middlewares.sort_by_key(|(name, _)| name.as_str()); + for (name, middleware) in middlewares { + if name.is_empty() { + violations.push(PolicyViolation::InvalidMiddlewareConfig { + name: name.clone(), + reason: "name must not be empty".to_string(), + }); + } + + if let Some(first_name) = orders.insert(middleware.order, name.clone()) { + violations.push(PolicyViolation::DuplicateMiddlewareOrder { + order: middleware.order, + first_name, + second_name: name.clone(), + }); + } + + if middleware.middleware.is_empty() { + violations.push(PolicyViolation::InvalidMiddlewareConfig { + name: name.clone(), + reason: "middleware must not be empty".to_string(), + }); + } + + if !matches!( + middleware.on_error.as_str(), + "" | "fail_closed" | "fail_open" + ) { + violations.push(PolicyViolation::InvalidMiddlewareConfig { + name: name.clone(), + reason: format!("invalid on_error '{}'", middleware.on_error), + }); + } + + let Some(selector) = &middleware.endpoints else { + violations.push(PolicyViolation::InvalidMiddlewareConfig { + name: name.clone(), + reason: "endpoint selector is required".to_string(), + }); + continue; + }; + if selector.include.is_empty() { + violations.push(PolicyViolation::InvalidMiddlewareConfig { + name: name.clone(), + reason: "endpoint selector must include at least one host pattern".to_string(), + }); + } + let selector_patterns = selector + .include + .len() + .saturating_add(selector.exclude.len()); + if selector_patterns > MAX_MIDDLEWARE_SELECTOR_PATTERNS { + violations.push(PolicyViolation::TooManyMiddlewareSelectorPatterns { + name: name.clone(), + count: selector_patterns, + }); + continue; + } + let mut selector_valid = !selector.include.is_empty(); + for pattern in selector.include.iter().chain(&selector.exclude) { + if let Err(reason) = HostPattern::new(pattern) { + selector_valid = false; + violations.push(PolicyViolation::InvalidMiddlewareConfig { + name: name.clone(), + reason: format!("endpoint selector pattern '{pattern}' is invalid: {reason}"), + }); + } + } + let compiled_selector = if selector_valid { + HostSelector::new(&selector.include, &selector.exclude).ok() + } else { + None + }; + + let requires_inspection = matches!(middleware.on_error.as_str(), "" | "fail_closed"); + for (key, rule) in &policy.network_policies { + let policy_name = if rule.name.is_empty() { + key + } else { + &rule.name + }; + for endpoint in &rule.endpoints { + let overlaps_tls_skip = requires_inspection + && endpoint.tls == "skip" + && compiled_selector.as_ref().is_some_and(|selector| { + HostPattern::new(&endpoint.host) + .is_ok_and(|endpoint| selector.may_match_pattern(&endpoint)) + }); + if overlaps_tls_skip { + violations.push(PolicyViolation::MiddlewareTlsSkipConflict { + middleware_name: name.clone(), + policy_name: policy_name.clone(), + host: endpoint.host.clone(), + }); + } + } + } + } + + violations +} diff --git a/crates/openshell-sandbox/Cargo.toml b/crates/openshell-sandbox/Cargo.toml index 0d7ff33925..f9c23cf60f 100644 --- a/crates/openshell-sandbox/Cargo.toml +++ b/crates/openshell-sandbox/Cargo.toml @@ -19,6 +19,8 @@ openshell-core = { path = "../openshell-core", default-features = false } openshell-ocsf = { path = "../openshell-ocsf" } openshell-policy = { path = "../openshell-policy" } openshell-supervisor-network = { path = "../openshell-supervisor-network" } +openshell-supervisor-middleware = { path = "../openshell-supervisor-middleware" } +openshell-supervisor-middleware-builtins = { path = "../openshell-supervisor-middleware-builtins" } openshell-supervisor-process = { path = "../openshell-supervisor-process" } # Async runtime @@ -26,6 +28,7 @@ tokio = { workspace = true } # gRPC (tonic::Status downcast in error mapping) tonic = { workspace = true, features = ["channel", "tls-native-roots"] } +prost-types = { workspace = true } # CLI clap = { workspace = true } diff --git a/crates/openshell-sandbox/src/lib.rs b/crates/openshell-sandbox/src/lib.rs index 7a1085f1bf..78e5027953 100644 --- a/crates/openshell-sandbox/src/lib.rs +++ b/crates/openshell-sandbox/src/lib.rs @@ -160,9 +160,17 @@ pub async fn run_sandbox( // Load policy and initialize OPA engine let openshell_endpoint_for_proxy = openshell_endpoint.clone(); let sandbox_name_for_agg = sandbox.clone(); - let (mut policy, opa_engine, retained_proto, loaded_policy_origin) = + let (mut policy, opa_engine, retained_proto, middleware_registry_status, loaded_policy_origin) = if let Some(bootstrap) = sidecar_bootstrap.as_ref() { - load_policy_from_sidecar_bootstrap(bootstrap)? + let (policy, opa_engine, retained_proto, loaded_policy_origin) = + load_policy_from_sidecar_bootstrap(bootstrap)?; + ( + policy, + opa_engine, + retained_proto, + MiddlewareRegistryStatus::Synchronized, + loaded_policy_origin, + ) } else { load_policy( sandbox_id.clone(), @@ -555,6 +563,7 @@ pub async fn run_sandbox( ocsf_enabled: poll_ocsf_enabled, provider_credentials: poll_provider_credentials, policy_local_ctx: poll_policy_local, + middleware_registry_status, sidecar_control_publisher: sidecar_control_publisher.clone(), }; @@ -1787,6 +1796,7 @@ async fn load_policy( SandboxPolicy, Option>, Option, + MiddlewareRegistryStatus, LoadedPolicyOrigin, )> { // File mode: load OPA engine from rego rules + YAML data (dev override) @@ -1801,10 +1811,22 @@ async fn load_policy( "Loading OPA policy engine from local files [rules:{policy_file} data:{data_file}]" )) .build()); - let engine = OpaEngine::from_files( + let validate_middleware_config = |implementation: &str, config: &prost_types::Struct| { + openshell_supervisor_middleware_builtins::validate_config(implementation, config) + .map_err(|error| error.to_string()) + }; + let engine = OpaEngine::from_files_with_middleware_config( std::path::Path::new(policy_file), std::path::Path::new(data_file), + Some(&validate_middleware_config), )?; + let middleware_registry = + openshell_supervisor_middleware::MiddlewareRegistry::connect_services( + openshell_supervisor_middleware_builtins::services(), + Vec::new(), + ) + .await?; + engine.replace_middleware_registry(middleware_registry)?; let config = engine.query_sandbox_config()?; let mut policy = SandboxPolicy { version: 1, @@ -1817,10 +1839,12 @@ async fn load_policy( process: config.process, }; enrich_sandbox_baseline_paths(&mut policy); + // File mode has no operator-registered middleware to connect. return Ok(( policy, Some(Arc::new(engine)), None, + MiddlewareRegistryStatus::Synchronized, LoadedPolicyOrigin::LocalOverride, )); } @@ -1934,8 +1958,8 @@ async fn load_policy( // container hasn't started yet. After the entrypoint spawns, the // engine is rebuilt with the real PID for symlink resolution. info!("Creating OPA engine from proto policy data"); - let opa_engine = match OpaEngine::from_proto(&proto_policy) { - Ok(engine) => Some(Arc::new(engine)), + let engine = match OpaEngine::from_proto(&proto_policy) { + Ok(engine) => engine, Err(e) => { report_initial_policy_failure(endpoint, id, loaded_policy_revision.as_ref(), &e) .await; @@ -1943,6 +1967,47 @@ async fn load_policy( } }; + // Install the in-process catalog before any external connection can + // fail. A newly started sandbox must always be able to resolve built-in + // bindings, even while operator-run services are unavailable. + install_builtin_middleware_registry(&engine).await?; + + // Connect operator-registered middleware services. A connect/describe + // failure keeps the built-in registry active so each request's + // `on_error` policy governs matched traffic. The policy poll loop + // retries the install without waiting for a config change. + let middleware_services = snapshot.supervisor_middleware_services.clone(); + let middleware_registry_status = if middleware_services.is_empty() { + MiddlewareRegistryStatus::Synchronized + } else if let Err(error) = grpc_retry("Middleware connect", || { + openshell_supervisor_middleware::MiddlewareRegistry::connect_services( + openshell_supervisor_middleware_builtins::services(), + middleware_services.clone(), + ) + }) + .await + .and_then(|registry| engine.replace_middleware_registry(registry)) + { + ocsf_emit!( + ConfigStateChangeBuilder::new(ocsf_ctx()) + .severity(SeverityId::Medium) + .status(StatusId::Failure) + .state(StateId::Other, "degraded") + .unmapped( + "supervisor_middleware_service_count", + serde_json::json!(middleware_services.len()) + ) + .message(format!( + "Supervisor middleware connect failed at startup; continuing with built-in middleware only, per-request on_error governs matched requests [error:{error}]" + )) + .build() + ); + MiddlewareRegistryStatus::NeedsReconciliation + } else { + MiddlewareRegistryStatus::Synchronized + }; + let opa_engine = Some(Arc::new(engine)); + let policy = match SandboxPolicy::try_from(proto_policy.clone()) { Ok(policy) => policy, Err(e) => { @@ -1955,6 +2020,7 @@ async fn load_policy( policy, opa_engine, Some(proto_policy), + middleware_registry_status, LoadedPolicyOrigin::Gateway { revision: loaded_policy_revision, }, @@ -2077,6 +2143,45 @@ fn discover_policy_from_path(path: &std::path::Path) -> openshell_core::proto::S } } +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum MiddlewareRegistryStatus { + Synchronized, + NeedsReconciliation, +} + +/// True when the installed middleware registry no longer matches the desired +/// service set and must be rebuilt (reconnecting every delivered service). +/// +/// A policy-only change never requires a rebuild: middleware configs were +/// validated at gateway admission and the installed registry's manifests +/// already cover the unchanged service set, so requiring the services to be +/// reachable would only let a middleware outage block the policy update. +fn middleware_registry_needs_rebuild( + registry_status: MiddlewareRegistryStatus, + current_services: &[openshell_core::proto::SupervisorMiddlewareService], + desired_services: &[openshell_core::proto::SupervisorMiddlewareService], +) -> bool { + registry_status == MiddlewareRegistryStatus::NeedsReconciliation + || current_services != desired_services +} + +fn gateway_policy_runtime_needs_reconciliation( + reloads_gateway_policy: bool, + current_policy_hash: &str, + desired_policy_hash: &str, + current_services: &[openshell_core::proto::SupervisorMiddlewareService], + desired_services: &[openshell_core::proto::SupervisorMiddlewareService], + registry_status: MiddlewareRegistryStatus, +) -> bool { + reloads_gateway_policy + && (current_policy_hash != desired_policy_hash + || middleware_registry_needs_rebuild( + registry_status, + current_services, + desired_services, + )) +} + /// Identity returned with the exact policy snapshot used to construct OPA. #[derive(Clone, Debug, PartialEq, Eq)] struct LoadedPolicyRevision { @@ -2363,9 +2468,85 @@ struct PolicyPollLoopContext { ocsf_enabled: Arc, provider_credentials: ProviderCredentialState, policy_local_ctx: Option>, + middleware_registry_status: MiddlewareRegistryStatus, sidecar_control_publisher: Option, } +async fn connect_middleware_registry( + services: &[openshell_core::proto::SupervisorMiddlewareService], +) -> Result { + openshell_supervisor_middleware::MiddlewareRegistry::connect_services( + openshell_supervisor_middleware_builtins::services(), + services.to_vec(), + ) + .await +} + +async fn install_builtin_middleware_registry(opa_engine: &OpaEngine) -> Result<()> { + let registry = openshell_supervisor_middleware::MiddlewareRegistry::connect_services( + openshell_supervisor_middleware_builtins::services(), + Vec::new(), + ) + .await?; + opa_engine.replace_middleware_registry(registry) +} + +async fn reconcile_middleware_registry( + opa_engine: &OpaEngine, + desired_services: &[openshell_core::proto::SupervisorMiddlewareService], + current_services: &mut Vec, + status: &mut MiddlewareRegistryStatus, +) { + if *status == MiddlewareRegistryStatus::Synchronized + && desired_services == current_services.as_slice() + { + return; + } + + match connect_middleware_registry(desired_services) + .await + .and_then(|registry| opa_engine.replace_middleware_registry(registry)) + { + Ok(()) => { + current_services.clear(); + current_services.extend_from_slice(desired_services); + *status = MiddlewareRegistryStatus::Synchronized; + ocsf_emit!( + ConfigStateChangeBuilder::new(ocsf_ctx()) + .severity(SeverityId::Informational) + .status(StatusId::Success) + .state(StateId::Enabled, "loaded") + .unmapped( + "supervisor_middleware_service_count", + serde_json::json!(current_services.len()) + ) + .message(format!( + "Supervisor middleware registry reloaded [service_count:{}]", + current_services.len() + )) + .build() + ); + } + Err(error) => { + // Emit only on the transition into the failed state to avoid + // repeating the same finding on every poll during an outage. + if *status == MiddlewareRegistryStatus::Synchronized { + ocsf_emit!( + ConfigStateChangeBuilder::new(ocsf_ctx()) + .severity(SeverityId::Medium) + .status(StatusId::Failure) + .state(StateId::Other, "failed") + .message(format!( + "Supervisor middleware registry reload failed, keeping last-known-good registry [error:{error}]" + )) + .build() + ); + } + *status = MiddlewareRegistryStatus::NeedsReconciliation; + } + } +} + async fn run_policy_poll_loop(ctx: PolicyPollLoopContext) -> Result<()> { use openshell_core::grpc_client::CachedOpenShellClient; use openshell_core::proto::PolicySource; @@ -2382,10 +2563,14 @@ async fn run_policy_poll_loop(ctx: PolicyPollLoopContext) -> Result<()> { let mut current_config_revision: u64 = 0; let mut current_provider_env_revision: u64 = ctx.provider_credentials.snapshot().revision; let mut current_policy_hash = String::new(); + let mut current_middleware_services = Vec::new(); + let mut middleware_registry_status = ctx.middleware_registry_status; let mut current_settings: std::collections::HashMap< String, openshell_core::proto::EffectiveSetting, > = std::collections::HashMap::new(); + let reloads_gateway_policy = ctx.loaded_policy_origin.allows_gateway_policy_reload(); + let mut last_failed_runtime_revision: Option<(u64, String)> = None; // A first poll that does not match the policy already loaded into OPA must // pass through the normal reconciliation path immediately. It must never @@ -2401,6 +2586,7 @@ async fn run_policy_poll_loop(ctx: PolicyPollLoopContext) -> Result<()> { apply_ocsf_json_setting(&ctx.ocsf_enabled, &result.settings); current_config_revision = candidate.config_revision; current_policy_hash.clone_from(&candidate.policy_hash); + current_middleware_services = result.supervisor_middleware_services; current_settings = result.settings; enqueue_policy_status( &status_sender, @@ -2416,6 +2602,7 @@ async fn run_policy_poll_loop(ctx: PolicyPollLoopContext) -> Result<()> { apply_ocsf_json_setting(&ctx.ocsf_enabled, &result.settings); current_config_revision = result.config_revision; current_policy_hash = result.policy_hash.clone(); + current_middleware_services = result.supervisor_middleware_services; current_settings = result.settings; debug!( config_revision = current_config_revision, @@ -2443,29 +2630,59 @@ async fn run_policy_poll_loop(ctx: PolicyPollLoopContext) -> Result<()> { } }; + let config_changed = result.config_revision != current_config_revision; let provider_env_changed = result.provider_env_revision != current_provider_env_revision; - if result.config_revision == current_config_revision && !provider_env_changed { - continue; + let policy_changed = result.policy_hash != current_policy_hash; + let middleware_registry_changed = middleware_registry_needs_rebuild( + middleware_registry_status, + ¤t_middleware_services, + &result.supervisor_middleware_services, + ); + let policy_runtime_changed = gateway_policy_runtime_needs_reconciliation( + reloads_gateway_policy, + ¤t_policy_hash, + &result.policy_hash, + ¤t_middleware_services, + &result.supervisor_middleware_services, + middleware_registry_status, + ); + + // A local policy override is not coupled to the gateway policy + // snapshot, so its service registry can still be reconciled alone. + // Gateway policy snapshots, however, must install policy and registry + // as one generation below. + if !reloads_gateway_policy { + reconcile_middleware_registry( + &ctx.opa_engine, + &result.supervisor_middleware_services, + &mut current_middleware_services, + &mut middleware_registry_status, + ) + .await; } - let policy_changed = result.policy_hash != current_policy_hash; + if !config_changed && !provider_env_changed && !policy_runtime_changed { + continue; + } - // Log which settings changed. - log_setting_changes(¤t_settings, &result.settings); + if config_changed || provider_env_changed { + // Log which settings changed. + log_setting_changes(¤t_settings, &result.settings); - ocsf_emit!(ConfigStateChangeBuilder::new(ocsf_ctx()) - .severity(SeverityId::Informational) - .status(StatusId::Success) - .state(StateId::Other, "detected") - .unmapped("old_config_revision", serde_json::json!(current_config_revision)) - .unmapped("new_config_revision", serde_json::json!(result.config_revision)) - .unmapped("policy_changed", serde_json::json!(policy_changed)) - .unmapped("provider_env_changed", serde_json::json!(provider_env_changed)) - .message(format!( - "Settings poll: config change detected [old_revision:{current_config_revision} new_revision:{} policy_changed:{policy_changed} provider_env_changed:{provider_env_changed}]", - result.config_revision - )) - .build()); + ocsf_emit!(ConfigStateChangeBuilder::new(ocsf_ctx()) + .severity(SeverityId::Informational) + .status(StatusId::Success) + .state(StateId::Other, "detected") + .unmapped("old_config_revision", serde_json::json!(current_config_revision)) + .unmapped("new_config_revision", serde_json::json!(result.config_revision)) + .unmapped("policy_changed", serde_json::json!(policy_changed)) + .unmapped("provider_env_changed", serde_json::json!(provider_env_changed)) + .message(format!( + "Settings poll: config change detected [old_revision:{current_config_revision} new_revision:{} policy_changed:{policy_changed} provider_env_changed:{provider_env_changed}]", + result.config_revision + )) + .build()); + } if provider_env_changed { match openshell_core::grpc_client::fetch_provider_environment( @@ -2516,86 +2733,131 @@ async fn run_policy_poll_loop(ctx: PolicyPollLoopContext) -> Result<()> { } } - // Only reload OPA when the policy payload actually changed. - if policy_changed && ctx.loaded_policy_origin.allows_gateway_policy_reload() { - let Some(policy) = result.policy.as_ref() else { - ocsf_emit!(ConfigStateChangeBuilder::new(ocsf_ctx()) - .severity(SeverityId::Medium) - .status(StatusId::Failure) - .state(StateId::Other, "skipped") - .message("Settings poll: policy hash changed but no policy payload present; skipping reload") - .build()); - current_config_revision = result.config_revision; - current_policy_hash = result.policy_hash; - current_settings = result.settings; - continue; + if policy_runtime_changed { + let pid = ctx.entrypoint_pid.load(Ordering::Acquire); + let runtime_result = match result.policy.as_ref() { + Some(policy) if middleware_registry_changed => { + match connect_middleware_registry(&result.supervisor_middleware_services).await + { + Ok(registry) => ctx + .opa_engine + .reload_policy_and_middleware_from_proto_with_pid( + policy, pid, registry, + ), + Err(error) => Err(error), + } + } + // Policy-only change: the installed registry already matches + // the delivered service set, so swap the engine alone. This + // must not require middleware reachability. + Some(policy) => ctx.opa_engine.reload_from_proto_with_pid(policy, pid), + None => Err(miette::miette!( + "runtime reload requires a policy payload but none was returned" + )), }; - let pid = ctx.entrypoint_pid.load(Ordering::Acquire); - match ctx.opa_engine.reload_from_proto_with_pid(policy, pid) { + match runtime_result { Ok(()) => { - if let Some(policy_local_ctx) = ctx.policy_local_ctx.as_ref() { - policy_local_ctx.set_current_policy(policy.clone()).await; - } - if let Some(publisher) = ctx.sidecar_control_publisher.as_ref() { - publisher.publish_policy( - policy.clone(), - result.policy_hash.clone(), - result.config_revision, - ); + let policy = result + .policy + .as_ref() + .expect("successful runtime reload requires a policy payload"); + if policy_changed { + if let Some(policy_local_ctx) = ctx.policy_local_ctx.as_ref() { + policy_local_ctx.set_current_policy(policy.clone()).await; + } + if let Some(publisher) = ctx.sidecar_control_publisher.as_ref() { + publisher.publish_policy( + policy.clone(), + result.policy_hash.clone(), + result.config_revision, + ); + } + if result.global_policy_version > 0 { + ocsf_emit!(ConfigStateChangeBuilder::new(ocsf_ctx()) + .severity(SeverityId::Informational) + .status(StatusId::Success) + .state(StateId::Enabled, "loaded") + .unmapped("policy_hash", serde_json::json!(&result.policy_hash)) + .unmapped("global_version", serde_json::json!(result.global_policy_version)) + .message(format!( + "Policy reloaded successfully (global) [policy_hash:{} global_version:{}]", + result.policy_hash, + result.global_policy_version + )) + .build()); + } else { + ocsf_emit!( + ConfigStateChangeBuilder::new(ocsf_ctx()) + .severity(SeverityId::Informational) + .status(StatusId::Success) + .state(StateId::Enabled, "loaded") + .unmapped("policy_hash", serde_json::json!(&result.policy_hash)) + .message(format!( + "Policy reloaded successfully [policy_hash:{}]", + result.policy_hash + )) + .build() + ); + } + if result.version > 0 && result.policy_source == PolicySource::Sandbox { + enqueue_policy_status( + &status_sender, + PolicyStatusUpdate::loaded(result.version), + ); + } } - if result.global_policy_version > 0 { + + if middleware_registry_changed { ocsf_emit!(ConfigStateChangeBuilder::new(ocsf_ctx()) .severity(SeverityId::Informational) .status(StatusId::Success) .state(StateId::Enabled, "loaded") - .unmapped("policy_hash", serde_json::json!(&result.policy_hash)) - .unmapped("global_version", serde_json::json!(result.global_policy_version)) + .unmapped( + "supervisor_middleware_service_count", + serde_json::json!(result.supervisor_middleware_services.len()) + ) .message(format!( - "Policy reloaded successfully (global) [policy_hash:{} global_version:{}]", - result.policy_hash, - result.global_policy_version + "Supervisor policy runtime reloaded atomically [service_count:{}]", + result.supervisor_middleware_services.len() )) .build()); - } else { - ocsf_emit!( - ConfigStateChangeBuilder::new(ocsf_ctx()) - .severity(SeverityId::Informational) - .status(StatusId::Success) - .state(StateId::Enabled, "loaded") - .unmapped("policy_hash", serde_json::json!(&result.policy_hash)) - .message(format!( - "Policy reloaded successfully [policy_hash:{}]", - result.policy_hash - )) - .build() - ); - } - if result.version > 0 && result.policy_source == PolicySource::Sandbox { - enqueue_policy_status( - &status_sender, - PolicyStatusUpdate::loaded(result.version), - ); } + + current_policy_hash.clone_from(&result.policy_hash); + current_middleware_services.clone_from(&result.supervisor_middleware_services); + middleware_registry_status = MiddlewareRegistryStatus::Synchronized; + last_failed_runtime_revision = None; } Err(e) => { - ocsf_emit!(ConfigStateChangeBuilder::new(ocsf_ctx()) - .severity(SeverityId::Medium) - .status(StatusId::Failure) - .state(StateId::Other, "failed") - .unmapped("version", serde_json::json!(result.version)) - .unmapped("error", serde_json::json!(e.to_string())) - .message(format!( - "Policy reload failed, keeping last-known-good policy [version:{} error:{e}]", - result.version - )) - .build()); - if result.version > 0 && result.policy_source == PolicySource::Sandbox { - enqueue_policy_status( - &status_sender, - PolicyStatusUpdate::failed(result.version, e.to_string()), - ); + let failed_revision = (result.config_revision, result.policy_hash.clone()); + if last_failed_runtime_revision.as_ref() != Some(&failed_revision) { + ocsf_emit!(ConfigStateChangeBuilder::new(ocsf_ctx()) + .severity(SeverityId::Medium) + .status(StatusId::Failure) + .state(StateId::Other, "failed") + .unmapped("version", serde_json::json!(result.version)) + .unmapped("error", serde_json::json!(e.to_string())) + .message(format!( + "Policy and middleware runtime reload failed, keeping last-known-good runtime [version:{} error:{e}]", + result.version + )) + .build()); + if policy_changed + && result.version > 0 + && result.policy_source == PolicySource::Sandbox + { + enqueue_policy_status( + &status_sender, + PolicyStatusUpdate::failed(result.version, e.to_string()), + ); + } } + last_failed_runtime_revision = Some(failed_revision); + // Nothing was installed, so the registry status still + // describes the live registry. The retry is driven by the + // persisting hash/service-set mismatch (or an existing + // NeedsReconciliation), not by degrading the status here. } } } @@ -2638,7 +2900,9 @@ async fn run_policy_poll_loop(ctx: PolicyPollLoopContext) -> Result<()> { } current_config_revision = result.config_revision; - current_policy_hash = result.policy_hash; + if !reloads_gateway_policy { + current_policy_hash = result.policy_hash; + } current_settings = result.settings; } } @@ -3008,9 +3272,137 @@ filesystem_policy: settings: std::collections::HashMap::new(), global_policy_version: 0, provider_env_revision: 0, + supervisor_middleware_services: Vec::new(), } } + #[tokio::test] + async fn failed_external_startup_registry_build_preserves_installed_builtins() { + let engine = OpaEngine::from_proto(&proto_policy_fixture()).expect("build OPA engine"); + install_builtin_middleware_registry(&engine) + .await + .expect("install built-in middleware registry"); + let builtins_generation = engine.current_generation(); + assert_eq!(builtins_generation, 1); + + let invalid_external = openshell_core::proto::SupervisorMiddlewareService { + name: "unavailable-guard".into(), + grpc_endpoint: "http://127.0.0.1:1".into(), + max_body_bytes: 1024, + ..Default::default() + }; + connect_middleware_registry(&[invalid_external]) + .await + .expect_err("unavailable external service must not replace built-ins"); + + assert_eq!(engine.current_generation(), builtins_generation); + } + + #[test] + fn failed_gateway_runtime_snapshot_is_retried_without_revision_change() { + let services = Vec::new(); + + assert!(gateway_policy_runtime_needs_reconciliation( + true, + "hash-v1", + "hash-v1", + &services, + &services, + MiddlewareRegistryStatus::NeedsReconciliation, + )); + assert!(!gateway_policy_runtime_needs_reconciliation( + true, + "hash-v1", + "hash-v1", + &services, + &services, + MiddlewareRegistryStatus::Synchronized, + )); + } + + #[test] + fn gateway_runtime_reconciliation_tracks_policy_and_service_changes() { + let no_services = Vec::new(); + let desired_services = vec![openshell_core::proto::SupervisorMiddlewareService { + name: "guard".into(), + ..Default::default() + }]; + + assert!(gateway_policy_runtime_needs_reconciliation( + true, + "hash-v1", + "hash-v2", + &no_services, + &no_services, + MiddlewareRegistryStatus::Synchronized, + )); + assert!(gateway_policy_runtime_needs_reconciliation( + true, + "hash-v1", + "hash-v1", + &no_services, + &desired_services, + MiddlewareRegistryStatus::Synchronized, + )); + assert!(!gateway_policy_runtime_needs_reconciliation( + false, + "local-policy", + "hash-v2", + &no_services, + &desired_services, + MiddlewareRegistryStatus::NeedsReconciliation, + )); + } + + #[test] + fn policy_only_change_does_not_rebuild_middleware_registry() { + let services = vec![openshell_core::proto::SupervisorMiddlewareService { + name: "guard".into(), + ..Default::default() + }]; + + // The runtime must reconcile, but the registry (and therefore + // middleware reachability) is not part of that reconciliation. + assert!(gateway_policy_runtime_needs_reconciliation( + true, + "hash-v1", + "hash-v2", + &services, + &services, + MiddlewareRegistryStatus::Synchronized, + )); + assert!(!middleware_registry_needs_rebuild( + MiddlewareRegistryStatus::Synchronized, + &services, + &services, + )); + } + + #[test] + fn registry_rebuild_requires_service_set_change_or_degraded_registry() { + let no_services = Vec::new(); + let desired_services = vec![openshell_core::proto::SupervisorMiddlewareService { + name: "guard".into(), + ..Default::default() + }]; + + assert!(middleware_registry_needs_rebuild( + MiddlewareRegistryStatus::Synchronized, + &no_services, + &desired_services, + )); + assert!(middleware_registry_needs_rebuild( + MiddlewareRegistryStatus::NeedsReconciliation, + &desired_services, + &desired_services, + )); + assert!(!middleware_registry_needs_rebuild( + MiddlewareRegistryStatus::Synchronized, + &desired_services, + &desired_services, + )); + } + #[test] fn initial_ack_candidate_matches_sandbox_revision() { let canonical = settings_poll_result( diff --git a/crates/openshell-sandbox/src/sidecar_control.rs b/crates/openshell-sandbox/src/sidecar_control.rs index 03cfeff886..c98dbc33bf 100644 --- a/crates/openshell-sandbox/src/sidecar_control.rs +++ b/crates/openshell-sandbox/src/sidecar_control.rs @@ -49,7 +49,7 @@ pub enum ControlUpdate { provider_child_env: HashMap, }, PolicyUpdated { - policy_proto: openshell_core::proto::SandboxPolicy, + policy_proto: Box, policy_hash: String, config_revision: u64, }, @@ -231,7 +231,7 @@ impl TryFrom for ControlUpdate { .into_diagnostic() .wrap_err("failed to decode sidecar policy update")?; Ok(Self::PolicyUpdated { - policy_proto, + policy_proto: Box::new(policy_proto), policy_hash, config_revision, }) diff --git a/crates/openshell-sdk/tests/client_mock.rs b/crates/openshell-sdk/tests/client_mock.rs index 544c5a9b29..f9244b3c82 100644 --- a/crates/openshell-sdk/tests/client_mock.rs +++ b/crates/openshell-sdk/tests/client_mock.rs @@ -54,8 +54,8 @@ fn sandbox_with_phase(name: &str, phase: proto::SandboxPhase) -> proto::Sandbox name: name.to_string(), created_at_ms: 0, labels: HashMap::new(), - resource_version: 1, annotations: HashMap::new(), + resource_version: 1, }), spec: None, status: Some(proto::SandboxStatus { diff --git a/crates/openshell-server/Cargo.toml b/crates/openshell-server/Cargo.toml index ca106a335f..4c4f289ed6 100644 --- a/crates/openshell-server/Cargo.toml +++ b/crates/openshell-server/Cargo.toml @@ -27,6 +27,8 @@ openshell-prover = { path = "../openshell-prover" } openshell-providers = { path = "../openshell-providers" } openshell-router = { path = "../openshell-router" } openshell-server-macros = { path = "../openshell-server-macros" } +openshell-supervisor-middleware = { path = "../openshell-supervisor-middleware" } +openshell-supervisor-middleware-builtins = { path = "../openshell-supervisor-middleware-builtins" } # Kubernetes client (used by the `generate-certs` subcommand) kube = { workspace = true } diff --git a/crates/openshell-server/src/config_file.rs b/crates/openshell-server/src/config_file.rs index 37fe6d94e6..c4e0cbc959 100644 --- a/crates/openshell-server/src/config_file.rs +++ b/crates/openshell-server/src/config_file.rs @@ -25,6 +25,7 @@ use std::net::SocketAddr; use std::path::{Path, PathBuf}; use openshell_core::config::ComputeDriverKind; +use openshell_core::proto::SupervisorMiddlewareService; use openshell_core::{ GatewayAuthConfig, GatewayInterceptorConfig, GatewayJwtConfig, GatewayProviderProfileSourceConfig, MtlsAuthConfig, OidcConfig, TlsConfig, @@ -58,6 +59,9 @@ pub struct OpenShellRoot { #[serde(default)] pub gateway: GatewayFileSection, + #[serde(default)] + pub supervisor: SupervisorFileSection, + /// `[openshell.drivers.]` tables — passed verbatim to each driver /// crate's `Deserialize` impl after the gateway-side inheritance merge. /// Stored as raw [`toml::Value`] so each driver can evolve its schema @@ -167,6 +171,42 @@ pub struct GatewayFileSection { pub database_url: Option, } +/// `[openshell.supervisor]` section. +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct SupervisorFileSection { + /// Statically registered supervisor middleware services. Registration is + /// operator-owned and changes require a gateway restart. + #[serde(default)] + pub middleware: Vec, +} + +/// One `[[openshell.supervisor.middleware]]` supervisor middleware registration. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct MiddlewareServiceFileConfig { + /// Operator-facing name used for diagnostics. + pub name: String, + /// Plaintext gRPC endpoint reachable by the gateway and supervisors. + pub grpc_endpoint: String, + /// Operator-owned body limit for every binding exposed by this service. + pub max_body_bytes: u64, + /// Default RPC timeout using an integer with an `ms` or `s` suffix. + #[serde(default)] + pub timeout: Option, +} + +impl From<&MiddlewareServiceFileConfig> for SupervisorMiddlewareService { + fn from(config: &MiddlewareServiceFileConfig) -> Self { + Self { + name: config.name.clone(), + grpc_endpoint: config.grpc_endpoint.clone(), + max_body_bytes: config.max_body_bytes, + timeout: config.timeout.clone().unwrap_or_default(), + } + } +} + #[derive(Debug, thiserror::Error)] pub enum ConfigFileError { #[error("failed to read gateway config file '{}': {source}", path.display())] @@ -408,6 +448,31 @@ allow_unauthenticated_users = true assert!(auth.allow_unauthenticated_users); } + #[test] + fn parses_supervisor_middleware_registration() { + let toml = r#" +[[openshell.supervisor.middleware]] +name = "local-guard" +grpc_endpoint = "http://127.0.0.1:50051" +max_body_bytes = 262144 +timeout = "2s" +"#; + let tmp = write_tmp(toml); + let file = load(tmp.path()).expect("valid middleware registration parses"); + assert_eq!( + file.openshell.supervisor.middleware, + vec![MiddlewareServiceFileConfig { + name: "local-guard".into(), + grpc_endpoint: "http://127.0.0.1:50051".into(), + max_body_bytes: 262_144, + timeout: Some("2s".into()), + }] + ); + let registration = + SupervisorMiddlewareService::from(&file.openshell.supervisor.middleware[0]); + assert_eq!(registration.timeout, "2s"); + } + #[test] fn parses_provider_profile_source_composition() { let toml = r#" diff --git a/crates/openshell-server/src/grpc/policy.rs b/crates/openshell-server/src/grpc/policy.rs index 9a612f5e19..59774bbcc8 100644 --- a/crates/openshell-server/src/grpc/policy.rs +++ b/crates/openshell-server/src/grpc/policy.rs @@ -1337,13 +1337,37 @@ pub(super) async fn handle_get_sandbox_config( .await?; if !provider_layers.is_empty() { let effective_policy = compose_effective_policy(source_policy, &provider_layers); + validate_policy_safety(&effective_policy).map_err(|error| { + Status::failed_precondition(format!( + "provider composition produced an invalid effective policy: {}", + error.message() + )) + })?; policy_hash = deterministic_policy_hash(&effective_policy); policy = Some(effective_policy); } } + if let Some(policy) = policy.as_ref() { + state + .middleware_registry + .ensure_policy_middlewares_registered(policy) + .map_err(|error| { + Status::failed_precondition(format!( + "effective policy middleware registration is invalid: {error}" + )) + })?; + } + let settings = merge_effective_settings(&global_settings, &sandbox_settings)?; - let config_revision = compute_config_revision(policy.as_ref(), &settings, policy_source); + let supervisor_middleware_services = + state.middleware_registry.required_services(policy.as_ref()); + let config_revision = compute_config_revision( + policy.as_ref(), + &settings, + policy_source, + &supervisor_middleware_services, + ); let provider_env_revision = compute_provider_env_revision_with_catalog( state.store.as_ref(), &provider_profile_catalog, @@ -1360,6 +1384,7 @@ pub(super) async fn handle_get_sandbox_config( policy_source: policy_source.into(), global_policy_version, provider_env_revision, + supervisor_middleware_services, })) } @@ -1641,6 +1666,8 @@ async fn handle_update_config_inner( openshell_policy::ensure_sandbox_process_identity(&mut new_policy); validate_no_reserved_provider_policy_keys(&new_policy)?; validate_policy_safety(&new_policy)?; + crate::middleware::validate_policy(state.middleware_registry.as_ref(), &new_policy) + .await?; let payload = new_policy.encode_to_vec(); let hash = deterministic_policy_hash(&new_policy); @@ -2004,11 +2031,14 @@ async fn handle_update_config_inner( let backfill_policy = if let Some(baseline_policy) = spec.policy.as_ref() { validate_static_fields_unchanged(baseline_policy, &new_policy)?; - validate_policy_safety(&new_policy)?; None } else { Some(new_policy.clone()) }; + + validate_policy_safety(&new_policy)?; + crate::middleware::validate_policy(state.middleware_registry.as_ref(), &new_policy).await?; + let _sandbox_sync_guard = if backfill_policy.is_some() { Some(state.compute.sandbox_sync_guard().await) } else { @@ -3342,6 +3372,21 @@ fn deterministic_policy_hash(policy: &ProtoSandboxPolicy) -> String { hasher.update(key.as_bytes()); hasher.update(value.encode_to_vec()); } + if !policy.network_middlewares.is_empty() { + hasher.update(b"network_middlewares"); + let mut entries: Vec<_> = policy.network_middlewares.iter().collect(); + entries.sort_by_key(|(name, _)| name.as_str()); + for (name, middleware) in entries { + hasher.update(name.as_bytes()); + let encoded = middleware.encode_to_vec(); + hasher.update( + u64::try_from(encoded.len()) + .expect("protobuf payload length fits in u64") + .to_le_bytes(), + ); + hasher.update(encoded); + } + } hex::encode(hasher.finalize()) } @@ -3350,6 +3395,7 @@ fn compute_config_revision( policy: Option<&ProtoSandboxPolicy>, settings: &HashMap, policy_source: PolicySource, + supervisor_middleware_services: &[openshell_core::proto::SupervisorMiddlewareService], ) -> u64 { let mut hasher = Sha256::new(); hasher.update((policy_source as i32).to_le_bytes()); @@ -3382,6 +3428,11 @@ fn compute_config_revision( } } } + let mut middleware = supervisor_middleware_services.iter().collect::>(); + middleware.sort_by(|left, right| left.name.cmp(&right.name)); + for service in middleware { + hasher.update(service.encode_to_vec()); + } let digest = hasher.finalize(); let mut bytes = [0_u8; 8]; @@ -5247,6 +5298,85 @@ mod tests { ); } + #[tokio::test] + async fn sandbox_config_rejects_invalid_provider_composed_policy() { + use openshell_core::proto::{ + MiddlewareEndpointSelector, NetworkMiddlewareConfig, ProviderProfile, + ProviderProfileCategory, StoredProviderProfile, + }; + + let state = test_server_state().await; + enable_providers_v2(&state).await; + + let profile = StoredProviderProfile { + metadata: Some(openshell_core::proto::datamodel::v1::ObjectMeta { + id: "profile-tls-skip".to_string(), + name: "tls-skip".to_string(), + created_at_ms: 1_000_000, + labels: HashMap::new(), + annotations: HashMap::new(), + resource_version: 0, + }), + profile: Some(ProviderProfile { + id: "tls-skip".to_string(), + display_name: "TLS skip".to_string(), + category: ProviderProfileCategory::Other as i32, + endpoints: vec![NetworkEndpoint { + host: "api.example.com".to_string(), + port: 443, + tls: "skip".to_string(), + ..Default::default() + }], + ..Default::default() + }), + }; + state.store.put_message(&profile).await.unwrap(); + state + .store + .put_message(&test_provider("work-tls-skip", "tls-skip")) + .await + .unwrap(); + + let policy = ProtoSandboxPolicy { + network_middlewares: HashMap::from([( + "redactor".to_string(), + NetworkMiddlewareConfig { + middleware: "openshell/regex".to_string(), + on_error: "fail_closed".to_string(), + endpoints: Some(MiddlewareEndpointSelector { + include: vec!["api.example.com".to_string()], + exclude: Vec::new(), + }), + ..Default::default() + }, + )]), + ..Default::default() + }; + state + .store + .put_message(&test_sandbox( + "sb-invalid-composed-policy", + "invalid-composed-policy", + policy, + vec!["work-tls-skip".to_string()], + )) + .await + .unwrap(); + + let error = handle_get_sandbox_config( + &state, + with_user(Request::new(GetSandboxConfigRequest { + sandbox_id: "sb-invalid-composed-policy".to_string(), + })), + ) + .await + .expect_err("invalid composed policy must not be delivered"); + + assert_eq!(error.code(), Code::FailedPrecondition); + assert!(error.message().contains("provider composition")); + assert!(error.message().contains("tls: skip")); + } + #[tokio::test] async fn sandbox_config_skips_profileless_provider_types_when_v2_enabled() { let state = test_server_state().await; @@ -9568,7 +9698,7 @@ mod tests { allowed_ips: vec!["127.0.0.1".to_string()], ..Default::default() }], - binaries: vec![], + ..Default::default() }; let result = validate_rule_not_always_blocked(&rule); assert!(result.is_err()); @@ -9589,7 +9719,7 @@ mod tests { allowed_ips: vec!["169.254.169.254".to_string()], ..Default::default() }], - binaries: vec![], + ..Default::default() }; let result = validate_rule_not_always_blocked(&rule); assert!(result.is_err()); @@ -9607,7 +9737,7 @@ mod tests { port: 80, ..Default::default() }], - binaries: vec![], + ..Default::default() }; let result = validate_rule_not_always_blocked(&rule); assert!(result.is_err()); @@ -9625,7 +9755,7 @@ mod tests { port: 8080, ..Default::default() }], - binaries: vec![], + ..Default::default() }; let result = validate_rule_not_always_blocked(&rule); assert!(result.is_err()); @@ -9643,7 +9773,7 @@ mod tests { port: 80, ..Default::default() }], - binaries: vec![], + ..Default::default() }; let result = validate_rule_not_always_blocked(&rule); assert!(result.is_err()); @@ -9691,7 +9821,7 @@ mod tests { allowed_ips: vec!["10.0.5.0/24".to_string()], ..Default::default() }], - binaries: vec![], + ..Default::default() }; let result = validate_rule_not_always_blocked(&rule); assert!(result.is_ok()); @@ -9708,7 +9838,7 @@ mod tests { port: 443, ..Default::default() }], - binaries: vec![], + ..Default::default() }; let result = validate_rule_not_always_blocked(&rule); assert!(result.is_ok()); @@ -9784,7 +9914,7 @@ mod tests { }, ); - let rev_a = compute_config_revision(Some(&policy), &settings, PolicySource::Sandbox); + let rev_a = compute_config_revision(Some(&policy), &settings, PolicySource::Sandbox, &[]); settings.insert( "mode".to_string(), EffectiveSetting { @@ -9794,7 +9924,7 @@ mod tests { scope: SettingScope::Sandbox.into(), }, ); - let rev_b = compute_config_revision(Some(&policy), &settings, PolicySource::Sandbox); + let rev_b = compute_config_revision(Some(&policy), &settings, PolicySource::Sandbox, &[]); assert_ne!(rev_a, rev_b); } @@ -10059,8 +10189,8 @@ mod tests { }, ); - let rev_a = compute_config_revision(Some(&policy), &settings, PolicySource::Sandbox); - let rev_b = compute_config_revision(Some(&policy), &settings, PolicySource::Sandbox); + let rev_a = compute_config_revision(Some(&policy), &settings, PolicySource::Sandbox, &[]); + let rev_b = compute_config_revision(Some(&policy), &settings, PolicySource::Sandbox, &[]); assert_eq!(rev_a, rev_b); } @@ -10076,21 +10206,117 @@ mod tests { }; let settings = HashMap::new(); - let rev_a = compute_config_revision(Some(&policy_a), &settings, PolicySource::Sandbox); - let rev_b = compute_config_revision(Some(&policy_b), &settings, PolicySource::Sandbox); + let rev_a = compute_config_revision(Some(&policy_a), &settings, PolicySource::Sandbox, &[]); + let rev_b = compute_config_revision(Some(&policy_b), &settings, PolicySource::Sandbox, &[]); assert_ne!(rev_a, rev_b); } + #[test] + fn policy_hash_changes_when_network_middlewares_change() { + let policy_a = ProtoSandboxPolicy::default(); + let policy_b = ProtoSandboxPolicy { + network_middlewares: HashMap::from([( + "regex-redactor".into(), + openshell_core::proto::NetworkMiddlewareConfig { + middleware: "openshell/regex".into(), + on_error: "fail_closed".into(), + ..Default::default() + }, + )]), + ..Default::default() + }; + + assert_ne!( + deterministic_policy_hash(&policy_a), + deterministic_policy_hash(&policy_b), + "middleware-only policy changes must produce a new policy hash" + ); + } + + #[test] + fn policy_hash_is_stable_across_middleware_config_field_insertion_order() { + use prost_types::{Struct, Value, value::Kind}; + use std::collections::BTreeMap; + + fn string_value(value: &str) -> Value { + Value { + kind: Some(Kind::StringValue(value.into())), + } + } + + fn middleware_config(reverse: bool) -> Struct { + let mut nested = BTreeMap::new(); + let mut fields = BTreeMap::new(); + if reverse { + nested.insert("second".into(), string_value("two")); + nested.insert("first".into(), string_value("one")); + fields.insert( + "nested".into(), + Value { + kind: Some(Kind::StructValue(Struct { fields: nested })), + }, + ); + fields.insert("mode".into(), string_value("redact")); + } else { + nested.insert("first".into(), string_value("one")); + nested.insert("second".into(), string_value("two")); + fields.insert("mode".into(), string_value("redact")); + fields.insert( + "nested".into(), + Value { + kind: Some(Kind::StructValue(Struct { fields: nested })), + }, + ); + } + Struct { fields } + } + + let policy = |reverse| ProtoSandboxPolicy { + network_middlewares: HashMap::from([( + "regex-redactor".into(), + openshell_core::proto::NetworkMiddlewareConfig { + middleware: "openshell/regex".into(), + config: Some(middleware_config(reverse)), + ..Default::default() + }, + )]), + ..Default::default() + }; + + assert_eq!( + deterministic_policy_hash(&policy(false)), + deterministic_policy_hash(&policy(true)), + "equivalent middleware configs must hash identically regardless of field insertion order" + ); + } + #[test] fn config_revision_changes_when_policy_source_changes() { let policy = ProtoSandboxPolicy::default(); let settings = HashMap::new(); - let rev_a = compute_config_revision(Some(&policy), &settings, PolicySource::Sandbox); - let rev_b = compute_config_revision(Some(&policy), &settings, PolicySource::Global); + let rev_a = compute_config_revision(Some(&policy), &settings, PolicySource::Sandbox, &[]); + let rev_b = compute_config_revision(Some(&policy), &settings, PolicySource::Global, &[]); assert_ne!(rev_a, rev_b); } + #[test] + fn config_revision_changes_when_supervisor_middleware_services_change() { + let policy = ProtoSandboxPolicy::default(); + let settings = HashMap::new(); + let service = openshell_core::proto::SupervisorMiddlewareService { + name: "local-guard".into(), + grpc_endpoint: "http://127.0.0.1:50051".into(), + max_body_bytes: 1024, + ..Default::default() + }; + + let without = compute_config_revision(Some(&policy), &settings, PolicySource::Sandbox, &[]); + let with = + compute_config_revision(Some(&policy), &settings, PolicySource::Sandbox, &[service]); + assert_ne!(without, with); + } + #[test] fn config_revision_without_policy_still_hashes_settings() { let mut settings = HashMap::new(); @@ -10104,7 +10330,7 @@ mod tests { }, ); - let rev_a = compute_config_revision(None, &settings, PolicySource::Sandbox); + let rev_a = compute_config_revision(None, &settings, PolicySource::Sandbox, &[]); settings.insert( "log_level".to_string(), @@ -10116,7 +10342,7 @@ mod tests { }, ); - let rev_b = compute_config_revision(None, &settings, PolicySource::Sandbox); + let rev_b = compute_config_revision(None, &settings, PolicySource::Sandbox, &[]); assert_ne!(rev_a, rev_b); } diff --git a/crates/openshell-server/src/grpc/sandbox.rs b/crates/openshell-server/src/grpc/sandbox.rs index 8e2f6d25c5..ad03741481 100644 --- a/crates/openshell-server/src/grpc/sandbox.rs +++ b/crates/openshell-server/src/grpc/sandbox.rs @@ -165,6 +165,7 @@ async fn handle_create_sandbox_inner( openshell_policy::ensure_sandbox_process_identity(policy); validate_no_reserved_provider_policy_keys(policy)?; validate_policy_safety(policy)?; + crate::middleware::validate_policy(state.middleware_registry.as_ref(), policy).await?; } let id = uuid::Uuid::new_v4().to_string(); diff --git a/crates/openshell-server/src/grpc/validation.rs b/crates/openshell-server/src/grpc/validation.rs index 8f4242af17..9e47a01524 100644 --- a/crates/openshell-server/src/grpc/validation.rs +++ b/crates/openshell-server/src/grpc/validation.rs @@ -1655,6 +1655,30 @@ mod tests { assert!(err.message().contains("TLD wildcard")); } + #[test] + fn validate_policy_safety_rejects_invalid_middleware_before_acceptance() { + use openshell_core::proto::{MiddlewareEndpointSelector, NetworkMiddlewareConfig}; + + let mut policy = openshell_policy::restrictive_default_policy(); + policy.network_middlewares.insert( + "redactor".into(), + NetworkMiddlewareConfig { + middleware: "openshell/regex".into(), + on_error: "maybe".into(), + endpoints: Some(MiddlewareEndpointSelector { + include: vec!["api[.example.com".into()], + exclude: Vec::new(), + }), + ..Default::default() + }, + ); + + let err = validate_policy_safety(&policy).unwrap_err(); + assert_eq!(err.code(), Code::InvalidArgument); + assert!(err.message().contains("invalid on_error")); + assert!(err.message().contains("invalid host pattern")); + } + #[test] fn validate_no_reserved_provider_policy_keys_rejects_reserved_key() { use openshell_core::proto::NetworkPolicyRule; diff --git a/crates/openshell-server/src/lib.rs b/crates/openshell-server/src/lib.rs index d40364523c..dc00bc4561 100644 --- a/crates/openshell-server/src/lib.rs +++ b/crates/openshell-server/src/lib.rs @@ -32,6 +32,7 @@ mod defaults; mod grpc; mod http; mod inference; +mod middleware; mod multiplex; mod persistence; pub(crate) mod policy_store; @@ -54,6 +55,7 @@ mod ws_tunnel; use metrics_exporter_prometheus::PrometheusBuilder; use openshell_core::{ComputeDriverKind, Config, Error, Result}; +use openshell_supervisor_middleware::MiddlewareRegistry; use std::collections::HashMap; use std::io::ErrorKind; use std::net::SocketAddr; @@ -127,6 +129,9 @@ pub struct ServerState { /// query session state to surface supervisor readiness. pub supervisor_sessions: Arc, + /// Validated built-in and operator-registered supervisor middleware. + pub middleware_registry: Arc, + /// OIDC JWKS cache for JWT validation. `None` when OIDC is not configured. pub oidc_cache: Option>, @@ -201,6 +206,7 @@ impl ServerState { ssh_connections_by_sandbox: Mutex::new(HashMap::new()), settings_mutex: tokio::sync::Mutex::new(()), supervisor_sessions, + middleware_registry: Arc::new(MiddlewareRegistry::default()), oidc_cache, sandbox_jwt_issuer: None, sandbox_jwt_authenticator: None, @@ -235,6 +241,26 @@ pub(crate) async fn run_server( return Err(Error::config("database_url is required")); } + let middleware_registrations = config_file + .as_ref() + .map(|file| { + file.openshell + .supervisor + .middleware + .iter() + .map(Into::into) + .collect() + }) + .unwrap_or_default(); + let middleware_registry = Arc::new( + MiddlewareRegistry::connect_services( + openshell_supervisor_middleware_builtins::services(), + middleware_registrations, + ) + .await + .map_err(|error| Error::config(format!("middleware registration failed: {error}")))?, + ); + let store = Arc::new(Store::connect(database_url).await?); let oidc_cache = if let Some(ref oidc) = config.oidc { @@ -304,6 +330,7 @@ pub(crate) async fn run_server( supervisor_sessions, oidc_cache, ); + state.middleware_registry = middleware_registry; state.gateway_interceptors = gateway_interceptors; state.provider_profile_sources = provider_profile_sources; diff --git a/crates/openshell-server/src/middleware.rs b/crates/openshell-server/src/middleware.rs new file mode 100644 index 0000000000..31865b02a4 --- /dev/null +++ b/crates/openshell-server/src/middleware.rs @@ -0,0 +1,80 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +use openshell_core::proto::SandboxPolicy; +use openshell_supervisor_middleware::MiddlewareRegistry; +use tonic::Status; + +/// Validate implementation-owned middleware config before accepting a policy. +pub async fn validate_policy( + registry: &MiddlewareRegistry, + policy: &SandboxPolicy, +) -> Result<(), Status> { + registry + .validate_policy_configs(policy) + .await + .map_err(|error| { + Status::invalid_argument(format!("policy middleware validation failed: {error}")) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use openshell_core::proto::NetworkMiddlewareConfig; + + #[tokio::test] + async fn unregistered_external_middleware_is_rejected_before_admission() { + let policy = SandboxPolicy { + network_middlewares: std::collections::HashMap::from([( + "guard".into(), + NetworkMiddlewareConfig { + middleware: "example/content-guard".into(), + ..Default::default() + }, + )]), + ..Default::default() + }; + + let error = validate_policy(&MiddlewareRegistry::default(), &policy) + .await + .expect_err("unregistered middleware must fail"); + assert_eq!(error.code(), tonic::Code::InvalidArgument); + assert!(error.message().contains("not registered")); + } + + #[tokio::test] + async fn invalid_builtin_config_is_rejected_by_implementation() { + let registry = MiddlewareRegistry::connect_services( + openshell_supervisor_middleware_builtins::services(), + Vec::new(), + ) + .await + .expect("built-in registry"); + let policy = SandboxPolicy { + network_middlewares: std::collections::HashMap::from([( + "redactor".into(), + NetworkMiddlewareConfig { + middleware: openshell_supervisor_middleware_builtins::BUILTIN_REGEX.into(), + config: Some(prost_types::Struct { + fields: std::iter::once(( + "mode".into(), + prost_types::Value { + kind: Some(prost_types::value::Kind::StringValue("allow".into())), + }, + )) + .collect(), + }), + ..Default::default() + }, + )]), + ..Default::default() + }; + + let error = validate_policy(®istry, &policy) + .await + .expect_err("invalid built-in config must fail admission"); + assert_eq!(error.code(), tonic::Code::InvalidArgument); + assert!(error.message().contains("supports only mode: redact")); + } +} diff --git a/crates/openshell-supervisor-middleware-builtins/Cargo.toml b/crates/openshell-supervisor-middleware-builtins/Cargo.toml new file mode 100644 index 0000000000..f892c718fd --- /dev/null +++ b/crates/openshell-supervisor-middleware-builtins/Cargo.toml @@ -0,0 +1,27 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +[package] +name = "openshell-supervisor-middleware-builtins" +description = "First-party in-process supervisor middleware implementations for OpenShell" +version.workspace = true +edition.workspace = true +license.workspace = true +repository.workspace = true +rust-version.workspace = true + +[dependencies] +openshell-core = { path = "../openshell-core", default-features = false } + +miette = { workspace = true } +prost-types = { workspace = true } +regex = { workspace = true } +serde = { workspace = true } +serde_json = { workspace = true } +tonic = { workspace = true, features = ["server"] } + +[dev-dependencies] +tokio = { workspace = true } + +[lints] +workspace = true diff --git a/crates/openshell-supervisor-middleware-builtins/src/lib.rs b/crates/openshell-supervisor-middleware-builtins/src/lib.rs new file mode 100644 index 0000000000..e23a228f05 --- /dev/null +++ b/crates/openshell-supervisor-middleware-builtins/src/lib.rs @@ -0,0 +1,202 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! First-party in-process supervisor middleware implementations. + +mod regex; + +use std::sync::Arc; + +use miette::{Result, miette}; +use openshell_core::proto::middleware::v1::supervisor_middleware_server::SupervisorMiddleware; +use openshell_core::proto::{ + HttpRequestEvaluation, HttpRequestResult, MiddlewareManifest, ValidateConfigRequest, + ValidateConfigResponse, +}; +use tonic::{Request, Response, Status}; + +pub use regex::{NAME as BUILTIN_REGEX, RegexConfig, RegexMode}; + +/// Return the first-party services that the gateway and supervisor install. +pub fn services() -> Vec> { + vec![Arc::new(BuiltinMiddlewareService)] +} + +/// Validate configuration for a first-party binding. +pub fn validate_config(implementation: &str, config: &prost_types::Struct) -> Result<()> { + match implementation { + BUILTIN_REGEX => regex::validate_config(config), + other => Err(miette!( + "middleware implementation '{other}' is not a registered OpenShell built-in" + )), + } +} + +fn evaluate_http_request(evaluation: &HttpRequestEvaluation) -> Result { + match evaluation.middleware_name.as_str() { + BUILTIN_REGEX => regex::evaluate_http_request(evaluation), + other => Err(miette!( + "middleware implementation '{other}' is not a registered OpenShell built-in" + )), + } +} + +/// Built-in regex service exposed through the standard middleware contract. +#[derive(Debug, Default)] +pub struct BuiltinMiddlewareService; + +#[tonic::async_trait] +impl SupervisorMiddleware for BuiltinMiddlewareService { + async fn describe( + &self, + _request: Request<()>, + ) -> Result, Status> { + Ok(Response::new(MiddlewareManifest { + name: BUILTIN_REGEX.into(), + service_version: env!("CARGO_PKG_VERSION").into(), + bindings: vec![regex::describe()], + })) + } + + async fn validate_config( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + let config = request.config.unwrap_or_default(); + Ok(Response::new( + match validate_config(&request.middleware_name, &config) { + Ok(()) => ValidateConfigResponse { + valid: true, + reason: String::new(), + }, + Err(error) => ValidateConfigResponse { + valid: false, + reason: error.to_string(), + }, + }, + )) + } + + async fn evaluate_http_request( + &self, + request: Request, + ) -> Result, Status> { + evaluate_http_request(&request.into_inner()) + .map(Response::new) + .map_err(|error| Status::invalid_argument(error.to_string())) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use openshell_core::proto::{ + Decision, SupervisorMiddlewareOperation, SupervisorMiddlewarePhase, + }; + + fn string_config(key: &str, value: &str) -> prost_types::Struct { + prost_types::Struct { + fields: std::iter::once(( + key.to_string(), + prost_types::Value { + kind: Some(prost_types::value::Kind::StringValue(value.into())), + }, + )) + .collect(), + } + } + + #[tokio::test] + async fn service_describes_regex_binding() { + let manifest = BuiltinMiddlewareService + .describe(Request::new(())) + .await + .expect("describe") + .into_inner(); + assert_eq!(manifest.bindings.len(), 1); + assert_eq!( + manifest.bindings[0].operation, + SupervisorMiddlewareOperation::HttpRequest as i32 + ); + assert_eq!( + manifest.bindings[0].phase, + SupervisorMiddlewarePhase::PreCredentials as i32 + ); + assert_eq!(manifest.bindings[0].max_body_bytes, 256 * 1024); + } + + #[test] + fn regex_config_defaults_to_redact() { + let config = RegexConfig::from_struct(&prost_types::Struct::default()).unwrap(); + assert_eq!(config.mode, RegexMode::Redact); + } + + #[test] + fn regex_config_accepts_explicit_redact() { + let config = RegexConfig::from_struct(&string_config("mode", "redact")).unwrap(); + assert_eq!(config.mode, RegexMode::Redact); + } + + #[test] + fn regex_config_rejects_unsupported_or_malformed_values() { + for config in [ + string_config("mode", "allow"), + string_config("patterns", "password"), + prost_types::Struct { + fields: std::iter::once(( + "mode".into(), + prost_types::Value { + kind: Some(prost_types::value::Kind::NumberValue(42.0)), + }, + )) + .collect(), + }, + ] { + assert!(validate_config(BUILTIN_REGEX, &config).is_err()); + } + } + + #[test] + fn regex_replacement_evaluates_through_binding() { + let result = evaluate_http_request(&HttpRequestEvaluation { + middleware_name: BUILTIN_REGEX.into(), + body: br#"{"password":"top-secret","token":"sk-ABCDEFGHIJKLMNOP"}"#.to_vec(), + config: Some(prost_types::Struct::default()), + ..Default::default() + }) + .expect("evaluate regex binding"); + + assert_eq!(result.decision, Decision::Allow as i32); + assert!(result.has_body); + let body = String::from_utf8(result.body).unwrap(); + assert!(body.contains("top-secret")); + assert!(!body.contains("sk-ABCDEFGHIJKLMNOP")); + assert!( + result + .findings + .iter() + .all(|finding| finding.r#type != "regex.keyword") + ); + } + + #[test] + fn regex_replacement_does_not_parse_keyword_assignments() { + let body = concat!( + r#"{"password":"alpha beta","secret":"alpha,beta","api_key":"alpha\"beta"}"#, + "\npassword=alpha\nnotpassword=omega" + ); + let result = evaluate_http_request(&HttpRequestEvaluation { + middleware_name: BUILTIN_REGEX.into(), + body: body.as_bytes().to_vec(), + config: Some(prost_types::Struct::default()), + ..Default::default() + }) + .expect("evaluate regex binding"); + + assert_eq!(result.decision, Decision::Allow as i32); + assert!(!result.has_body); + assert_eq!(result.body, body.as_bytes()); + assert!(result.findings.is_empty()); + } +} diff --git a/crates/openshell-supervisor-middleware-builtins/src/regex.rs b/crates/openshell-supervisor-middleware-builtins/src/regex.rs new file mode 100644 index 0000000000..34e727430a --- /dev/null +++ b/crates/openshell-supervisor-middleware-builtins/src/regex.rs @@ -0,0 +1,132 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Example built-in middleware that applies a fixed set of regular-expression +//! replacements to UTF-8 request bodies. +//! +//! This is intentionally a best-effort text transformation, not a secret +//! scanner or a parser-aware redactor. It provides no guarantee that sensitive +//! values will be detected or fully removed. + +use std::collections::HashMap; +use std::sync::LazyLock; + +use miette::{Result, miette}; +use openshell_core::proto::{ + Decision, Finding, HttpRequestEvaluation, HttpRequestResult, MiddlewareBinding, + SupervisorMiddlewareOperation, SupervisorMiddlewarePhase, +}; +use regex::Regex; +use serde::Deserialize; + +pub const NAME: &str = "openshell/regex"; +const MAX_BODY_BYTES: u64 = 256 * 1024; + +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct RegexConfig { + /// Replacement mode. Omitting the field selects [`RegexMode::Redact`]. + pub mode: RegexMode, +} + +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum RegexMode { + #[default] + Redact, +} + +impl RegexConfig { + pub fn from_struct(config: &prost_types::Struct) -> Result { + serde_json::from_value(openshell_core::proto_struct::struct_to_json_value(config)).map_err( + |error| { + miette!("invalid {NAME} config: {error}; this example supports only mode: redact") + }, + ) + } +} + +pub fn describe() -> MiddlewareBinding { + MiddlewareBinding { + operation: SupervisorMiddlewareOperation::HttpRequest as i32, + phase: SupervisorMiddlewarePhase::PreCredentials as i32, + max_body_bytes: MAX_BODY_BYTES, + timeout: String::new(), + } +} + +struct ReplacementPattern { + kind: &'static str, + regex: Regex, +} + +impl ReplacementPattern { + fn new(kind: &'static str, pattern: &str) -> Self { + Self { + kind, + regex: Regex::new(pattern).expect("valid built-in replacement pattern"), + } + } +} + +// TODO: Allow policies to supply custom replacement expressions after the +// configuration contract, validation limits, and replacement semantics are +// designed. The initial example deliberately exposes only these fixed patterns. +static REPLACEMENT_PATTERNS: LazyLock<[ReplacementPattern; 1]> = + LazyLock::new(|| [ReplacementPattern::new("openai", r"sk-[A-Za-z0-9_-]{16,}")]); + +pub fn validate_config(config: &prost_types::Struct) -> Result<()> { + RegexConfig::from_struct(config).map(|_| ()) +} + +pub fn evaluate_http_request(evaluation: &HttpRequestEvaluation) -> Result { + let default_config = prost_types::Struct::default(); + validate_config(evaluation.config.as_ref().unwrap_or(&default_config))?; + let text = String::from_utf8(evaluation.body.clone()) + .map_err(|_| miette!("{NAME} requires UTF-8 request bodies"))?; + let (body, matches) = apply_replacements(&text); + let total: u32 = matches + .iter() + .fold(0u32, |acc, (_, count)| acc.saturating_add(*count)); + let mut result = HttpRequestResult { + decision: Decision::Allow as i32, + reason: String::new(), + body: body.into_bytes(), + has_body: !matches.is_empty(), + header_mutations: Vec::new(), + findings: Vec::new(), + metadata: HashMap::new(), + reason_code: String::new(), + }; + for (kind, count) in &matches { + result.findings.push(Finding { + r#type: format!("regex.{kind}"), + label: format!("{kind} regex match"), + count: *count, + confidence: "medium".into(), + severity: "medium".into(), + }); + } + if !matches.is_empty() { + result + .metadata + .insert("regex_matches_replaced".into(), total.to_string()); + } + Ok(result) +} + +fn apply_replacements(input: &str) -> (String, Vec<(&'static str, u32)>) { + let mut output = input.to_string(); + let mut matches = Vec::new(); + for pattern in REPLACEMENT_PATTERNS.iter() { + let count = u32::try_from(pattern.regex.find_iter(&output).count()).unwrap_or(u32::MAX); + if count > 0 { + matches.push((pattern.kind, count)); + } + output = pattern + .regex + .replace_all(&output, "[REDACTED]") + .into_owned(); + } + (output, matches) +} diff --git a/crates/openshell-supervisor-middleware/Cargo.toml b/crates/openshell-supervisor-middleware/Cargo.toml new file mode 100644 index 0000000000..9cdc53febb --- /dev/null +++ b/crates/openshell-supervisor-middleware/Cargo.toml @@ -0,0 +1,27 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +[package] +name = "openshell-supervisor-middleware" +description = "Supervisor middleware registry and chain execution for OpenShell" +version.workspace = true +edition.workspace = true +license.workspace = true +repository.workspace = true +rust-version.workspace = true + +[dependencies] +openshell-core = { path = "../openshell-core", default-features = false } + +miette = { workspace = true } +prost = { workspace = true } +prost-types = { workspace = true } +tokio = { workspace = true } +tonic = { workspace = true, features = ["channel", "server", "tls-native-roots"] } + +[dev-dependencies] +openshell-supervisor-middleware-builtins = { path = "../openshell-supervisor-middleware-builtins" } +tokio-stream = { workspace = true, features = ["net"] } + +[lints] +workspace = true diff --git a/crates/openshell-supervisor-middleware/src/headers.rs b/crates/openshell-supervisor-middleware/src/headers.rs new file mode 100644 index 0000000000..655cf4790a --- /dev/null +++ b/crates/openshell-supervisor-middleware/src/headers.rs @@ -0,0 +1,417 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Validation and logical application of middleware request-header mutations. + +use openshell_core::proto::{ExistingHeaderAction, HeaderMutation, header_mutation}; + +pub const MAX_HEADER_MUTATIONS: usize = 64; +pub const MAX_HEADER_MUTATION_BYTES: usize = 32 * 1024; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum HeaderMutationError { + TooMany { count: usize }, + InvalidName { name: String }, + Protected { name: String }, + HopByHop { name: String }, + WriteNamespace { name: String }, + UnsafeValue { name: String }, + TooLarge, + InvalidExistingAction, + MissingExistingAction { name: String }, + UnsupportedExistingAction, + Empty, +} + +impl HeaderMutationError { + /// Stable platform-owned reason suitable for untrusted middleware failures. + pub(crate) fn code(&self) -> &'static str { + match self { + Self::TooMany { .. } => "header_mutation_count_over_capacity", + Self::InvalidName { .. } => "header_mutation_invalid_name", + Self::Protected { .. } => "header_mutation_protected_header", + Self::HopByHop { .. } => "header_mutation_hop_by_hop_header", + Self::WriteNamespace { .. } => "header_mutation_write_namespace", + Self::UnsafeValue { .. } => "header_mutation_unsafe_value", + Self::TooLarge => "header_mutation_bytes_over_capacity", + Self::InvalidExistingAction => "header_mutation_invalid_existing_action", + Self::MissingExistingAction { .. } => "header_mutation_missing_existing_action", + Self::UnsupportedExistingAction => "header_mutation_unsupported_existing_action", + Self::Empty => "header_mutation_empty", + } + } +} + +impl std::fmt::Display for HeaderMutationError { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::TooMany { count } => write!( + formatter, + "middleware returned too many header mutations: {count} exceeds {MAX_HEADER_MUTATIONS}" + ), + Self::InvalidName { name } => { + write!( + formatter, + "middleware returned invalid header name '{name}'" + ) + } + Self::Protected { name } => { + write!( + formatter, + "middleware cannot mutate protected header '{name}'" + ) + } + Self::HopByHop { name } => { + write!( + formatter, + "middleware cannot mutate hop-by-hop header '{name}'" + ) + } + Self::WriteNamespace { name } => write!( + formatter, + "middleware can only write request headers prefixed with x-openshell-middleware- and cannot write '{name}'" + ), + Self::UnsafeValue { name } => { + write!( + formatter, + "middleware cannot write header '{name}' with an unsafe value" + ) + } + Self::TooLarge => write!( + formatter, + "middleware header mutations exceed {MAX_HEADER_MUTATION_BYTES} bytes" + ), + Self::InvalidExistingAction => { + write!(formatter, "middleware returned invalid on_existing action") + } + Self::MissingExistingAction { name } => write!( + formatter, + "middleware must specify on_existing for header '{name}'" + ), + Self::UnsupportedExistingAction => { + write!( + formatter, + "middleware returned unsupported on_existing action" + ) + } + Self::Empty => write!(formatter, "middleware returned an empty header mutation"), + } + } +} + +impl std::error::Error for HeaderMutationError {} + +/// Validate and atomically apply one middleware response to the logical header +/// state observed by the next middleware. Repeated values and wire order are +/// preserved; comparisons are case-insensitive. +pub fn apply( + existing_headers: &[(String, String)], + connection_nominated_headers: &[String], + mutations: &[HeaderMutation], +) -> Result, HeaderMutationError> { + if mutations.len() > MAX_HEADER_MUTATIONS { + return Err(HeaderMutationError::TooMany { + count: mutations.len(), + }); + } + + let mut headers = existing_headers.to_vec(); + let mut mutation_bytes = 0usize; + for mutation in mutations { + match mutation.operation.as_ref() { + Some(header_mutation::Operation::Write(write)) => { + let name = validate_name(&write.name)?; + if is_connection_nominated(connection_nominated_headers, &name) { + return Err(HeaderMutationError::HopByHop { + name: write.name.clone(), + }); + } + if !name.starts_with("x-openshell-middleware-") { + return Err(HeaderMutationError::WriteNamespace { + name: write.name.clone(), + }); + } + if !is_safe_value(&write.value) { + return Err(HeaderMutationError::UnsafeValue { + name: write.name.clone(), + }); + } + mutation_bytes = mutation_bytes + .saturating_add(name.len()) + .saturating_add(write.value.len()); + enforce_size_limit(mutation_bytes)?; + + let action = ExistingHeaderAction::try_from(write.on_existing) + .map_err(|_| HeaderMutationError::InvalidExistingAction)?; + if action == ExistingHeaderAction::Unspecified { + return Err(HeaderMutationError::MissingExistingAction { + name: write.name.clone(), + }); + } + let exists = headers.iter().any(|(existing, _)| *existing == name); + if !exists || action == ExistingHeaderAction::Append { + headers.push((name, write.value.clone())); + } else if action == ExistingHeaderAction::Overwrite { + headers.retain(|(existing, _)| *existing != name); + headers.push((name, write.value.clone())); + } else if action != ExistingHeaderAction::Skip { + return Err(HeaderMutationError::UnsupportedExistingAction); + } + } + Some(header_mutation::Operation::Remove(remove)) => { + let name = validate_name(&remove.name)?; + if is_connection_nominated(connection_nominated_headers, &name) { + return Err(HeaderMutationError::HopByHop { + name: remove.name.clone(), + }); + } + mutation_bytes = mutation_bytes.saturating_add(name.len()); + enforce_size_limit(mutation_bytes)?; + headers.retain(|(existing, _)| *existing != name); + } + None => return Err(HeaderMutationError::Empty), + } + } + Ok(headers) +} + +fn enforce_size_limit(mutation_bytes: usize) -> Result<(), HeaderMutationError> { + if mutation_bytes > MAX_HEADER_MUTATION_BYTES { + return Err(HeaderMutationError::TooLarge); + } + Ok(()) +} + +fn validate_name(name: &str) -> Result { + let lower = name.to_ascii_lowercase(); + if lower.is_empty() || !lower.bytes().all(is_name_token_byte) { + return Err(HeaderMutationError::InvalidName { + name: name.to_string(), + }); + } + if is_protected(&lower) { + return Err(HeaderMutationError::Protected { + name: name.to_string(), + }); + } + Ok(lower) +} + +fn is_name_token_byte(byte: u8) -> bool { + byte.is_ascii_alphanumeric() + || matches!( + byte, + b'!' | b'#' + | b'$' + | b'%' + | b'&' + | b'\'' + | b'*' + | b'+' + | b'-' + | b'.' + | b'^' + | b'_' + | b'`' + | b'|' + | b'~' + ) +} + +/// A header value is safe to write only if it contains no control characters. +/// Horizontal tab, printable ASCII, and obs-text (>= 0x80) are permitted; CR, LF, +/// NUL, and other control bytes are rejected. +fn is_safe_value(value: &str) -> bool { + value + .bytes() + .all(|byte| byte == b'\t' || (0x20..=0x7e).contains(&byte) || byte >= 0x80) +} + +fn is_protected(name: &str) -> bool { + matches!( + name, + "authorization" + | "proxy-authorization" + | "proxy-authenticate" + | "cookie" + | "host" + | "content-length" + | "transfer-encoding" + | "connection" + | "proxy-connection" + | "keep-alive" + | "te" + | "trailer" + | "upgrade" + ) || name.starts_with("x-amz-") + || name.starts_with("x-openshell-credential") +} + +fn is_connection_nominated(connection_nominated_headers: &[String], name: &str) -> bool { + connection_nominated_headers + .iter() + .any(|nominated| nominated.eq_ignore_ascii_case(name)) +} + +#[cfg(test)] +mod tests { + use super::*; + use openshell_core::proto::{RemoveHeader, WriteHeader}; + + fn write(name: &str, value: &str, on_existing: ExistingHeaderAction) -> HeaderMutation { + HeaderMutation { + operation: Some(header_mutation::Operation::Write(WriteHeader { + name: name.into(), + value: value.into(), + on_existing: on_existing as i32, + })), + } + } + + fn remove(name: &str) -> HeaderMutation { + HeaderMutation { + operation: Some(header_mutation::Operation::Remove(RemoveHeader { + name: name.into(), + })), + } + } + + #[test] + fn protected_header_write_is_rejected() { + let error = apply( + &[], + &[], + &[write( + "Authorization", + "Bearer nope", + ExistingHeaderAction::Overwrite, + )], + ) + .expect_err("protected header"); + assert!( + error + .to_string() + .contains("protected header 'Authorization'") + ); + } + + #[test] + fn unsafe_header_value_is_rejected() { + let error = apply( + &[], + &[], + &[write( + "x-openshell-middleware-inject", + "ok\r\nAuthorization: Bearer evil", + ExistingHeaderAction::Append, + )], + ) + .expect_err("CRLF value"); + assert!(error.to_string().contains("unsafe value")); + } + + #[test] + fn existing_header_write_obeys_collision_action() { + let existing = [ + ("x-openshell-middleware-tag".to_string(), "one".to_string()), + ("accept".to_string(), "application/json".to_string()), + ]; + let appended = apply( + &existing, + &[], + &[write( + "X-OpenShell-Middleware-Tag", + "two", + ExistingHeaderAction::Append, + )], + ) + .expect("append existing header"); + assert_eq!( + appended, + vec![ + ("x-openshell-middleware-tag".into(), "one".into()), + ("accept".into(), "application/json".into()), + ("x-openshell-middleware-tag".into(), "two".into()), + ] + ); + + let overwritten = apply( + &existing, + &[], + &[write( + "X-OpenShell-Middleware-Tag", + "two", + ExistingHeaderAction::Overwrite, + )], + ) + .expect("overwrite existing header"); + assert_eq!( + overwritten, + vec![ + ("accept".into(), "application/json".into()), + ("x-openshell-middleware-tag".into(), "two".into()), + ] + ); + + let skipped = apply( + &existing, + &[], + &[write( + "X-OpenShell-Middleware-Tag", + "two", + ExistingHeaderAction::Skip, + )], + ) + .expect("skip existing header"); + assert_eq!(skipped, existing); + } + + #[test] + fn remove_drops_every_case_insensitive_value() { + let existing = [ + ("x-trace".to_string(), "one".to_string()), + ("accept".to_string(), "application/json".to_string()), + ("x-trace".to_string(), "two".to_string()), + ]; + let updated = apply(&existing, &[], &[remove("X-Trace")]).expect("remove visible header"); + assert_eq!(updated, vec![("accept".into(), "application/json".into())]); + } + + #[test] + fn protected_header_remove_is_rejected_even_when_not_visible() { + let error = apply(&[], &[], &[remove("Authorization")]).expect_err("protected removal"); + assert!( + error + .to_string() + .contains("protected header 'Authorization'") + ); + } + + #[test] + fn connection_nominated_header_is_protected() { + let nominated = vec!["x-openshell-middleware-tag".to_string()]; + let write_error = apply( + &[], + &nominated, + &[write( + "X-OpenShell-Middleware-Tag", + "value", + ExistingHeaderAction::Append, + )], + ) + .expect_err("hop-by-hop write"); + assert!( + write_error + .to_string() + .contains("hop-by-hop header 'X-OpenShell-Middleware-Tag'") + ); + + let remove_error = apply(&[], &nominated, &[remove("X-OpenShell-Middleware-Tag")]) + .expect_err("hop-by-hop removal"); + assert!( + remove_error + .to_string() + .contains("hop-by-hop header 'X-OpenShell-Middleware-Tag'") + ); + } +} diff --git a/crates/openshell-supervisor-middleware/src/lib.rs b/crates/openshell-supervisor-middleware/src/lib.rs new file mode 100644 index 0000000000..fe0f15f0a6 --- /dev/null +++ b/crates/openshell-supervisor-middleware/src/lib.rs @@ -0,0 +1,3514 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Supervisor middleware registration and chain execution. + +mod headers; +mod remote; + +#[cfg(test)] +use std::collections::HashMap; +use std::collections::{BTreeMap, HashSet}; +use std::future::Future; +use std::sync::Arc; +use std::time::Duration; + +use miette::{Result, miette}; +use prost::Message; + +use openshell_core::proto::middleware::v1::supervisor_middleware_server::SupervisorMiddleware; +use openshell_core::proto::{ + Decision, Finding, HeaderMutation, HttpHeader, HttpRequestEvaluation, HttpRequestTarget, + MiddlewareBinding, MiddlewareManifest, NetworkMiddlewareConfig, RequestContext, SandboxPolicy, + SupervisorMiddlewareOperation, SupervisorMiddlewarePhase, SupervisorMiddlewareService, + ValidateConfigRequest, +}; +use tokio::sync::OnceCell; +use tonic::Request; + +pub use openshell_core::middleware::{ + DEFAULT_MIDDLEWARE_TIMEOUT, MAX_MIDDLEWARE_CHAIN_FINDINGS, MAX_MIDDLEWARE_CHAIN_STAGES, + MAX_MIDDLEWARE_CONFIGS, MAX_MIDDLEWARE_FINDINGS_PER_STAGE, MAX_MIDDLEWARE_SELECTOR_PATTERNS, + MAX_MIDDLEWARE_TIMEOUT, MIN_MIDDLEWARE_TIMEOUT, middleware_timeout_or_default, + parse_middleware_timeout, +}; + +/// Largest request or replacement body accepted by the middleware platform. +pub const MAX_MIDDLEWARE_BODY_BYTES: usize = 4 * 1024 * 1024; +/// Largest encoded service-specific configuration attached to one evaluation. +pub const MAX_MIDDLEWARE_CONFIG_BYTES: usize = 64 * 1024; +/// Largest encoded request identity context attached to one evaluation. +pub const MAX_MIDDLEWARE_CONTEXT_BYTES: usize = 4 * 1024; +/// Largest encoded destination and request target attached to one evaluation. +pub const MAX_MIDDLEWARE_TARGET_BYTES: usize = 32 * 1024; +/// Largest number of request header lines exposed to one middleware. +pub const MAX_MIDDLEWARE_HEADERS: usize = 128; +/// Largest encoded request header collection exposed to one middleware. +pub const MAX_MIDDLEWARE_HEADER_BYTES: usize = 64 * 1024; +/// Largest operator-provided reason accepted in one middleware result. +pub const MAX_MIDDLEWARE_REASON_BYTES: usize = 4 * 1024; +/// Largest stable reason code accepted in one middleware result. +pub const MAX_MIDDLEWARE_REASON_CODE_BYTES: usize = 64; +/// Largest encoded individual finding accepted from one middleware stage. +pub const MAX_MIDDLEWARE_FINDING_BYTES: usize = 4 * 1024; +/// Largest number of metadata entries accepted from one middleware stage. +pub const MAX_MIDDLEWARE_METADATA_ENTRIES: usize = 64; +/// Largest combined metadata key/value payload accepted from one middleware stage. +pub const MAX_MIDDLEWARE_METADATA_BYTES: usize = 32 * 1024; + +const MAX_MIDDLEWARE_HEADER_MUTATION_WIRE_BYTES: usize = 64 * 1024; +const MAX_MIDDLEWARE_PROTOBUF_OVERHEAD_BYTES: usize = 64 * 1024; +const MAX_MIDDLEWARE_REQUEST_ENVELOPE_BYTES: usize = MAX_MIDDLEWARE_CONFIG_BYTES + + MAX_MIDDLEWARE_CONTEXT_BYTES + + MAX_MIDDLEWARE_TARGET_BYTES + + MAX_MIDDLEWARE_HEADER_BYTES + + MAX_MIDDLEWARE_PROTOBUF_OVERHEAD_BYTES; +const MAX_MIDDLEWARE_RESPONSE_ENVELOPE_BYTES: usize = MAX_MIDDLEWARE_REASON_BYTES + + MAX_MIDDLEWARE_REASON_CODE_BYTES + + MAX_MIDDLEWARE_HEADER_MUTATION_WIRE_BYTES + + MAX_MIDDLEWARE_FINDINGS_PER_STAGE * MAX_MIDDLEWARE_FINDING_BYTES + + MAX_MIDDLEWARE_METADATA_BYTES + + MAX_MIDDLEWARE_PROTOBUF_OVERHEAD_BYTES; +/// gRPC envelope headroom derived from every bounded non-body component. +pub const MIDDLEWARE_GRPC_ENVELOPE_BYTES: usize = + if MAX_MIDDLEWARE_REQUEST_ENVELOPE_BYTES > MAX_MIDDLEWARE_RESPONSE_ENVELOPE_BYTES { + MAX_MIDDLEWARE_REQUEST_ENVELOPE_BYTES + } else { + MAX_MIDDLEWARE_RESPONSE_ENVELOPE_BYTES + }; +/// gRPC message limit derived from the body and bounded protobuf components. +pub const MIDDLEWARE_GRPC_MESSAGE_BYTES: usize = + MAX_MIDDLEWARE_BODY_BYTES + MIDDLEWARE_GRPC_ENVELOPE_BYTES; + +const HTTP_REQUEST_OPERATION: SupervisorMiddlewareOperation = + SupervisorMiddlewareOperation::HttpRequest; +const PRE_CREDENTIALS_PHASE: SupervisorMiddlewarePhase = SupervisorMiddlewarePhase::PreCredentials; +const MAX_STABLE_IDENTIFIER_BYTES: usize = 128; +const EXTERNAL_FINDING_LABEL: &str = "External middleware finding"; +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum OnError { + FailClosed, + FailOpen, +} + +impl OnError { + pub fn parse(value: &str) -> Result { + match value { + "" | "fail_closed" => Ok(Self::FailClosed), + "fail_open" => Ok(Self::FailOpen), + other => Err(miette!( + "invalid middleware on_error '{other}', expected fail_closed or fail_open" + )), + } + } +} + +#[derive(Debug, Clone)] +pub struct ChainEntry { + pub name: String, + pub implementation: String, + pub order: i32, + pub config: prost_types::Struct, + pub on_error: OnError, +} + +impl TryFrom<(&str, &NetworkMiddlewareConfig)> for ChainEntry { + type Error = miette::Report; + + fn try_from((name, value): (&str, &NetworkMiddlewareConfig)) -> Result { + if name.is_empty() { + return Err(miette!("middleware config name cannot be empty")); + } + if value.middleware.is_empty() { + return Err(miette!( + "middleware config '{}' must reference a middleware", + name + )); + } + Ok(Self { + name: name.to_string(), + implementation: value.middleware.clone(), + order: value.order, + config: value.config.clone().unwrap_or_default(), + on_error: OnError::parse(&value.on_error)?, + }) + } +} + +/// A policy-selected middleware config joined with metadata reported by its +/// service's `Describe` call. A missing binding is retained so `on_error` can +/// decide whether the request fails open or closed. +#[derive(Clone)] +pub struct DescribedChainEntry { + entry: ChainEntry, + service: Option>, + binding: Option, + max_body_bytes: usize, + timeout: Duration, +} + +impl DescribedChainEntry { + pub fn max_body_bytes(&self) -> usize { + self.max_body_bytes + } + + pub fn on_error(&self) -> OnError { + self.entry.on_error + } + + pub fn timeout(&self) -> Duration { + self.timeout + } + + /// True when this entry resolved to a registered binding and will be + /// evaluated. When false, the binding is absent from the current registry + /// and the entry is handled entirely by its `on_error` policy, so it + /// imposes no body-buffering limit on the chain. + pub fn is_resolved(&self) -> bool { + self.binding.is_some() + } +} + +/// Re-checks a middleware-transformed request body against sandbox policy. +/// +/// Returns `Some(reason)` to deny the chain, `None` to proceed. Invoked after +/// each stage that replaces the body so neither a later stage nor the upstream +/// sees a payload the policy would reject. Protocols with no body-aware policy +/// select [`TransformedBodyPolicy::NotPolicyRelevant`] instead. +pub type TransformedBodyValidator<'a> = dyn Fn(&[u8]) -> Result> + Send + Sync + 'a; + +/// Whether middleware body replacements affect the selected request policy. +/// +/// The network pipeline must choose a mode explicitly. This avoids representing +/// a security-relevant re-evaluation requirement as an optional callback where +/// an omitted value is indistinguishable from an intentionally body-independent +/// protocol. +#[derive(Clone, Copy)] +pub enum TransformedBodyPolicy<'a> { + /// The selected policy does not inspect the request body. + NotPolicyRelevant, + /// Re-evaluate every body replacement before the next stage runs. + Reevaluate(&'a TransformedBodyValidator<'a>), +} + +#[derive(Debug, Clone)] +pub struct HttpRequestInput { + pub request_id: String, + pub sandbox_id: String, + pub scheme: String, + pub host: String, + pub port: u16, + pub method: String, + pub path: String, + pub query: String, + /// Lowercased request headers in wire order. Repeated header names are + /// preserved as separate entries so middleware inspects every value the + /// upstream will receive. + pub headers: Vec<(String, String)>, + /// Lowercased names nominated by the original request's `Connection` + /// headers. Their values are not exposed to middleware, but mutations must + /// still treat these dynamically hop-by-hop fields as protected. + pub connection_nominated_headers: Vec, + pub body: Vec, +} + +#[derive(Debug, Clone)] +pub struct ChainOutcome { + pub allowed: bool, + pub reason: String, + pub body: Vec, + /// Ordered, validated mutations to replay against the original raw request. + pub header_mutations: Vec, + pub findings: Vec, + pub metadata: BTreeMap>, + pub applied: Vec, + /// Present only when a middleware completed successfully and explicitly + /// denied the request. Fail-closed service errors and transformed-body + /// policy denials are not represented as middleware decisions. + pub denial: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct MiddlewareDenial { + /// Stable policy-local middleware config identity. + pub config_name: String, + /// Validated service-defined code. Free-form service reason text is never + /// carried into client responses or security logs. + pub reason_code: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct NamespacedFinding { + pub middleware: String, + pub finding: Finding, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct MiddlewareInvocation { + pub name: String, + pub implementation: String, + pub decision: Decision, + pub transformed: bool, + /// True when the middleware could not be evaluated and `on_error` was applied + /// (service error, malformed/unsafe response, etc.). The `decision` reflects + /// the `on_error` outcome, not a decision the middleware actually returned. + pub failed: bool, +} + +enum OnErrorAction { + /// `fail_open`: skip this middleware, leaving the request unchanged. + FailOpen, + /// `fail_closed`: short-circuit the chain and deny with the given reason. + FailClosed(String), +} + +/// Apply a middleware entry's `on_error` policy after a failure (service error or +/// malformed response). Records a `failed` invocation for telemetry in both cases. +fn apply_on_error( + entry: &DescribedChainEntry, + reason: &str, + applied: &mut Vec, +) -> OnErrorAction { + match entry.entry.on_error { + OnError::FailOpen => { + applied.push(MiddlewareInvocation { + name: entry.entry.name.clone(), + implementation: entry.entry.implementation.clone(), + decision: Decision::Allow, + transformed: false, + failed: true, + }); + OnErrorAction::FailOpen + } + OnError::FailClosed => { + applied.push(MiddlewareInvocation { + name: entry.entry.name.clone(), + implementation: entry.entry.implementation.clone(), + decision: Decision::Deny, + transformed: false, + failed: true, + }); + OnErrorAction::FailClosed(format!("middleware_failed: {reason}")) + } + } +} + +#[derive(Clone)] +pub struct ChainRunner { + registry: Arc, +} + +struct MiddlewareServiceState { + /// Policy-facing built-in name or operator-owned registration name. The + /// single-service test constructor leaves this empty and uses the manifest + /// name after Describe. + attachment_name: Option, + service: Arc, + manifest: OnceCell, + diagnostic_policy: MiddlewareDiagnosticPolicy, + operator_max_body_bytes: Option, + operator_timeout: Duration, +} + +impl MiddlewareServiceState { + fn timeout_for_binding(&self, binding: &MiddlewareBinding) -> Result { + if binding.timeout.trim().is_empty() { + Ok(self.operator_timeout) + } else { + parse_middleware_timeout(&binding.timeout) + .map(|binding_timeout| binding_timeout.min(self.operator_timeout)) + .map_err(|reason| miette!("middleware binding has invalid timeout: {reason}")) + } + } +} + +async fn call_with_timeout( + timeout: Duration, + operation: &'static str, + future: impl Future, tonic::Status>>, +) -> std::result::Result, tonic::Status> { + tokio::time::timeout(timeout, future).await.map_err(|_| { + tonic::Status::deadline_exceeded(format!("middleware {operation} timed out")) + })? +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum MiddlewareDiagnosticPolicy { + Preserve, + Normalize, +} + +impl MiddlewareDiagnosticPolicy { + fn error_reason(self, error: &tonic::Status) -> String { + match self { + Self::Preserve => safe_reason(&error.to_string()), + Self::Normalize => "external_service_error".to_string(), + } + } + + fn process_result( + self, + middleware_name: &str, + result: &mut openshell_core::proto::HttpRequestResult, + ) { + if self == Self::Normalize { + normalize_untrusted_diagnostics(middleware_name, result); + } + } + + fn header_mutation_error_reason(self, error: &headers::HeaderMutationError) -> String { + match self { + Self::Preserve => safe_reason(&error.to_string()), + Self::Normalize => error.code().to_string(), + } + } +} + +/// Validated middleware services available to a gateway or one supervisor. +/// +/// In-process services are supplied by the composition root; the generic +/// registry does not select concrete built-ins. All in-process and remote +/// services are described before construction succeeds, so callers never +/// observe a partially registered service set. +#[derive(Clone)] +pub struct MiddlewareRegistry { + services: Arc>>, + registered_services: Arc>, + middleware_names: Arc>, +} + +impl std::fmt::Debug for MiddlewareRegistry { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter + .debug_struct("MiddlewareRegistry") + .field("service_count", &self.services.len()) + .field("registered_service_count", &self.registered_services.len()) + .field("middleware_count", &self.middleware_names.len()) + .finish() + } +} + +#[derive(Clone)] +struct RegisteredMiddlewareService { + registration: SupervisorMiddlewareService, +} + +impl Default for MiddlewareRegistry { + fn default() -> Self { + Self { + services: Arc::new(Vec::new()), + registered_services: Arc::new(Vec::new()), + middleware_names: Arc::new(HashSet::new()), + } + } +} + +fn validate_registration(registration: &SupervisorMiddlewareService) -> Result { + if !is_stable_identifier(®istration.name) { + return Err(miette!( + "supervisor middleware registration names must be 1-{MAX_STABLE_IDENTIFIER_BYTES} bytes and contain only ASCII letters, digits, '.', '_', '-', or '/'" + )); + } + if registration.name.starts_with("openshell/") { + return Err(miette!( + "middleware registration '{}' cannot claim the reserved openshell/ namespace", + registration.name + )); + } + if !registration.grpc_endpoint.starts_with("http://") + && !registration.grpc_endpoint.starts_with("https://") + { + return Err(miette!( + "middleware registration '{}' grpc_endpoint must use http:// or https://", + registration.name + )); + } + if registration.max_body_bytes == 0 { + return Err(miette!( + "middleware registration '{}' max_body_bytes must be greater than zero", + registration.name + )); + } + if registration.max_body_bytes > MAX_MIDDLEWARE_BODY_BYTES as u64 { + return Err(miette!( + "middleware registration '{}' max_body_bytes exceeds the platform maximum of {MAX_MIDDLEWARE_BODY_BYTES}", + registration.name + )); + } + middleware_timeout_or_default(®istration.timeout).map_err(|reason| { + miette!( + "middleware registration '{}' has invalid timeout: {reason}", + registration.name + ) + }) +} + +fn is_stable_identifier(value: &str) -> bool { + !value.is_empty() + && value.len() <= MAX_STABLE_IDENTIFIER_BYTES + && value + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-' | b'/')) +} + +fn is_stable_reason_code(value: &str) -> bool { + value.len() <= MAX_MIDDLEWARE_REASON_CODE_BYTES + && value.as_bytes().first().is_some_and(u8::is_ascii_lowercase) + && value + .bytes() + .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_') +} + +fn middleware_denial_reason(config_name: &str, reason_code: Option<&str>) -> String { + let config_id: String = config_name + .chars() + .map(|character| { + if character.is_ascii_alphanumeric() || matches!(character, '_' | '-') { + character + } else { + '_' + } + }) + .take(MAX_STABLE_IDENTIFIER_BYTES) + .collect(); + reason_code.map_or_else( + || format!("middleware_denied:{config_id}"), + |code| format!("middleware_denied:{config_id}:{code}"), + ) +} + +fn validate_body_limit(source: &str, binding: &MiddlewareBinding) -> Result { + if binding.max_body_bytes == 0 { + return Err(miette!("{source} must advertise a non-zero body limit")); + } + if binding.max_body_bytes > MAX_MIDDLEWARE_BODY_BYTES as u64 { + return Err(miette!( + "{source} body limit exceeds the platform maximum of {MAX_MIDDLEWARE_BODY_BYTES}" + )); + } + usize::try_from(binding.max_body_bytes) + .map_err(|_| miette!("{source} reports a body limit too large for this platform")) +} + +fn validate_manifest_bindings( + source: &str, + manifest: &MiddlewareManifest, + operator_max_body_bytes: Option, +) -> Result<()> { + if manifest.bindings.is_empty() { + return Err(miette!("{source} describes no bindings")); + } + + let mut described_pairs = HashSet::with_capacity(manifest.bindings.len()); + for binding in &manifest.bindings { + if binding.operation != HTTP_REQUEST_OPERATION as i32 + || binding.phase != PRE_CREDENTIALS_PHASE as i32 + { + return Err(miette!( + "{source} must support HTTP_REQUEST/PRE_CREDENTIALS" + )); + } + if !described_pairs.insert((binding.operation, binding.phase)) { + return Err(miette!( + "{source} describes more than one binding for HTTP_REQUEST/PRE_CREDENTIALS" + )); + } + let advertised = validate_body_limit(source, binding)?; + if !binding.timeout.trim().is_empty() { + parse_middleware_timeout(&binding.timeout) + .map_err(|reason| miette!("{source} has invalid timeout for binding: {reason}"))?; + } + if operator_max_body_bytes.is_some_and(|limit| limit > advertised) { + return Err(miette!( + "{source} max_body_bytes ({}) exceeds the binding capability ({advertised})", + operator_max_body_bytes.expect("operator limit checked above") + )); + } + } + Ok(()) +} + +fn validate_external_manifest( + registration: &SupervisorMiddlewareService, + manifest: &MiddlewareManifest, + operator_max_body_bytes: usize, +) -> Result<()> { + validate_manifest_bindings( + &format!("external middleware registration '{}'", registration.name), + manifest, + Some(operator_max_body_bytes), + ) +} + +/// External diagnostic text is untrusted and may contain request data. Keep +/// only values derived from the validated, operator-owned registration name +/// and numeric finding counts; do not carry per-request free-form text into +/// logs. +fn normalize_untrusted_diagnostics( + middleware_name: &str, + result: &mut openshell_core::proto::HttpRequestResult, +) { + let reason_id: String = middleware_name + .chars() + .map(|character| { + if character.is_ascii_alphanumeric() || matches!(character, '_' | '-') { + character + } else { + '_' + } + }) + .collect(); + result.reason = format!("middleware_denied:{reason_id}"); + result.metadata.clear(); + for finding in &mut result.findings { + finding.r#type = format!("{middleware_name}.finding"); + finding.label = EXTERNAL_FINDING_LABEL.to_string(); + finding.confidence.clear(); + finding.severity = match finding.severity.as_str() { + "low" => "low", + "high" => "high", + _ => "medium", + } + .to_string(); + } +} + +fn validate_request_envelope( + evaluation: &HttpRequestEvaluation, +) -> std::result::Result<(), &'static str> { + if evaluation.body.len() > MAX_MIDDLEWARE_BODY_BYTES { + return Err("request_body_over_capacity"); + } + if evaluation + .config + .as_ref() + .is_some_and(|config| config.encoded_len() > MAX_MIDDLEWARE_CONFIG_BYTES) + { + return Err("request_config_over_capacity"); + } + if evaluation + .context + .as_ref() + .is_some_and(|context| context.encoded_len() > MAX_MIDDLEWARE_CONTEXT_BYTES) + { + return Err("request_context_over_capacity"); + } + if evaluation + .target + .as_ref() + .is_some_and(|target| target.encoded_len() > MAX_MIDDLEWARE_TARGET_BYTES) + { + return Err("request_target_over_capacity"); + } + if evaluation.headers.len() > MAX_MIDDLEWARE_HEADERS { + return Err("request_header_count_over_capacity"); + } + let header_bytes = evaluation.headers.iter().fold(0usize, |total, header| { + total.saturating_add(header.encoded_len()) + }); + if header_bytes > MAX_MIDDLEWARE_HEADER_BYTES { + return Err("request_header_bytes_over_capacity"); + } + if evaluation.encoded_len() > MIDDLEWARE_GRPC_MESSAGE_BYTES { + return Err("request_envelope_over_capacity"); + } + Ok(()) +} + +fn validate_response_envelope( + result: &openshell_core::proto::HttpRequestResult, +) -> std::result::Result<(), &'static str> { + if result.body.len() > MAX_MIDDLEWARE_BODY_BYTES { + return Err("response_body_over_capacity"); + } + if result.reason.len() > MAX_MIDDLEWARE_REASON_BYTES { + return Err("response_reason_over_capacity"); + } + if !result.reason_code.is_empty() && !is_stable_reason_code(&result.reason_code) { + return Err("response_reason_code_invalid"); + } + if result.header_mutations.len() > headers::MAX_HEADER_MUTATIONS { + return Err("header_mutation_count_over_capacity"); + } + let mutation_bytes = result + .header_mutations + .iter() + .fold(0usize, |total, mutation| { + total.saturating_add(mutation.encoded_len()) + }); + if mutation_bytes > MAX_MIDDLEWARE_HEADER_MUTATION_WIRE_BYTES { + return Err("header_mutation_bytes_over_capacity"); + } + if result.findings.len() > MAX_MIDDLEWARE_FINDINGS_PER_STAGE { + return Err("response_findings_over_capacity"); + } + if result + .findings + .iter() + .any(|finding| finding.encoded_len() > MAX_MIDDLEWARE_FINDING_BYTES) + { + return Err("response_finding_over_capacity"); + } + if result.metadata.len() > MAX_MIDDLEWARE_METADATA_ENTRIES { + return Err("response_metadata_count_over_capacity"); + } + let metadata_bytes = result.metadata.iter().fold(0usize, |total, (key, value)| { + total.saturating_add(key.len()).saturating_add(value.len()) + }); + if metadata_bytes > MAX_MIDDLEWARE_METADATA_BYTES { + return Err("response_metadata_bytes_over_capacity"); + } + if result.encoded_len() > MIDDLEWARE_GRPC_MESSAGE_BYTES { + return Err("response_envelope_over_capacity"); + } + Ok(()) +} + +impl MiddlewareRegistry { + /// Describe in-process services, then connect and validate every + /// operator-provided service registration. + pub async fn connect_services( + in_process_services: Vec>, + registrations: Vec, + ) -> Result { + let mut services = Vec::with_capacity(in_process_services.len() + registrations.len()); + let mut registered_services = Vec::with_capacity(registrations.len()); + let mut middleware_names = HashSet::new(); + + for service in in_process_services { + let manifest = call_with_timeout( + DEFAULT_MIDDLEWARE_TIMEOUT, + "Describe", + service.describe(Request::new(())), + ) + .await + .map(tonic::Response::into_inner) + .map_err(|error| { + miette!( + "in-process middleware Describe failed: {}", + safe_reason(&error.to_string()) + ) + })?; + let source = if manifest.name.trim().is_empty() { + "in-process middleware service".to_string() + } else { + format!("in-process middleware service '{}'", manifest.name) + }; + if !is_stable_identifier(&manifest.name) { + return Err(miette!( + "in-process middleware names must be 1-{MAX_STABLE_IDENTIFIER_BYTES} bytes and contain only ASCII letters, digits, '.', '_', '-', or '/'" + )); + } + if !middleware_names.insert(manifest.name.clone()) { + return Err(miette!( + "duplicate supervisor middleware name '{}'", + manifest.name + )); + } + validate_manifest_bindings(&source, &manifest, None)?; + let attachment_name = manifest.name.clone(); + let manifest_cell = OnceCell::new(); + manifest_cell + .set(manifest) + .map_err(|_| miette!("middleware manifest cache initialized twice"))?; + services.push(Arc::new(MiddlewareServiceState { + attachment_name: Some(attachment_name), + service, + manifest: manifest_cell, + diagnostic_policy: MiddlewareDiagnosticPolicy::Preserve, + operator_max_body_bytes: None, + operator_timeout: DEFAULT_MIDDLEWARE_TIMEOUT, + })); + } + + for registration in registrations { + let operator_timeout = validate_registration(®istration)?; + if !middleware_names.insert(registration.name.clone()) { + return Err(miette!( + "duplicate supervisor middleware registration name '{}'", + registration.name + )); + } + + let operator_max_body_bytes = + usize::try_from(registration.max_body_bytes).map_err(|_| { + miette!( + "middleware registration '{}' body limit is too large for this platform", + registration.name + ) + })?; + let service = Arc::new( + remote::RemoteMiddlewareService::connect( + ®istration.name, + ®istration.grpc_endpoint, + ) + .await?, + ); + let manifest = call_with_timeout( + operator_timeout, + "Describe", + service.describe(Request::new(())), + ) + .await + .map(tonic::Response::into_inner) + .map_err(|error| { + miette!( + "middleware registration '{}' Describe failed: {}", + registration.name, + safe_reason(&error.to_string()) + ) + })?; + validate_external_manifest(®istration, &manifest, operator_max_body_bytes)?; + let manifest_cell = OnceCell::new(); + manifest_cell + .set(manifest) + .map_err(|_| miette!("middleware manifest cache initialized twice"))?; + services.push(Arc::new(MiddlewareServiceState { + attachment_name: Some(registration.name.clone()), + service, + manifest: manifest_cell, + diagnostic_policy: MiddlewareDiagnosticPolicy::Normalize, + operator_max_body_bytes: Some(operator_max_body_bytes), + operator_timeout, + })); + registered_services.push(RegisteredMiddlewareService { registration }); + } + + Ok(Self { + services: Arc::new(services), + registered_services: Arc::new(registered_services), + middleware_names: Arc::new(middleware_names), + }) + } + + /// Validate implementation-owned configuration for every middleware entry. + pub async fn validate_policy_configs(&self, policy: &SandboxPolicy) -> Result<()> { + ensure_config_capacity(policy.network_middlewares.len())?; + let runner = ChainRunner::from_registry(self.clone()); + for (name, config) in &policy.network_middlewares { + runner + .validate_config( + &config.middleware, + config.config.clone().unwrap_or_default(), + ) + .await + .map_err(|error| { + miette!( + "middleware config '{}' is invalid: {}", + name, + safe_reason(&error.to_string()) + ) + })?; + } + Ok(()) + } + + /// Check that every policy attachment still belongs to the current static + /// registry without making a network call. + pub fn ensure_policy_middlewares_registered(&self, policy: &SandboxPolicy) -> Result<()> { + for (name, config) in &policy.network_middlewares { + if !self.middleware_names.contains(&config.middleware) { + return Err(miette!( + "middleware '{}' used by config '{}' is not registered", + config.middleware, + name + )); + } + } + Ok(()) + } + + /// Return only operator-registered services referenced by the effective policy. + pub fn required_services( + &self, + policy: Option<&SandboxPolicy>, + ) -> Vec { + let Some(policy) = policy else { + return Vec::new(); + }; + let selected: HashSet<&str> = policy + .network_middlewares + .values() + .map(|config| config.middleware.as_str()) + .collect(); + self.registered_services + .iter() + .filter(|service| selected.contains(service.registration.name.as_str())) + .map(|service| service.registration.clone()) + .collect() + } +} + +impl Default for ChainRunner { + fn default() -> Self { + Self::from_registry(MiddlewareRegistry::default()) + } +} + +impl ChainRunner { + pub fn new(service: Arc) -> Self { + Self { + registry: Arc::new(MiddlewareRegistry { + services: Arc::new(vec![Arc::new(MiddlewareServiceState { + attachment_name: None, + service, + manifest: OnceCell::new(), + diagnostic_policy: MiddlewareDiagnosticPolicy::Preserve, + operator_max_body_bytes: None, + operator_timeout: DEFAULT_MIDDLEWARE_TIMEOUT, + })]), + registered_services: Arc::new(Vec::new()), + middleware_names: Arc::new(HashSet::new()), + }), + } + } + + pub fn from_registry(registry: MiddlewareRegistry) -> Self { + Self { + registry: Arc::new(registry), + } + } + + async fn manifests(&self) -> Result, MiddlewareManifest)>> { + let mut manifests = Vec::with_capacity(self.registry.services.len()); + for state in self.registry.services.iter() { + let manifest = state + .manifest + .get_or_try_init(|| async { + call_with_timeout( + state.operator_timeout, + "Describe", + state.service.describe(Request::new(())), + ) + .await + .map(tonic::Response::into_inner) + .map_err(|error| { + miette!( + "middleware Describe failed: {}", + safe_reason(&error.to_string()) + ) + }) + }) + .await?; + manifests.push((Arc::clone(state), manifest.clone())); + } + Ok(manifests) + } + + fn attachment_name<'a>( + state: &'a MiddlewareServiceState, + manifest: &'a MiddlewareManifest, + ) -> &'a str { + state + .attachment_name + .as_deref() + .unwrap_or(manifest.name.as_str()) + } + + fn http_pre_credentials_binding(manifest: &MiddlewareManifest) -> Option<&MiddlewareBinding> { + manifest.bindings.iter().find(|binding| { + binding.operation == HTTP_REQUEST_OPERATION as i32 + && binding.phase == PRE_CREDENTIALS_PHASE as i32 + }) + } + + pub async fn describe_chain(&self, entries: &[ChainEntry]) -> Result> { + ensure_chain_capacity(entries.len())?; + let manifests = self.manifests().await?; + let mut entries = entries.to_vec(); + sort_chain_entries(&mut entries); + entries + .iter() + .map(|entry| { + let described = manifests + .iter() + .find(|(state, manifest)| { + Self::attachment_name(state, manifest) == entry.implementation + }) + .and_then(|(state, manifest)| { + Self::http_pre_credentials_binding(manifest) + .cloned() + .map(|binding| (Arc::clone(state), binding)) + }); + let (service, binding) = described.map_or((None, None), |(service, binding)| { + (Some(service), Some(binding)) + }); + let max_body_bytes = binding + .as_ref() + .map(|binding| { + let advertised = validate_body_limit("middleware manifest", binding)?; + Ok::<_, miette::Report>( + service + .as_ref() + .and_then(|state| state.operator_max_body_bytes) + .unwrap_or(advertised), + ) + }) + .transpose()? + .unwrap_or(0); + let timeout = service + .as_ref() + .zip(binding.as_ref()) + .map(|(state, binding)| state.timeout_for_binding(binding)) + .transpose()? + .unwrap_or(DEFAULT_MIDDLEWARE_TIMEOUT); + Ok(DescribedChainEntry { + entry: entry.clone(), + service, + binding, + max_body_bytes, + timeout, + }) + }) + .collect() + } + + pub async fn validate_config( + &self, + middleware_name: &str, + config: prost_types::Struct, + ) -> Result<()> { + if config.encoded_len() > MAX_MIDDLEWARE_CONFIG_BYTES { + return Err(miette!( + "middleware config exceeds the platform maximum of {MAX_MIDDLEWARE_CONFIG_BYTES} encoded bytes" + )); + } + let manifests = self.manifests().await?; + let Some((state, binding)) = manifests.iter().find_map(|(state, manifest)| { + (Self::attachment_name(state, manifest) == middleware_name) + .then(|| Self::http_pre_credentials_binding(manifest)) + .flatten() + .map(|binding| (state, binding)) + }) else { + return Err(miette!("middleware '{middleware_name}' is not registered")); + }; + let response = call_with_timeout( + state.timeout_for_binding(binding)?, + "ValidateConfig", + state + .service + .validate_config(Request::new(ValidateConfigRequest { + config: Some(config), + middleware_name: middleware_name.into(), + })), + ) + .await + .map(tonic::Response::into_inner) + .map_err(|error| { + miette!( + "middleware ValidateConfig failed: {}", + safe_reason(&error.to_string()) + ) + })?; + if response.valid { + Ok(()) + } else { + Err(miette!("{}", safe_reason(&response.reason))) + } + } + + pub async fn evaluate( + &self, + entries: &[ChainEntry], + input: HttpRequestInput, + ) -> Result { + let entries = self.describe_chain(entries).await?; + self.evaluate_described(&entries, input).await + } + + pub async fn evaluate_described( + &self, + entries: &[DescribedChainEntry], + input: HttpRequestInput, + ) -> Result { + self.evaluate_described_with_policy( + entries, + input, + TransformedBodyPolicy::NotPolicyRelevant, + ) + .await + } + + /// Evaluate a described chain, re-checking the request body against sandbox + /// policy after every stage that replaces it. Policy runs on the original + /// body before the chain, so without this a stage could hand the next stage + /// (or the upstream) a payload the policy rejects. When the evaluator returns + /// a deny reason the chain stops with that reason, so no later stage ever + /// sees a non-compliant body. Body-independent protocols must select + /// [`TransformedBodyPolicy::NotPolicyRelevant`] explicitly. + pub async fn evaluate_described_with_policy( + &self, + entries: &[DescribedChainEntry], + input: HttpRequestInput, + transformed_body_policy: TransformedBodyPolicy<'_>, + ) -> Result { + ensure_chain_capacity(entries.len())?; + let mut headers = input.headers.clone(); + let mut body = input.body.clone(); + let mut header_mutations = Vec::new(); + let mut findings = Vec::new(); + let mut metadata = BTreeMap::new(); + let mut applied = Vec::new(); + + for entry in entries { + let Some(binding) = entry.binding.as_ref() else { + match apply_on_error(entry, "binding_not_described", &mut applied) { + OnErrorAction::FailOpen => continue, + OnErrorAction::FailClosed(reason) => { + return Ok(ChainOutcome { + allowed: false, + reason, + body, + header_mutations, + findings, + metadata, + applied, + denial: None, + }); + } + } + }; + if body.len() > entry.max_body_bytes { + match apply_on_error(entry, "request_body_over_capacity", &mut applied) { + OnErrorAction::FailOpen => continue, + OnErrorAction::FailClosed(reason) => { + return Ok(ChainOutcome { + allowed: false, + reason, + body, + header_mutations, + findings, + metadata, + applied, + denial: None, + }); + } + } + } + let evaluation = build_evaluation(entry, binding, &input, &headers, &body); + if let Err(reason) = validate_request_envelope(&evaluation) { + match apply_on_error(entry, reason, &mut applied) { + OnErrorAction::FailOpen => continue, + OnErrorAction::FailClosed(reason) => { + return Ok(ChainOutcome { + allowed: false, + reason, + body, + header_mutations, + findings, + metadata, + applied, + denial: None, + }); + } + } + } + let Some(service) = entry.service.as_ref() else { + unreachable!("described binding always has a service") + }; + let mut result = match call_with_timeout( + entry.timeout, + "EvaluateHttpRequest", + service + .service + .evaluate_http_request(Request::new(evaluation)), + ) + .await + { + Ok(result) => result.into_inner(), + Err(err) => { + let reason = if err.code() == tonic::Code::DeadlineExceeded { + "middleware_timeout".to_string() + } else { + service.diagnostic_policy.error_reason(&err) + }; + match apply_on_error(entry, &reason, &mut applied) { + OnErrorAction::FailOpen => continue, + OnErrorAction::FailClosed(reason) => { + return Ok(ChainOutcome { + allowed: false, + reason, + body, + header_mutations, + findings, + metadata, + applied, + denial: None, + }); + } + } + } + }; + + if let Err(reason) = validate_response_envelope(&result) { + match apply_on_error(entry, reason, &mut applied) { + OnErrorAction::FailOpen => continue, + OnErrorAction::FailClosed(reason) => { + return Ok(ChainOutcome { + allowed: false, + reason, + body, + header_mutations, + findings, + metadata, + applied, + denial: None, + }); + } + } + } + + service + .diagnostic_policy + .process_result(&entry.entry.implementation, &mut result); + + let decision = match Decision::try_from(result.decision) { + Ok(decision @ (Decision::Allow | Decision::Deny)) => decision, + Ok(Decision::Unspecified) | Err(_) => { + match apply_on_error(entry, "invalid_response_decision", &mut applied) { + OnErrorAction::FailOpen => continue, + OnErrorAction::FailClosed(reason) => { + return Ok(ChainOutcome { + allowed: false, + reason, + body, + header_mutations, + findings, + metadata, + applied, + denial: None, + }); + } + } + } + }; + + if decision == Decision::Deny { + let reason_code = + (!result.reason_code.is_empty()).then(|| result.reason_code.clone()); + let denial = MiddlewareDenial { + config_name: entry.entry.name.clone(), + reason_code, + }; + for finding in result.findings { + findings.push(NamespacedFinding { + middleware: entry.entry.name.clone(), + finding, + }); + } + if !result.metadata.is_empty() { + metadata.insert( + entry.entry.name.clone(), + result.metadata.into_iter().collect(), + ); + } + applied.push(MiddlewareInvocation { + name: entry.entry.name.clone(), + implementation: entry.entry.implementation.clone(), + decision, + transformed: false, + failed: false, + }); + return Ok(ChainOutcome { + allowed: false, + reason: middleware_denial_reason( + &denial.config_name, + denial.reason_code.as_deref(), + ), + body, + header_mutations, + findings, + metadata, + applied, + denial: Some(denial), + }); + } + + if result.has_body && result.body.len() > entry.max_body_bytes { + match apply_on_error(entry, "response_body_over_capacity", &mut applied) { + OnErrorAction::FailOpen => continue, + OnErrorAction::FailClosed(reason) => { + return Ok(ChainOutcome { + allowed: false, + reason, + body, + header_mutations, + findings, + metadata, + applied, + denial: None, + }); + } + } + } + + // Validate and apply the entire stage atomically. Under fail-open, + // one malformed mutation must not leave earlier mutations from the + // same response visible to later middleware. + let updated_headers = match headers::apply( + &headers, + &input.connection_nominated_headers, + &result.header_mutations, + ) { + Ok(updated) => updated, + Err(error) => { + let reason = service + .diagnostic_policy + .header_mutation_error_reason(&error); + match apply_on_error(entry, &reason, &mut applied) { + OnErrorAction::FailOpen => continue, + OnErrorAction::FailClosed(reason) => { + return Ok(ChainOutcome { + allowed: false, + reason, + body, + header_mutations, + findings, + metadata, + applied, + denial: None, + }); + } + } + } + }; + let headers_transformed = updated_headers != headers; + headers = updated_headers; + header_mutations.extend(result.header_mutations.iter().cloned()); + + let body_transformed = result.has_body; + if body_transformed { + result.body.clone_into(&mut body); + } + for finding in result.findings { + findings.push(NamespacedFinding { + middleware: entry.entry.name.clone(), + finding, + }); + } + if !result.metadata.is_empty() { + metadata.insert( + entry.entry.name.clone(), + result.metadata.clone().into_iter().collect(), + ); + } + applied.push(MiddlewareInvocation { + name: entry.entry.name.clone(), + implementation: entry.entry.implementation.clone(), + decision, + transformed: body_transformed || headers_transformed, + failed: false, + }); + + // The stage ran successfully but its output must still satisfy the + // sandbox policy the original body was admitted under. Re-check now, + // before the next stage or the upstream sees the replaced body. A + // policy deny here is a hard deny, independent of `on_error`. + if body_transformed + && let TransformedBodyPolicy::Reevaluate(validate) = transformed_body_policy + { + let denied = match validate(&body) { + Ok(reason) => reason, + Err(error) => Some(format!( + "transformed_body_policy_evaluation_failed: {}", + safe_reason(&error.to_string()) + )), + }; + if let Some(reason) = denied { + return Ok(ChainOutcome { + allowed: false, + reason, + body, + header_mutations, + findings, + metadata, + applied, + denial: None, + }); + } + } + } + + Ok(ChainOutcome { + allowed: true, + reason: String::new(), + body, + header_mutations, + findings, + metadata, + applied, + denial: None, + }) + } +} + +/// Sort middleware by policy-defined priority. Valid policies have unique order +/// values; the name comparison only keeps direct internal callers deterministic. +pub fn sort_chain_entries(entries: &mut [ChainEntry]) { + entries.sort_by(|left, right| { + left.order + .cmp(&right.order) + .then_with(|| left.name.cmp(&right.name)) + }); +} + +fn ensure_config_capacity(count: usize) -> Result<()> { + if count > MAX_MIDDLEWARE_CONFIGS { + return Err(miette!( + "middleware config count {count} exceeds platform maximum {MAX_MIDDLEWARE_CONFIGS}" + )); + } + Ok(()) +} + +fn ensure_chain_capacity(count: usize) -> Result<()> { + if count > MAX_MIDDLEWARE_CHAIN_STAGES { + return Err(miette!( + "selected middleware stage count {count} exceeds platform maximum {MAX_MIDDLEWARE_CHAIN_STAGES}" + )); + } + Ok(()) +} + +fn build_evaluation( + entry: &DescribedChainEntry, + binding: &MiddlewareBinding, + input: &HttpRequestInput, + headers: &[(String, String)], + body: &[u8], +) -> HttpRequestEvaluation { + HttpRequestEvaluation { + phase: binding.phase, + context: Some(RequestContext { + request_id: input.request_id.clone(), + sandbox_id: input.sandbox_id.clone(), + originating_process: None, + }), + config: Some(entry.entry.config.clone()), + target: Some(HttpRequestTarget { + scheme: input.scheme.clone(), + host: input.host.clone(), + port: u32::from(input.port), + method: input.method.clone(), + path: input.path.clone(), + query: input.query.clone(), + }), + headers: headers + .iter() + .map(|(name, value)| HttpHeader { + name: name.clone(), + value: value.clone(), + }) + .collect(), + body: body.to_vec(), + middleware_name: entry.entry.implementation.clone(), + } +} + +pub(crate) fn safe_reason(reason: &str) -> String { + reason + .chars() + .filter(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '_' | '-' | ':' | ' ')) + .take(160) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + use openshell_core::proto::middleware::v1::supervisor_middleware_server::{ + SupervisorMiddleware, SupervisorMiddlewareServer, + }; + use openshell_core::proto::{ExistingHeaderAction, header_mutation}; + use openshell_supervisor_middleware_builtins::{BUILTIN_REGEX, services}; + use tokio_stream::wrappers::TcpListenerStream; + + fn builtin_runner() -> ChainRunner { + ChainRunner::new( + services() + .into_iter() + .next() + .expect("built-in middleware service"), + ) + } + + fn entry(name: &str, on_error: OnError) -> ChainEntry { + ChainEntry { + name: name.into(), + implementation: BUILTIN_REGEX.into(), + order: 0, + config: prost_types::Struct { + fields: std::iter::once(( + "mode".into(), + prost_types::Value { + kind: Some(prost_types::value::Kind::StringValue("redact".into())), + }, + )) + .collect(), + }, + on_error, + } + } + + fn input(body: &str) -> HttpRequestInput { + HttpRequestInput { + request_id: "req".into(), + sandbox_id: "sbx".into(), + scheme: "https".into(), + host: "api.example.com".into(), + port: 443, + method: "POST".into(), + path: "/v1".into(), + query: String::new(), + headers: Vec::new(), + connection_nominated_headers: Vec::new(), + body: body.as_bytes().to_vec(), + } + } + + fn write_header(name: &str, value: &str, on_existing: ExistingHeaderAction) -> HeaderMutation { + HeaderMutation { + operation: Some(header_mutation::Operation::Write( + openshell_core::proto::WriteHeader { + name: name.into(), + value: value.into(), + on_existing: on_existing as i32, + }, + )), + } + } + + #[tokio::test] + async fn phase_one_evaluation_omits_originating_process() { + let entries = builtin_runner() + .describe_chain(&[entry("redact", OnError::FailClosed)]) + .await + .expect("describe chain"); + let entry = &entries[0]; + let binding = entry.binding.as_ref().expect("described binding"); + let input = input("payload"); + let evaluation = build_evaluation(entry, binding, &input, &[], b"payload"); + + assert_eq!( + evaluation.phase, + SupervisorMiddlewarePhase::PreCredentials as i32 + ); + assert!( + evaluation + .context + .expect("request context") + .originating_process + .is_none() + ); + } + + #[tokio::test] + async fn applies_fixed_regex_replacements() { + let outcome = builtin_runner() + .evaluate( + &[entry("redact", OnError::FailClosed)], + input(r#"{"api_key":"sk-1234567890abcdef"}"#), + ) + .await + .expect("evaluate"); + assert!(outcome.allowed); + assert_eq!( + String::from_utf8(outcome.body).expect("utf8"), + r#"{"api_key":"[REDACTED]"}"# + ); + assert_eq!(outcome.findings[0].finding.count, 1); + } + + #[tokio::test] + async fn transformed_body_feeds_next_stage() { + let entries = [ + entry("first", OnError::FailClosed), + entry("second", OnError::FailClosed), + ]; + let outcome = builtin_runner() + .evaluate(&entries, input(r#"token="sk-ABCDEFGHIJKLMNOP""#)) + .await + .expect("evaluate"); + assert!(outcome.allowed); + assert_eq!( + String::from_utf8(outcome.body).expect("utf8"), + r#"token="[REDACTED]""# + ); + assert_eq!(outcome.applied.len(), 2); + } + + #[tokio::test] + async fn describe_chain_sorts_by_order_then_name() { + let mut later = entry("later", OnError::FailClosed); + later.order = 20; + let mut beta = entry("beta", OnError::FailClosed); + beta.order = 10; + let mut alpha = entry("alpha", OnError::FailClosed); + alpha.order = 10; + + let described = builtin_runner() + .describe_chain(&[later, beta, alpha]) + .await + .expect("describe ordered chain"); + let names: Vec<_> = described + .iter() + .map(|entry| entry.entry.name.as_str()) + .collect(); + assert_eq!(names, vec!["alpha", "beta", "later"]); + } + + #[tokio::test] + async fn describe_chain_accepts_maximum_selected_stages() { + let entries: Vec<_> = (0..MAX_MIDDLEWARE_CHAIN_STAGES) + .map(|index| entry(&format!("stage-{index}"), OnError::FailClosed)) + .collect(); + + let described = builtin_runner() + .describe_chain(&entries) + .await + .expect("maximum selected stage count"); + assert_eq!(described.len(), MAX_MIDDLEWARE_CHAIN_STAGES); + } + + #[tokio::test] + async fn describe_chain_rejects_selected_stages_over_capacity() { + let entries: Vec<_> = (0..=MAX_MIDDLEWARE_CHAIN_STAGES) + .map(|index| entry(&format!("stage-{index}"), OnError::FailClosed)) + .collect(); + + let error = builtin_runner() + .describe_chain(&entries) + .await + .err() + .expect("selected stage count over capacity"); + assert!( + error + .to_string() + .contains("selected middleware stage count 11 exceeds platform maximum 10") + ); + } + + #[tokio::test] + async fn fail_open_allows_unavailable_middleware() { + let unavailable = ChainEntry { + name: "missing".into(), + implementation: "third-party/missing".into(), + order: 0, + config: prost_types::Struct::default(), + on_error: OnError::FailOpen, + }; + let outcome = builtin_runner() + .evaluate(&[unavailable], input("hello")) + .await + .expect("evaluate"); + assert!(outcome.allowed); + assert_eq!(outcome.body, b"hello"); + } + + #[tokio::test] + async fn fail_closed_denies_unavailable_middleware() { + let unavailable = ChainEntry { + name: "missing".into(), + implementation: "third-party/missing".into(), + order: 0, + config: prost_types::Struct::default(), + on_error: OnError::FailClosed, + }; + let outcome = builtin_runner() + .evaluate(&[unavailable], input("hello")) + .await + .expect("evaluate"); + assert!(!outcome.allowed); + assert!(outcome.reason.starts_with("middleware_failed:")); + } + + #[tokio::test] + async fn injected_service_names_drive_registration_checks() { + let registry = MiddlewareRegistry::connect_services(services(), Vec::new()) + .await + .expect("connect built-in service"); + let policy = SandboxPolicy { + network_middlewares: HashMap::from([( + "redactor".into(), + NetworkMiddlewareConfig { + middleware: BUILTIN_REGEX.into(), + ..Default::default() + }, + )]), + ..Default::default() + }; + registry + .ensure_policy_middlewares_registered(&policy) + .expect("described middleware is registered"); + } + + #[tokio::test] + async fn injected_services_cannot_duplicate_middleware_names() { + let first: Arc = Arc::new(ScriptedService { + manifest_name: "openshell/test".into(), + max_body_bytes: 1024, + result: allow_result(), + }); + let second: Arc = Arc::new(ScriptedService { + manifest_name: "openshell/test".into(), + max_body_bytes: 1024, + result: allow_result(), + }); + + let error = MiddlewareRegistry::connect_services(vec![first, second], Vec::new()) + .await + .expect_err("duplicate injected middleware name must fail registry construction"); + assert!( + error + .to_string() + .contains("duplicate supervisor middleware name") + ); + } + + /// A mock middleware that returns a fixed, caller-supplied result for every + /// evaluation. Used to exercise chain behavior the built-in cannot produce + /// (explicit deny, metadata, findings, unsafe header mutations). + struct ScriptedService { + manifest_name: String, + max_body_bytes: u64, + result: openshell_core::proto::HttpRequestResult, + } + + #[tonic::async_trait] + impl SupervisorMiddleware for ScriptedService { + async fn describe( + &self, + _request: Request<()>, + ) -> std::result::Result, tonic::Status> { + Ok(tonic::Response::new(MiddlewareManifest { + name: self.manifest_name.clone(), + service_version: "test".into(), + bindings: vec![MiddlewareBinding { + operation: SupervisorMiddlewareOperation::HttpRequest as i32, + phase: SupervisorMiddlewarePhase::PreCredentials as i32, + max_body_bytes: self.max_body_bytes, + timeout: String::new(), + }], + })) + } + + async fn validate_config( + &self, + _request: Request, + ) -> std::result::Result< + tonic::Response, + tonic::Status, + > { + Ok(tonic::Response::new( + openshell_core::proto::ValidateConfigResponse { + valid: true, + reason: String::new(), + }, + )) + } + + async fn evaluate_http_request( + &self, + _request: Request, + ) -> std::result::Result< + tonic::Response, + tonic::Status, + > { + Ok(tonic::Response::new(self.result.clone())) + } + } + + struct SlowService { + delay: Duration, + binding_timeout: String, + } + + #[tonic::async_trait] + impl SupervisorMiddleware for SlowService { + async fn describe( + &self, + _request: Request<()>, + ) -> std::result::Result, tonic::Status> { + Ok(tonic::Response::new(MiddlewareManifest { + name: "test/slow".into(), + service_version: "test".into(), + bindings: vec![MiddlewareBinding { + operation: SupervisorMiddlewareOperation::HttpRequest as i32, + phase: SupervisorMiddlewarePhase::PreCredentials as i32, + max_body_bytes: 4096, + timeout: self.binding_timeout.clone(), + }], + })) + } + + async fn validate_config( + &self, + _request: Request, + ) -> std::result::Result< + tonic::Response, + tonic::Status, + > { + tokio::time::sleep(self.delay).await; + Ok(tonic::Response::new( + openshell_core::proto::ValidateConfigResponse { + valid: true, + reason: String::new(), + }, + )) + } + + async fn evaluate_http_request( + &self, + _request: Request, + ) -> std::result::Result< + tonic::Response, + tonic::Status, + > { + tokio::time::sleep(self.delay).await; + Ok(tonic::Response::new(allow_result())) + } + } + + /// A middleware attached twice for exercising per-stage validation. The + /// first policy config requests a body transformation; the second records + /// that it ran and allows. + struct TwoStageService { + second_ran: Arc, + } + + #[tonic::async_trait] + impl SupervisorMiddleware for TwoStageService { + async fn describe( + &self, + _request: Request<()>, + ) -> std::result::Result, tonic::Status> { + Ok(tonic::Response::new(MiddlewareManifest { + name: "test/two-stage".into(), + service_version: "test".into(), + bindings: vec![MiddlewareBinding { + operation: SupervisorMiddlewareOperation::HttpRequest as i32, + phase: SupervisorMiddlewarePhase::PreCredentials as i32, + max_body_bytes: 256 * 1024, + timeout: String::new(), + }], + })) + } + + async fn validate_config( + &self, + _request: Request, + ) -> std::result::Result< + tonic::Response, + tonic::Status, + > { + Ok(tonic::Response::new( + openshell_core::proto::ValidateConfigResponse { + valid: true, + reason: String::new(), + }, + )) + } + + async fn evaluate_http_request( + &self, + request: Request, + ) -> std::result::Result< + tonic::Response, + tonic::Status, + > { + let evaluation = request.into_inner(); + let mut result = allow_result(); + if evaluation.config.as_ref().is_some_and(|config| { + config.fields.get("transform").is_some_and(|value| { + matches!( + value.kind.as_ref(), + Some(prost_types::value::Kind::BoolValue(true)) + ) + }) + }) { + result.body = b"TRANSFORMED".to_vec(); + result.has_body = true; + } else { + self.second_ran + .store(true, std::sync::atomic::Ordering::SeqCst); + } + Ok(tonic::Response::new(result)) + } + } + + #[tokio::test] + async fn per_stage_validation_denies_before_the_next_stage_runs() { + // The validator rejects the first stage's transformed body. The chain + // must stop there: the second stage never runs, so it never sees a + // payload the policy would reject. + let second_ran = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let service: Arc = Arc::new(TwoStageService { + second_ran: Arc::clone(&second_ran), + }); + let runner = ChainRunner::new(service); + let transform = ChainEntry { + name: "transform".into(), + implementation: "test/two-stage".into(), + order: 0, + config: prost_types::Struct { + fields: std::iter::once(( + "transform".into(), + prost_types::Value { + kind: Some(prost_types::value::Kind::BoolValue(true)), + }, + )) + .collect(), + }, + on_error: OnError::FailClosed, + }; + let second = ChainEntry { + name: "second".into(), + implementation: "test/two-stage".into(), + order: 10, + config: prost_types::Struct::default(), + on_error: OnError::FailClosed, + }; + let described = runner + .describe_chain(&[transform, second]) + .await + .expect("describe two-stage chain"); + + let validator: Box> = Box::new(|body: &[u8]| { + if body == b"TRANSFORMED" { + Ok(Some("transformed body denied by policy".to_string())) + } else { + Ok(None) + } + }); + let outcome = runner + .evaluate_described_with_policy( + &described, + input("original"), + TransformedBodyPolicy::Reevaluate(&*validator), + ) + .await + .expect("evaluate two-stage chain"); + + assert!(!outcome.allowed); + assert_eq!(outcome.reason, "transformed body denied by policy"); + assert_eq!(outcome.applied.len(), 1, "only the first stage should run"); + assert_eq!(outcome.applied[0].name, "transform"); + assert!( + !second_ran.load(std::sync::atomic::Ordering::SeqCst), + "second stage must not run after a policy deny" + ); + } + + #[tokio::test] + async fn per_stage_validator_allows_compliant_transformations() { + // A validator that accepts every body lets both stages run; the second + // stage sees the first stage's output. + let second_ran = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let service: Arc = Arc::new(TwoStageService { + second_ran: Arc::clone(&second_ran), + }); + let runner = ChainRunner::new(service); + let transform = ChainEntry { + name: "transform".into(), + implementation: "test/two-stage".into(), + order: 0, + config: prost_types::Struct { + fields: std::iter::once(( + "transform".into(), + prost_types::Value { + kind: Some(prost_types::value::Kind::BoolValue(true)), + }, + )) + .collect(), + }, + on_error: OnError::FailClosed, + }; + let second = ChainEntry { + name: "second".into(), + implementation: "test/two-stage".into(), + order: 10, + config: prost_types::Struct::default(), + on_error: OnError::FailClosed, + }; + let described = runner + .describe_chain(&[transform, second]) + .await + .expect("describe two-stage chain"); + + let validator: Box> = Box::new(|_body: &[u8]| Ok(None)); + let outcome = runner + .evaluate_described_with_policy( + &described, + input("original"), + TransformedBodyPolicy::Reevaluate(&*validator), + ) + .await + .expect("evaluate two-stage chain"); + + assert!(outcome.allowed); + assert_eq!(outcome.applied.len(), 2); + assert!( + second_ran.load(std::sync::atomic::Ordering::SeqCst), + "second stage should run when the transformation is compliant" + ); + } + + #[tokio::test] + async fn per_stage_validator_error_becomes_structured_denial() { + let second_ran = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let service: Arc = Arc::new(TwoStageService { + second_ran: Arc::clone(&second_ran), + }); + let runner = ChainRunner::new(service); + let entries = [ + ChainEntry { + name: "transform".into(), + implementation: "test/two-stage".into(), + order: 0, + config: prost_types::Struct { + fields: std::iter::once(( + "transform".into(), + prost_types::Value { + kind: Some(prost_types::value::Kind::BoolValue(true)), + }, + )) + .collect(), + }, + on_error: OnError::FailClosed, + }, + ChainEntry { + name: "second".into(), + implementation: "test/two-stage".into(), + order: 10, + config: prost_types::Struct::default(), + on_error: OnError::FailClosed, + }, + ]; + let described = runner + .describe_chain(&entries) + .await + .expect("describe two-stage chain"); + let validator: Box> = + Box::new(|_body: &[u8]| Err(miette!("OPA engine unavailable"))); + + let outcome = runner + .evaluate_described_with_policy( + &described, + input("original"), + TransformedBodyPolicy::Reevaluate(&*validator), + ) + .await + .expect("policy evaluator failure should be a chain outcome"); + + assert!(!outcome.allowed); + assert!( + outcome + .reason + .starts_with("transformed_body_policy_evaluation_failed:"), + "{}", + outcome.reason + ); + assert_eq!(outcome.applied.len(), 1); + assert!(!second_ran.load(std::sync::atomic::Ordering::SeqCst)); + } + + fn scripted_service(result: openshell_core::proto::HttpRequestResult) -> ScriptedService { + ScriptedService { + manifest_name: BUILTIN_REGEX.into(), + max_body_bytes: 256 * 1024, + result, + } + } + + fn allow_result() -> openshell_core::proto::HttpRequestResult { + openshell_core::proto::HttpRequestResult { + decision: Decision::Allow as i32, + reason: String::new(), + body: Vec::new(), + has_body: false, + header_mutations: Vec::new(), + findings: Vec::new(), + metadata: HashMap::new(), + reason_code: String::new(), + } + } + + /// A middleware that records every evaluation it receives and allows the + /// request, for asserting what the supervisor actually sends to services. + struct RecordingService { + validated: std::sync::Mutex>, + received: std::sync::Mutex>, + } + + #[tonic::async_trait] + impl SupervisorMiddleware for RecordingService { + async fn describe( + &self, + _request: Request<()>, + ) -> std::result::Result, tonic::Status> { + Ok(tonic::Response::new(MiddlewareManifest { + name: "test/recorder".into(), + service_version: "test".into(), + bindings: vec![MiddlewareBinding { + operation: SupervisorMiddlewareOperation::HttpRequest as i32, + phase: SupervisorMiddlewarePhase::PreCredentials as i32, + max_body_bytes: 4096, + timeout: String::new(), + }], + })) + } + + async fn validate_config( + &self, + request: Request, + ) -> std::result::Result< + tonic::Response, + tonic::Status, + > { + self.validated + .lock() + .expect("validated config lock") + .push(request.into_inner()); + Ok(tonic::Response::new( + openshell_core::proto::ValidateConfigResponse { + valid: true, + reason: String::new(), + }, + )) + } + + async fn evaluate_http_request( + &self, + request: Request, + ) -> std::result::Result< + tonic::Response, + tonic::Status, + > { + self.received + .lock() + .expect("recording lock") + .push(request.into_inner()); + Ok(tonic::Response::new(allow_result())) + } + } + + /// Three-stage service used to verify that each stage observes the header + /// state produced by all preceding stages. + struct HeaderChainService { + second_action: ExistingHeaderAction, + received: std::sync::Mutex>, + } + + #[tonic::async_trait] + impl SupervisorMiddleware for HeaderChainService { + async fn describe( + &self, + _request: Request<()>, + ) -> std::result::Result, tonic::Status> { + Ok(tonic::Response::new(MiddlewareManifest { + name: "test/header-chain".into(), + service_version: "test".into(), + bindings: vec![MiddlewareBinding { + operation: SupervisorMiddlewareOperation::HttpRequest as i32, + phase: SupervisorMiddlewarePhase::PreCredentials as i32, + max_body_bytes: 4096, + timeout: String::new(), + }], + })) + } + + async fn validate_config( + &self, + _request: Request, + ) -> std::result::Result< + tonic::Response, + tonic::Status, + > { + Ok(tonic::Response::new( + openshell_core::proto::ValidateConfigResponse { + valid: true, + reason: String::new(), + }, + )) + } + + async fn evaluate_http_request( + &self, + request: Request, + ) -> std::result::Result< + tonic::Response, + tonic::Status, + > { + let evaluation = request.into_inner(); + let invocation = { + let mut received = self.received.lock().expect("header chain lock"); + let invocation = received.len(); + received.push(evaluation); + invocation + }; + let mut result = allow_result(); + if invocation == 0 { + result.header_mutations.push(write_header( + "x-openshell-middleware-chain", + "first", + ExistingHeaderAction::Overwrite, + )); + } else if invocation == 1 { + result.header_mutations.push(write_header( + "x-openshell-middleware-chain", + "second", + self.second_action, + )); + } + Ok(tonic::Response::new(result)) + } + } + + #[tokio::test] + async fn later_middleware_observes_prior_header_mutations() { + for (action, expected) in [ + (ExistingHeaderAction::Append, vec!["first", "second"]), + (ExistingHeaderAction::Overwrite, vec!["second"]), + (ExistingHeaderAction::Skip, vec!["first"]), + ] { + let service = Arc::new(HeaderChainService { + second_action: action, + received: std::sync::Mutex::new(Vec::new()), + }); + let runner = ChainRunner::new(service.clone()); + let entries = [ + ChainEntry { + name: "first".into(), + implementation: "test/header-chain".into(), + order: 0, + config: prost_types::Struct::default(), + on_error: OnError::FailClosed, + }, + ChainEntry { + name: "second".into(), + implementation: "test/header-chain".into(), + order: 10, + config: prost_types::Struct::default(), + on_error: OnError::FailClosed, + }, + ChainEntry { + name: "observer".into(), + implementation: "test/header-chain".into(), + order: 20, + config: prost_types::Struct::default(), + on_error: OnError::FailClosed, + }, + ]; + + let outcome = runner + .evaluate(&entries, input("payload")) + .await + .expect("evaluate header chain"); + assert!(outcome.allowed); + let received = service.received.lock().expect("recorded header chain"); + let observed: Vec<&str> = received[2] + .headers + .iter() + .filter(|header| header.name == "x-openshell-middleware-chain") + .map(|header| header.value.as_str()) + .collect(); + assert_eq!(observed, expected, "action {action:?}"); + } + } + + #[tokio::test] + async fn repeated_request_headers_reach_middleware_in_wire_order() { + // A map contract would collapse repeated header names to one value + // while the upstream still receives every original value, creating an + // inspection differential. The service must see each entry in wire + // order. + let service = Arc::new(RecordingService { + validated: std::sync::Mutex::new(Vec::new()), + received: std::sync::Mutex::new(Vec::new()), + }); + let recorder: Arc = service.clone(); + let runner = ChainRunner::new(recorder); + runner + .validate_config("test/recorder", prost_types::Struct::default()) + .await + .expect("validate recorder config"); + let recorder_entry = ChainEntry { + name: "recorder".into(), + implementation: "test/recorder".into(), + order: 0, + config: prost_types::Struct::default(), + on_error: OnError::FailClosed, + }; + let mut request = input("payload"); + request.headers = vec![ + ("x-api-key".into(), "first-value".into()), + ("accept".into(), "application/json".into()), + ("x-api-key".into(), "second-value".into()), + ]; + + let outcome = runner + .evaluate(&[recorder_entry], request) + .await + .expect("evaluate recording chain"); + assert!(outcome.allowed); + + let validated = service.validated.lock().expect("validated configs"); + assert_eq!(validated.len(), 1); + assert_eq!(validated[0].middleware_name, "test/recorder"); + drop(validated); + + let received = service.received.lock().expect("recorded evaluations"); + assert_eq!(received.len(), 1); + assert_eq!(received[0].middleware_name, "test/recorder"); + let headers: Vec<(&str, &str)> = received[0] + .headers + .iter() + .map(|header| (header.name.as_str(), header.value.as_str())) + .collect(); + assert_eq!( + headers, + vec![ + ("x-api-key", "first-value"), + ("accept", "application/json"), + ("x-api-key", "second-value"), + ] + ); + } + + fn external_registration(max_body_bytes: u64) -> SupervisorMiddlewareService { + SupervisorMiddlewareService { + name: "local-guard-service".into(), + grpc_endpoint: "http://127.0.0.1:50051".into(), + max_body_bytes, + ..Default::default() + } + } + + async fn registry_with_external( + service: Arc, + registration: SupervisorMiddlewareService, + ) -> MiddlewareRegistry { + let builtin_service = services() + .into_iter() + .next() + .expect("built-in middleware service"); + let builtin_manifest = builtin_service + .describe(Request::new(())) + .await + .expect("describe built-in service") + .into_inner(); + validate_manifest_bindings("test built-in service", &builtin_manifest, None) + .expect("valid built-in manifest"); + let builtin_name = builtin_manifest.name.clone(); + let builtin_manifest_cell = OnceCell::new(); + builtin_manifest_cell + .set(builtin_manifest) + .expect("built-in manifest cache"); + + let manifest = service + .describe(Request::new(())) + .await + .expect("describe test service") + .into_inner(); + let operator_max_body_bytes = usize::try_from(registration.max_body_bytes).unwrap(); + let operator_timeout = validate_registration(®istration).expect("valid registration"); + validate_external_manifest(®istration, &manifest, operator_max_body_bytes) + .expect("valid external manifest"); + let manifest_cell = OnceCell::new(); + manifest_cell.set(manifest).expect("manifest cache"); + let registration_name = registration.name.clone(); + MiddlewareRegistry { + services: Arc::new(vec![ + Arc::new(MiddlewareServiceState { + attachment_name: Some(builtin_name.clone()), + service: builtin_service, + manifest: builtin_manifest_cell, + diagnostic_policy: MiddlewareDiagnosticPolicy::Preserve, + operator_max_body_bytes: None, + operator_timeout: DEFAULT_MIDDLEWARE_TIMEOUT, + }), + Arc::new(MiddlewareServiceState { + attachment_name: Some(registration_name.clone()), + service, + manifest: manifest_cell, + diagnostic_policy: MiddlewareDiagnosticPolicy::Normalize, + operator_max_body_bytes: Some(operator_max_body_bytes), + operator_timeout, + }), + ]), + registered_services: Arc::new(vec![RegisteredMiddlewareService { registration }]), + middleware_names: Arc::new(HashSet::from([builtin_name, registration_name])), + } + } + + #[tokio::test] + async fn describe_chain_marks_resolved_and_unresolved_entries() { + let unresolved = ChainEntry { + name: "missing".into(), + implementation: "third-party/missing".into(), + order: 10, + config: prost_types::Struct::default(), + on_error: OnError::FailOpen, + }; + let described = builtin_runner() + .describe_chain(&[entry("redact", OnError::FailClosed), unresolved]) + .await + .expect("describe chain"); + // The built-in resolves and reports its real limit; the missing binding + // does not resolve and must not contribute a body limit. + assert!(described[0].is_resolved()); + assert_eq!(described[0].max_body_bytes(), 256 * 1024); + assert!(!described[1].is_resolved()); + } + + #[tokio::test] + async fn descriptors_are_resolved_from_any_middleware_service() { + let runner = ChainRunner::new(Arc::new(ScriptedService { + manifest_name: "test/middleware".into(), + max_body_bytes: 4096, + result: allow_result(), + })); + let entry = ChainEntry { + name: "external".into(), + implementation: "test/middleware".into(), + order: 0, + config: prost_types::Struct::default(), + on_error: OnError::FailClosed, + }; + + let described = runner + .describe_chain(std::slice::from_ref(&entry)) + .await + .expect("describe external middleware"); + assert_eq!(described[0].max_body_bytes(), 4096); + assert_eq!( + described[0] + .binding + .as_ref() + .expect("described binding") + .phase, + SupervisorMiddlewarePhase::PreCredentials as i32 + ); + + let outcome = runner + .evaluate_described(&described, input("hello")) + .await + .expect("evaluate external middleware"); + assert!(outcome.allowed); + } + + #[tokio::test] + async fn mixed_builtin_and_external_chain_uses_operator_limit() { + let external = Arc::new(ScriptedService { + manifest_name: "test/middleware".into(), + max_body_bytes: 4096, + result: allow_result(), + }); + let registry = registry_with_external(external, external_registration(1024)).await; + let runner = ChainRunner::from_registry(registry); + let external_entry = ChainEntry { + name: "external".into(), + implementation: "local-guard-service".into(), + order: 0, + config: prost_types::Struct::default(), + on_error: OnError::FailClosed, + }; + let entries = [entry("builtin", OnError::FailClosed), external_entry]; + + let described = runner + .describe_chain(&entries) + .await + .expect("describe chain"); + assert_eq!(described[0].max_body_bytes(), 256 * 1024); + assert_eq!(described[1].max_body_bytes(), 1024); + + let outcome = runner + .evaluate_described(&described, input(r#"token="sk-ABCDEFGHIJKLMNOP""#)) + .await + .expect("evaluate mixed chain"); + assert!(outcome.allowed); + assert_eq!(outcome.applied.len(), 2); + assert_eq!( + String::from_utf8(outcome.body).expect("utf8"), + r#"token="[REDACTED]""# + ); + } + + #[tokio::test] + async fn undersized_stage_fails_open_while_later_stage_runs() { + // A body over one stage's limit must fail only that stage through its + // own `on_error`, not the whole chain: the 1 KiB fail-open guard is + // skipped while the 256 KiB fail-closed redactor still runs. + let external = Arc::new(ScriptedService { + manifest_name: "test/middleware".into(), + max_body_bytes: 4096, + result: allow_result(), + }); + let registry = registry_with_external(external, external_registration(1024)).await; + let runner = ChainRunner::from_registry(registry); + let guard_entry = ChainEntry { + name: "guard".into(), + implementation: "local-guard-service".into(), + order: 0, + config: prost_types::Struct::default(), + on_error: OnError::FailOpen, + }; + let mut redact_entry = entry("redact", OnError::FailClosed); + redact_entry.order = 10; + let entries = [guard_entry, redact_entry]; + + let body = format!("{}token=\"sk-ABCDEFGHIJKLMNOP\"", "x".repeat(1500)); + let outcome = runner + .evaluate(&entries, input(&body)) + .await + .expect("evaluate mixed-limit chain"); + + assert!(outcome.allowed); + assert_eq!(outcome.applied.len(), 2); + assert!( + outcome.applied[0].failed, + "undersized guard must be skipped" + ); + assert_eq!(outcome.applied[0].decision, Decision::Allow); + assert!(!outcome.applied[1].failed); + assert!(outcome.applied[1].transformed); + let body = String::from_utf8(outcome.body).expect("utf8"); + assert!(body.contains("[REDACTED]")); + assert!(!body.contains("sk-ABCDEFGHIJKLMNOP")); + } + + #[tokio::test] + async fn transformed_body_still_over_later_stage_capacity_honors_on_error() { + // Per-stage capacity applies to the current body: the redactor's + // replacement is still over the 1 KiB guard limit, so the fail-closed + // guard denies through its own `on_error` after the redactor ran. + let external = Arc::new(ScriptedService { + manifest_name: "test/middleware".into(), + max_body_bytes: 4096, + result: allow_result(), + }); + let registry = registry_with_external(external, external_registration(1024)).await; + let runner = ChainRunner::from_registry(registry); + let guard_entry = ChainEntry { + name: "guard".into(), + implementation: "local-guard-service".into(), + order: 10, + config: prost_types::Struct::default(), + on_error: OnError::FailClosed, + }; + let entries = [entry("redact", OnError::FailClosed), guard_entry]; + + let body = format!("{}token=\"sk-ABCDEFGHIJKLMNOP\"", "x".repeat(1500)); + let outcome = runner + .evaluate(&entries, input(&body)) + .await + .expect("evaluate mixed-limit chain"); + + assert!(!outcome.allowed); + assert_eq!( + outcome.reason, + "middleware_failed: request_body_over_capacity" + ); + assert_eq!(outcome.applied.len(), 2); + assert!( + outcome.applied[0].transformed, + "redactor ran before the deny" + ); + assert!(outcome.applied[1].failed); + } + + #[test] + fn external_manifest_rejects_operator_limit_above_capability() { + let registration = external_registration(4097); + let manifest = MiddlewareManifest { + name: "example/service".into(), + service_version: "test".into(), + bindings: vec![MiddlewareBinding { + operation: HTTP_REQUEST_OPERATION as i32, + phase: PRE_CREDENTIALS_PHASE as i32, + max_body_bytes: 4096, + timeout: String::new(), + }], + }; + let error = validate_external_manifest(®istration, &manifest, 4097) + .expect_err("operator limit must fit capability"); + assert!(error.to_string().contains("exceeds")); + } + + #[test] + fn external_registration_rejects_body_limit_above_platform_maximum() { + let registration = external_registration(u64::MAX); + let error = validate_registration(®istration) + .expect_err("extreme body limit must be rejected before allocation"); + assert!(error.to_string().contains("platform maximum")); + } + + #[test] + fn manifest_rejects_body_limit_above_platform_maximum() { + let registration = external_registration(4096); + let manifest = MiddlewareManifest { + name: "example/service".into(), + service_version: "test".into(), + bindings: vec![MiddlewareBinding { + operation: HTTP_REQUEST_OPERATION as i32, + phase: PRE_CREDENTIALS_PHASE as i32, + max_body_bytes: u64::MAX, + timeout: String::new(), + }], + }; + let error = validate_external_manifest(®istration, &manifest, 4096) + .expect_err("extreme advertised body limit must be rejected"); + assert!(error.to_string().contains("platform maximum")); + } + + #[test] + fn manifest_rejects_duplicate_operation_phase_pairs() { + let registration = external_registration(4096); + let binding = || MiddlewareBinding { + operation: HTTP_REQUEST_OPERATION as i32, + phase: PRE_CREDENTIALS_PHASE as i32, + max_body_bytes: 4096, + timeout: String::new(), + }; + let manifest = MiddlewareManifest { + name: "example/service".into(), + service_version: "test".into(), + bindings: vec![binding(), binding()], + }; + + let error = validate_external_manifest(®istration, &manifest, 4096) + .expect_err("one service cannot advertise two bindings for the same pair"); + assert!( + error + .to_string() + .contains("more than one binding for HTTP_REQUEST/PRE_CREDENTIALS") + ); + } + + #[test] + fn external_registration_accepts_http_and_https_grpc_endpoints() { + for grpc_endpoint in [ + "http://127.0.0.1:50051", + "https://middleware.example.com:443", + ] { + let mut registration = external_registration(4096); + registration.grpc_endpoint = grpc_endpoint.into(); + validate_registration(®istration).expect("supported gRPC endpoint scheme"); + } + } + + #[test] + fn external_registration_rejects_unsupported_grpc_endpoint_scheme() { + let mut registration = external_registration(4096); + registration.grpc_endpoint = "ftp://middleware.example.com".into(); + let error = validate_registration(®istration).expect_err("unsupported scheme"); + assert!(error.to_string().contains("http:// or https://")); + } + + #[test] + fn external_registration_name_is_stable_and_cannot_shadow_builtins() { + for name in ["", "guard\nforged", "openshell/regex"] { + let mut registration = external_registration(4096); + registration.name = name.into(); + assert!( + validate_registration(®istration).is_err(), + "registration name {name:?} must be rejected" + ); + } + } + + #[test] + fn registration_timeout_uses_default_and_operator_override() { + let registration = external_registration(4096); + let timeout = validate_registration(®istration).expect("default timeout"); + assert_eq!(timeout, DEFAULT_MIDDLEWARE_TIMEOUT); + + let mut registration = external_registration(4096); + registration.timeout = "2s".into(); + let timeout = validate_registration(®istration).expect("operator timeout"); + assert_eq!(timeout, Duration::from_secs(2)); + } + + #[test] + fn registration_timeout_enforces_bounds() { + for timeout in ["9ms", "31s"] { + let mut registration = external_registration(4096); + registration.timeout = timeout.into(); + assert!(validate_registration(®istration).is_err()); + } + } + + #[test] + fn manifest_binding_timeout_enforces_bounds() { + let registration = external_registration(4096); + for timeout in ["9ms", "31s"] { + let manifest = MiddlewareManifest { + name: "example/service".into(), + service_version: "test".into(), + bindings: vec![MiddlewareBinding { + operation: HTTP_REQUEST_OPERATION as i32, + phase: PRE_CREDENTIALS_PHASE as i32, + max_body_bytes: 4096, + timeout: timeout.into(), + }], + }; + let error = validate_external_manifest(®istration, &manifest, 4096) + .expect_err("out-of-bounds binding timeout must be rejected"); + assert!(error.to_string().contains("invalid timeout")); + } + } + + #[tokio::test] + async fn binding_timeout_override_controls_evaluation_and_on_error() { + let mut registration = external_registration(4096); + registration.timeout = "2s".into(); + let registry = registry_with_external( + Arc::new(SlowService { + delay: Duration::from_millis(50), + binding_timeout: "10ms".into(), + }), + registration, + ) + .await; + let runner = ChainRunner::from_registry(registry); + let slow_entry = |on_error| ChainEntry { + name: "slow".into(), + implementation: "local-guard-service".into(), + order: 0, + config: prost_types::Struct::default(), + on_error, + }; + + let described = runner + .describe_chain(&[slow_entry(OnError::FailClosed)]) + .await + .expect("describe slow binding"); + assert_eq!(described[0].timeout(), Duration::from_millis(10)); + + let closed = runner + .evaluate(&[slow_entry(OnError::FailClosed)], input("payload")) + .await + .expect("fail-closed timeout outcome"); + assert!(!closed.allowed); + assert_eq!(closed.reason, "middleware_failed: middleware_timeout"); + + let open = runner + .evaluate(&[slow_entry(OnError::FailOpen)], input("payload")) + .await + .expect("fail-open timeout outcome"); + assert!(open.allowed); + assert!(open.applied[0].failed); + } + + #[tokio::test] + async fn operator_timeout_controls_binding_without_manifest_override() { + let mut registration = external_registration(4096); + registration.timeout = "10ms".into(); + let registry = registry_with_external( + Arc::new(SlowService { + delay: Duration::from_millis(50), + binding_timeout: String::new(), + }), + registration, + ) + .await; + let runner = ChainRunner::from_registry(registry); + let slow_entry = ChainEntry { + name: "slow".into(), + implementation: "local-guard-service".into(), + order: 0, + config: prost_types::Struct::default(), + on_error: OnError::FailClosed, + }; + + let described = runner + .describe_chain(std::slice::from_ref(&slow_entry)) + .await + .expect("describe slow binding"); + assert_eq!(described[0].timeout(), Duration::from_millis(10)); + + let outcome = runner + .evaluate(&[slow_entry], input("payload")) + .await + .expect("operator timeout outcome"); + assert!(!outcome.allowed); + assert_eq!(outcome.reason, "middleware_failed: middleware_timeout"); + } + + #[tokio::test] + async fn operator_timeout_caps_longer_binding_timeout_for_validation_and_evaluation() { + let mut registration = external_registration(4096); + registration.timeout = "10ms".into(); + let registry = registry_with_external( + Arc::new(SlowService { + delay: Duration::from_millis(50), + binding_timeout: "2s".into(), + }), + registration, + ) + .await; + let runner = ChainRunner::from_registry(registry); + let slow_entry = ChainEntry { + name: "slow".into(), + implementation: "local-guard-service".into(), + order: 0, + config: prost_types::Struct::default(), + on_error: OnError::FailClosed, + }; + + let described = runner + .describe_chain(std::slice::from_ref(&slow_entry)) + .await + .expect("describe slow binding"); + assert_eq!(described[0].timeout(), Duration::from_millis(10)); + + let validation_error = runner + .validate_config("local-guard-service", prost_types::Struct::default()) + .await + .expect_err("operator timeout must cap ValidateConfig"); + assert!( + validation_error + .to_string() + .contains("ValidateConfig failed") + ); + assert!(validation_error.to_string().contains("timed out")); + + let outcome = runner + .evaluate(&[slow_entry], input("payload")) + .await + .expect("operator-capped evaluation outcome"); + assert!(!outcome.allowed); + assert_eq!(outcome.reason, "middleware_failed: middleware_timeout"); + } + + #[tokio::test] + async fn external_registry_attaches_same_service_under_multiple_names() { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("bind test middleware"); + let address = listener.local_addr().expect("test middleware address"); + let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel(); + let server = tonic::transport::Server::builder() + .add_service(SupervisorMiddlewareServer::new(ScriptedService { + manifest_name: "test/middleware".into(), + max_body_bytes: 4096, + result: allow_result(), + })) + .serve_with_incoming_shutdown(TcpListenerStream::new(listener), async { + let _ = shutdown_rx.await; + }); + let server_task = tokio::spawn(server); + + let mut registration = external_registration(1024); + registration.grpc_endpoint = format!("http://{address}"); + let mut second_registration = registration.clone(); + second_registration.name = "secondary-guard-service".into(); + let registry = MiddlewareRegistry::connect_services( + Vec::new(), + vec![registration.clone(), second_registration.clone()], + ) + .await + .expect("connect the same external middleware binding under two names"); + let policy = SandboxPolicy { + network_middlewares: HashMap::from([( + "guard".into(), + NetworkMiddlewareConfig { + name: String::new(), + middleware: "local-guard-service".into(), + order: 0, + config: Some(prost_types::Struct::default()), + on_error: "fail_closed".into(), + endpoints: None, + }, + )]), + ..Default::default() + }; + + registry + .validate_policy_configs(&policy) + .await + .expect("remote config validates"); + assert_eq!( + registry.required_services(Some(&policy)), + vec![registration.clone()] + ); + + let outcome = ChainRunner::from_registry(registry) + .evaluate( + &[ + ChainEntry { + name: "primary".into(), + implementation: "local-guard-service".into(), + order: 0, + config: prost_types::Struct::default(), + on_error: OnError::FailClosed, + }, + ChainEntry { + name: "secondary".into(), + implementation: "secondary-guard-service".into(), + order: 10, + config: prost_types::Struct::default(), + on_error: OnError::FailClosed, + }, + ], + input("hello"), + ) + .await + .expect("remote evaluation"); + assert!(outcome.allowed); + assert_eq!(outcome.applied.len(), 2); + assert_eq!(outcome.applied[0].implementation, registration.name); + assert_eq!(outcome.applied[1].implementation, second_registration.name); + + let _ = shutdown_tx.send(()); + server_task + .await + .expect("join test middleware") + .expect("serve"); + } + + #[tokio::test] + async fn remote_transport_accepts_maximum_bounded_request_and_response_envelopes() { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("bind test middleware"); + let address = listener.local_addr().expect("test middleware address"); + let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel(); + let response_findings = (0..MAX_MIDDLEWARE_FINDINGS_PER_STAGE) + .map(|_| Finding { + r#type: "f".repeat(1024), + label: "finding".into(), + count: 1, + confidence: "medium".into(), + severity: "medium".into(), + }) + .collect(); + let server = tonic::transport::Server::builder() + .add_service( + SupervisorMiddlewareServer::new(ScriptedService { + manifest_name: "test/middleware".into(), + max_body_bytes: MAX_MIDDLEWARE_BODY_BYTES as u64, + result: openshell_core::proto::HttpRequestResult { + reason: "r".repeat(MAX_MIDDLEWARE_REASON_BYTES - 128), + reason_code: "r".repeat(MAX_MIDDLEWARE_REASON_CODE_BYTES), + body: vec![b'x'; MAX_MIDDLEWARE_BODY_BYTES], + has_body: true, + header_mutations: vec![write_header( + "x-openshell-middleware-envelope", + &"h".repeat(headers::MAX_HEADER_MUTATION_BYTES - 128), + ExistingHeaderAction::Append, + )], + findings: response_findings, + metadata: std::iter::once(( + "diagnostic".into(), + "m".repeat(MAX_MIDDLEWARE_METADATA_BYTES - 128), + )) + .collect(), + ..allow_result() + }, + }) + .max_decoding_message_size(MIDDLEWARE_GRPC_MESSAGE_BYTES) + .max_encoding_message_size(MIDDLEWARE_GRPC_MESSAGE_BYTES), + ) + .serve_with_incoming_shutdown(TcpListenerStream::new(listener), async { + let _ = shutdown_rx.await; + }); + let server_task = tokio::spawn(server); + + let mut registration = external_registration(MAX_MIDDLEWARE_BODY_BYTES as u64); + registration.grpc_endpoint = format!("http://{address}"); + let registry = MiddlewareRegistry::connect_services(Vec::new(), vec![registration]) + .await + .expect("connect external middleware"); + let config = prost_types::Struct { + fields: std::iter::once(( + "payload".into(), + prost_types::Value { + kind: Some(prost_types::value::Kind::StringValue( + "c".repeat(MAX_MIDDLEWARE_CONFIG_BYTES - 256), + )), + }, + )) + .collect(), + }; + assert!(config.encoded_len() <= MAX_MIDDLEWARE_CONFIG_BYTES); + let mut request = input(""); + request.request_id = "r".repeat(MAX_MIDDLEWARE_CONTEXT_BYTES - 256); + request.path = format!("/{}", "p".repeat(MAX_MIDDLEWARE_TARGET_BYTES - 512)); + request.headers = vec![( + "x-large-envelope".into(), + "v".repeat(MAX_MIDDLEWARE_HEADER_BYTES - 256), + )]; + request.body = vec![b'b'; MAX_MIDDLEWARE_BODY_BYTES]; + let outcome = ChainRunner::from_registry(registry) + .evaluate( + &[ChainEntry { + name: "guard".into(), + implementation: "local-guard-service".into(), + order: 0, + config, + on_error: OnError::FailClosed, + }], + request, + ) + .await + .expect("maximum bounded envelopes should fit configured transport limit"); + + assert!(outcome.allowed); + assert_eq!(outcome.body.len(), MAX_MIDDLEWARE_BODY_BYTES); + assert_eq!(outcome.header_mutations.len(), 1); + assert_eq!(outcome.findings.len(), MAX_MIDDLEWARE_FINDINGS_PER_STAGE); + let _ = shutdown_tx.send(()); + server_task + .await + .expect("join test middleware") + .expect("serve"); + } + + #[test] + fn grpc_envelope_headroom_matches_bounded_components() { + assert_eq!(MIDDLEWARE_GRPC_ENVELOPE_BYTES, 292 * 1024 + 64); + assert_eq!( + MIDDLEWARE_GRPC_MESSAGE_BYTES, + MAX_MIDDLEWARE_BODY_BYTES + 292 * 1024 + 64 + ); + } + + #[tokio::test] + async fn external_diagnostics_are_normalized_before_reaching_logs() { + let secret = "sk-secret-request-value"; + let registration = external_registration(4096); + let service = Arc::new(ScriptedService { + manifest_name: "test/middleware".into(), + max_body_bytes: 4096, + result: openshell_core::proto::HttpRequestResult { + decision: Decision::Deny as i32, + reason: format!("denied body={secret}\nFINDING:FORGED"), + reason_code: "content_match".into(), + findings: vec![Finding { + r#type: format!("secret.{secret}\nforged"), + label: format!("matched {secret}\nFINDING:FORGED"), + count: 1, + confidence: secret.into(), + severity: "high\nFINDING:FORGED".into(), + }], + metadata: std::iter::once(("request".into(), secret.into())).collect(), + ..allow_result() + }, + }); + let registry = registry_with_external(service, registration).await; + let outcome = ChainRunner::from_registry(registry) + .evaluate( + &[ChainEntry { + name: "guard".into(), + implementation: "local-guard-service".into(), + order: 0, + config: prost_types::Struct::default(), + on_error: OnError::FailClosed, + }], + input("hello"), + ) + .await + .expect("evaluate external middleware"); + + assert_eq!(outcome.reason, "middleware_denied:guard:content_match"); + assert_eq!( + outcome.denial, + Some(MiddlewareDenial { + config_name: "guard".into(), + reason_code: Some("content_match".into()), + }) + ); + assert_eq!( + outcome.findings[0].finding.r#type, + "local-guard-service.finding" + ); + assert_eq!(outcome.findings[0].finding.label, EXTERNAL_FINDING_LABEL); + assert_eq!(outcome.findings[0].finding.severity, "medium"); + assert!(outcome.metadata.is_empty()); + assert!(!format!("{outcome:?}").contains(secret)); + assert!(!format!("{outcome:?}").contains("FINDING:FORGED")); + } + + #[tokio::test] + async fn invalid_reason_code_is_a_middleware_failure() { + let runner = ChainRunner::new(Arc::new(scripted_service( + openshell_core::proto::HttpRequestResult { + decision: Decision::Deny as i32, + reason_code: "Secret value!".into(), + ..allow_result() + }, + ))); + let outcome = runner + .evaluate( + &[entry("content-guard", OnError::FailClosed)], + input("hello"), + ) + .await + .expect("evaluate invalid reason code"); + + assert!(!outcome.allowed); + assert_eq!( + outcome.reason, + "middleware_failed: response_reason_code_invalid" + ); + assert!(outcome.denial.is_none()); + assert!(outcome.applied[0].failed); + } + + #[tokio::test] + async fn external_header_mutation_failure_uses_platform_reason() { + let secret = "sk-secret-request-value"; + let registration = external_registration(4096); + let service = Arc::new(ScriptedService { + manifest_name: "test/middleware".into(), + max_body_bytes: 4096, + result: openshell_core::proto::HttpRequestResult { + header_mutations: vec![write_header( + &format!("x-openshell-middleware-invalid\n{secret}"), + "value", + ExistingHeaderAction::Append, + )], + ..allow_result() + }, + }); + let registry = registry_with_external(service, registration).await; + let outcome = ChainRunner::from_registry(registry) + .evaluate( + &[ChainEntry { + name: "guard".into(), + implementation: "local-guard-service".into(), + order: 0, + config: prost_types::Struct::default(), + on_error: OnError::FailClosed, + }], + input("hello"), + ) + .await + .expect("evaluate external middleware"); + + assert!(!outcome.allowed); + assert_eq!( + outcome.reason, + "middleware_failed: header_mutation_invalid_name" + ); + assert!(outcome.findings.is_empty()); + assert!(!format!("{outcome:?}").contains(secret)); + } + + #[tokio::test] + async fn connection_nominated_write_and_remove_are_rejected_after_filtering() { + let mutations = [ + write_header( + "x-openshell-middleware-tag", + "value", + ExistingHeaderAction::Append, + ), + HeaderMutation { + operation: Some(header_mutation::Operation::Remove( + openshell_core::proto::RemoveHeader { + name: "x-openshell-middleware-tag".into(), + }, + )), + }, + ]; + + for mutation in mutations { + let service = Arc::new(ScriptedService { + manifest_name: "test/middleware".into(), + max_body_bytes: 4096, + result: openshell_core::proto::HttpRequestResult { + header_mutations: vec![mutation], + ..allow_result() + }, + }); + let registry = registry_with_external(service, external_registration(4096)).await; + let mut request = input("hello"); + request.connection_nominated_headers = vec!["x-openshell-middleware-tag".into()]; + + let outcome = ChainRunner::from_registry(registry) + .evaluate( + &[ChainEntry { + name: "guard".into(), + implementation: "local-guard-service".into(), + order: 0, + config: prost_types::Struct::default(), + on_error: OnError::FailClosed, + }], + request, + ) + .await + .expect("evaluate external middleware"); + + assert!(!outcome.allowed); + assert_eq!( + outcome.reason, + "middleware_failed: header_mutation_hop_by_hop_header" + ); + } + } + + #[tokio::test] + async fn finding_overflow_is_an_invalid_response_governed_by_on_error() { + let registration = external_registration(4096); + let service = Arc::new(ScriptedService { + manifest_name: "test/middleware".into(), + max_body_bytes: 4096, + result: openshell_core::proto::HttpRequestResult { + findings: vec![Finding::default(); MAX_MIDDLEWARE_FINDINGS_PER_STAGE + 1], + ..allow_result() + }, + }); + let registry = registry_with_external(service, registration).await; + let runner = ChainRunner::from_registry(registry); + + for (on_error, allowed) in [(OnError::FailClosed, false), (OnError::FailOpen, true)] { + let outcome = runner + .evaluate( + &[ChainEntry { + name: "guard".into(), + implementation: "local-guard-service".into(), + order: 0, + config: prost_types::Struct::default(), + on_error, + }], + input("hello"), + ) + .await + .expect("evaluate finding overflow"); + + assert_eq!(outcome.allowed, allowed); + assert!(outcome.findings.is_empty()); + assert_eq!(outcome.applied.len(), 1); + assert!(outcome.applied[0].failed); + if !allowed { + assert_eq!( + outcome.reason, + "middleware_failed: response_findings_over_capacity" + ); + } + } + } + + #[tokio::test] + async fn maximum_chain_retains_findings_from_every_stage() { + let runner = ChainRunner::new(Arc::new(ScriptedService { + manifest_name: "test/middleware".into(), + max_body_bytes: 4096, + result: openshell_core::proto::HttpRequestResult { + findings: vec![ + Finding { + r#type: "example.finding".into(), + label: "Example finding".into(), + count: 1, + confidence: String::new(), + severity: "medium".into(), + }; + MAX_MIDDLEWARE_FINDINGS_PER_STAGE + ], + ..allow_result() + }, + })); + let entries: Vec<_> = (0..MAX_MIDDLEWARE_CHAIN_STAGES) + .map(|index| ChainEntry { + name: format!("guard-{index}"), + implementation: "test/middleware".into(), + order: i32::try_from(index).expect("bounded stage index"), + config: prost_types::Struct::default(), + on_error: OnError::FailClosed, + }) + .collect(); + + let outcome = runner + .evaluate(&entries, input("hello")) + .await + .expect("evaluate maximum chain"); + + assert!(outcome.allowed); + assert_eq!(outcome.applied.len(), MAX_MIDDLEWARE_CHAIN_STAGES); + assert_eq!(outcome.findings.len(), MAX_MIDDLEWARE_CHAIN_FINDINGS); + for (stage, findings) in outcome + .findings + .chunks_exact(MAX_MIDDLEWARE_FINDINGS_PER_STAGE) + .enumerate() + { + assert!( + findings + .iter() + .all(|finding| finding.middleware == format!("guard-{stage}")) + ); + } + } + + #[tokio::test] + async fn deny_decision_short_circuits_chain() { + let runner = ChainRunner::new(Arc::new(scripted_service( + openshell_core::proto::HttpRequestResult { + decision: Decision::Deny as i32, + reason: "blocked_by_policy".into(), + ..allow_result() + }, + ))); + let outcome = runner + .evaluate( + &[ + entry("first", OnError::FailClosed), + entry("second", OnError::FailClosed), + ], + input("hello"), + ) + .await + .expect("evaluate"); + assert!(!outcome.allowed); + assert_eq!(outcome.reason, "middleware_denied:first"); + assert_eq!( + outcome.denial, + Some(MiddlewareDenial { + config_name: "first".into(), + reason_code: None, + }) + ); + assert!(!format!("{outcome:?}").contains("blocked_by_policy")); + // The deny short-circuits the chain: the second middleware never runs. + assert_eq!(outcome.applied.len(), 1); + assert_eq!(outcome.applied[0].decision, Decision::Deny); + assert!(!outcome.applied[0].failed); + } + + #[tokio::test] + async fn deny_decision_ignores_unsafe_mutations_under_fail_open() { + let runner = ChainRunner::new(Arc::new(scripted_service( + openshell_core::proto::HttpRequestResult { + decision: Decision::Deny as i32, + reason: "blocked_by_policy".into(), + header_mutations: vec![write_header( + "x-openshell-middleware-inject", + "ok\r\nHost: evil", + ExistingHeaderAction::Append, + )], + ..allow_result() + }, + ))); + + let outcome = runner + .evaluate(&[entry("guard", OnError::FailOpen)], input("hello")) + .await + .expect("evaluate"); + + assert!(!outcome.allowed); + assert_eq!(outcome.reason, "middleware_denied:guard"); + assert!(outcome.header_mutations.is_empty()); + assert_eq!(outcome.applied.len(), 1); + assert_eq!(outcome.applied[0].decision, Decision::Deny); + assert!(!outcome.applied[0].failed); + } + + #[tokio::test] + async fn deny_decision_ignores_oversized_replacement_under_fail_open() { + let runner = ChainRunner::new(Arc::new(ScriptedService { + manifest_name: BUILTIN_REGEX.into(), + max_body_bytes: 4, + result: openshell_core::proto::HttpRequestResult { + decision: Decision::Deny as i32, + reason: "blocked_by_policy".into(), + body: b"too large".to_vec(), + has_body: true, + ..allow_result() + }, + })); + + let outcome = runner + .evaluate(&[entry("guard", OnError::FailOpen)], input("safe")) + .await + .expect("evaluate"); + + assert!(!outcome.allowed); + assert_eq!(outcome.reason, "middleware_denied:guard"); + assert_eq!(outcome.body, b"safe"); + assert_eq!(outcome.applied.len(), 1); + assert_eq!(outcome.applied[0].decision, Decision::Deny); + assert!(!outcome.applied[0].transformed); + assert!(!outcome.applied[0].failed); + } + + #[tokio::test] + async fn metadata_and_findings_are_namespaced_per_config() { + let runner = ChainRunner::new(Arc::new(scripted_service( + openshell_core::proto::HttpRequestResult { + findings: vec![Finding { + r#type: "pii.email".into(), + label: "email address".into(), + count: 2, + confidence: "high".into(), + severity: "medium".into(), + }], + metadata: std::iter::once(("sensitivity".to_string(), "high".to_string())) + .collect(), + ..allow_result() + }, + ))); + let outcome = runner + .evaluate( + &[ + entry("alpha", OnError::FailClosed), + entry("beta", OnError::FailClosed), + ], + input("hello"), + ) + .await + .expect("evaluate"); + assert!(outcome.allowed); + // Metadata is bucketed under each config's local name, so two configs + // emitting the same key do not collide. + assert_eq!(outcome.metadata["alpha"]["sensitivity"], "high"); + assert_eq!(outcome.metadata["beta"]["sensitivity"], "high"); + // Findings are tagged with the emitting config's name. + assert_eq!(outcome.findings.len(), 2); + assert_eq!(outcome.findings[0].middleware, "alpha"); + assert_eq!(outcome.findings[1].middleware, "beta"); + assert_eq!(outcome.findings[0].finding.r#type, "pii.email"); + assert_eq!(outcome.findings[0].finding.count, 2); + } + + fn unsafe_header_service() -> ScriptedService { + scripted_service(openshell_core::proto::HttpRequestResult { + header_mutations: vec![ + write_header( + "x-openshell-middleware-safe", + "safe", + ExistingHeaderAction::Append, + ), + write_header( + "x-openshell-middleware-inject", + "ok\r\nHost: evil", + ExistingHeaderAction::Append, + ), + ], + ..allow_result() + }) + } + + #[tokio::test] + async fn malformed_response_headers_fail_closed_denies() { + let runner = ChainRunner::new(Arc::new(unsafe_header_service())); + let outcome = runner + .evaluate(&[entry("redact", OnError::FailClosed)], input("hello")) + .await + .expect("evaluate"); + assert!(!outcome.allowed); + assert!(outcome.reason.starts_with("middleware_failed:")); + // The deny reason names the offending header so operators can fix the + // service without reading supervisor source. + assert!( + outcome.reason.contains("x-openshell-middleware-inject"), + "reason should name the offending header: {}", + outcome.reason + ); + assert!(outcome.applied.iter().any(|inv| inv.failed)); + // The stage is atomic: neither the unsafe mutation nor the safe + // mutation preceding it is forwarded. + assert!(outcome.header_mutations.is_empty()); + } + + #[tokio::test] + async fn malformed_response_headers_fail_open_continues() { + let runner = ChainRunner::new(Arc::new(unsafe_header_service())); + let outcome = runner + .evaluate(&[entry("redact", OnError::FailOpen)], input("hello")) + .await + .expect("evaluate"); + assert!(outcome.allowed); + assert_eq!(outcome.body, b"hello"); + assert!(outcome.header_mutations.is_empty()); + assert_eq!(outcome.applied.len(), 1); + assert!(outcome.applied[0].failed); + } + + #[tokio::test] + async fn oversized_replacement_body_honors_on_error() { + let runner = ChainRunner::new(Arc::new(ScriptedService { + manifest_name: BUILTIN_REGEX.into(), + max_body_bytes: 4, + result: openshell_core::proto::HttpRequestResult { + body: b"too large".to_vec(), + has_body: true, + ..allow_result() + }, + })); + let fail_open = entry("small", OnError::FailOpen); + let mut fail_closed = fail_open.clone(); + fail_closed.on_error = OnError::FailClosed; + + let open_outcome = runner + .evaluate(&[fail_open], input("safe")) + .await + .expect("fail-open evaluation"); + assert!(open_outcome.allowed); + assert_eq!(open_outcome.body, b"safe"); + assert!(open_outcome.applied[0].failed); + + let closed_outcome = runner + .evaluate(&[fail_closed], input("safe")) + .await + .expect("fail-closed evaluation"); + assert!(!closed_outcome.allowed); + assert_eq!( + closed_outcome.reason, + "middleware_failed: response_body_over_capacity" + ); + assert!(closed_outcome.applied[0].failed); + } + + #[tokio::test] + async fn oversized_request_body_honors_on_error() { + let runner = ChainRunner::new(Arc::new(ScriptedService { + manifest_name: BUILTIN_REGEX.into(), + max_body_bytes: 4, + result: allow_result(), + })); + let fail_open = entry("small", OnError::FailOpen); + let mut fail_closed = fail_open.clone(); + fail_closed.on_error = OnError::FailClosed; + + let open_outcome = runner + .evaluate(&[fail_open], input("hello")) + .await + .expect("fail-open evaluation"); + assert!(open_outcome.allowed); + assert_eq!(open_outcome.body, b"hello"); + assert!(open_outcome.applied[0].failed); + + let closed_outcome = runner + .evaluate(&[fail_closed], input("hello")) + .await + .expect("fail-closed evaluation"); + assert!(!closed_outcome.allowed); + assert_eq!( + closed_outcome.reason, + "middleware_failed: request_body_over_capacity" + ); + assert!(closed_outcome.applied[0].failed); + } + + #[tokio::test] + async fn unspecified_decision_uses_fail_closed() { + let runner = ChainRunner::new(Arc::new(scripted_service( + openshell_core::proto::HttpRequestResult { + decision: Decision::Unspecified as i32, + ..allow_result() + }, + ))); + + let outcome = runner + .evaluate(&[entry("redact", OnError::FailClosed)], input("hello")) + .await + .expect("evaluate"); + + assert!(!outcome.allowed); + assert_eq!( + outcome.reason, + "middleware_failed: invalid_response_decision" + ); + assert!(outcome.applied[0].failed); + } +} diff --git a/crates/openshell-supervisor-middleware/src/remote.rs b/crates/openshell-supervisor-middleware/src/remote.rs new file mode 100644 index 0000000000..378dac3ec4 --- /dev/null +++ b/crates/openshell-supervisor-middleware/src/remote.rs @@ -0,0 +1,85 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +use std::time::Duration; + +use miette::{IntoDiagnostic, Result, WrapErr}; +use openshell_core::proto::middleware::v1::supervisor_middleware_client::SupervisorMiddlewareClient; +use openshell_core::proto::middleware::v1::supervisor_middleware_server::SupervisorMiddleware; +use openshell_core::proto::{ + HttpRequestEvaluation, HttpRequestResult, MiddlewareManifest, ValidateConfigRequest, + ValidateConfigResponse, +}; +use tonic::transport::{Channel, ClientTlsConfig, Endpoint}; +use tonic::{Request, Response, Status}; + +use crate::MIDDLEWARE_GRPC_MESSAGE_BYTES; + +const CONNECT_TIMEOUT: Duration = Duration::from_secs(5); + +#[derive(Clone)] +pub struct RemoteMiddlewareService { + client: SupervisorMiddlewareClient, +} + +impl RemoteMiddlewareService { + pub async fn connect(registration_name: &str, grpc_endpoint: &str) -> Result { + let mut endpoint = Endpoint::from_shared(grpc_endpoint.to_string()) + .into_diagnostic() + .wrap_err_with(|| { + format!( + "middleware registration '{registration_name}' has an invalid grpc_endpoint" + ) + })?; + if grpc_endpoint.starts_with("https://") { + endpoint = endpoint + .tls_config(ClientTlsConfig::new().with_enabled_roots()) + .into_diagnostic() + .wrap_err_with(|| { + format!("middleware registration '{registration_name}' could not configure TLS") + })?; + } + let channel = endpoint + .connect_timeout(CONNECT_TIMEOUT) + .connect() + .await + .into_diagnostic() + .wrap_err_with(|| { + format!( + "middleware registration '{registration_name}' could not connect to {grpc_endpoint}" + ) + })?; + Ok(Self { + client: SupervisorMiddlewareClient::new(channel) + .max_decoding_message_size(MIDDLEWARE_GRPC_MESSAGE_BYTES) + .max_encoding_message_size(MIDDLEWARE_GRPC_MESSAGE_BYTES), + }) + } +} + +#[tonic::async_trait] +impl SupervisorMiddleware for RemoteMiddlewareService { + async fn describe( + &self, + request: Request<()>, + ) -> std::result::Result, Status> { + let mut client = self.client.clone(); + client.describe(request).await + } + + async fn validate_config( + &self, + request: Request, + ) -> std::result::Result, Status> { + let mut client = self.client.clone(); + client.validate_config(request).await + } + + async fn evaluate_http_request( + &self, + request: Request, + ) -> std::result::Result, Status> { + let mut client = self.client.clone(); + client.evaluate_http_request(request).await + } +} diff --git a/crates/openshell-supervisor-network/Cargo.toml b/crates/openshell-supervisor-network/Cargo.toml index 7d0079f7b3..1449276f4f 100644 --- a/crates/openshell-supervisor-network/Cargo.toml +++ b/crates/openshell-supervisor-network/Cargo.toml @@ -15,6 +15,7 @@ openshell-core = { path = "../openshell-core" } openshell-ocsf = { path = "../openshell-ocsf" } openshell-policy = { path = "../openshell-policy" } openshell-router = { path = "../openshell-router" } +openshell-supervisor-middleware = { path = "../openshell-supervisor-middleware" } apollo-parser = { workspace = true } aws-sigv4 = { version = "1", features = ["sign-http", "http1"] } @@ -28,6 +29,7 @@ glob = { workspace = true } hex = "0.4" ipnet = "2" miette = { workspace = true } +prost-types = { workspace = true } rcgen = { workspace = true } regorus = { version = "0.9", default-features = false, features = ["std", "arc", "glob"] } reqwest = { workspace = true } @@ -49,10 +51,13 @@ webpki-roots = { workspace = true } [dev-dependencies] openshell-core = { path = "../openshell-core", features = ["test-helpers"] } +openshell-supervisor-middleware-builtins = { path = "../openshell-supervisor-middleware-builtins" } tempfile = "3" +tonic = { workspace = true } temp-env = "0.3" tokio-tungstenite = { workspace = true } futures = { workspace = true } +tracing-subscriber = { workspace = true } [target.'cfg(unix)'.dev-dependencies] libc = "0.2" diff --git a/crates/openshell-supervisor-network/data/sandbox-policy.rego b/crates/openshell-supervisor-network/data/sandbox-policy.rego index d70c69b748..780080c54a 100644 --- a/crates/openshell-supervisor-network/data/sandbox-policy.rego +++ b/crates/openshell-supervisor-network/data/sandbox-policy.rego @@ -856,20 +856,22 @@ _policy_endpoint_configs(policy) := [ep | endpoint_has_extended_config(ep) ] -# Collect matching endpoint configs across all policies. Iterates over -# _matching_policy_names (a set, safe from regorus variable collisions) -# then collects per-policy configs via the helper function. _matching_endpoint_configs := [cfg | some pname _matching_policy_names[pname] cfgs := _policy_endpoint_configs(data.network_policies[pname]) cfg := cfgs[_] + endpoint_has_extended_config(cfg) ] matched_endpoint_config := _matching_endpoint_configs[0] if { count(_matching_endpoint_configs) > 0 } +# Expose middleware policy data to Rust. Selection and validation stay in Rust; +# Rego does not evaluate middleware selectors. +network_middlewares := object.get(data, "network_middlewares", {}) + _policy_has_exact_declared_endpoint(policy) if { some ep ep := policy.endpoints[_] diff --git a/crates/openshell-supervisor-network/src/l7/middleware.rs b/crates/openshell-supervisor-network/src/l7/middleware.rs new file mode 100644 index 0000000000..263d886f28 --- /dev/null +++ b/crates/openshell-supervisor-network/src/l7/middleware.rs @@ -0,0 +1,727 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Supervisor middleware application for L7 requests. + +use crate::l7::relay::L7EvalContext; +use crate::opa::PolicyGenerationGuard; +use miette::{Result, miette}; +use openshell_ocsf::{ + ActionId, ActivityId, DetectionFindingBuilder, DispositionId, Endpoint, FindingInfo, + HttpActivityBuilder, HttpRequest, SeverityId, StatusId, Url as OcsfUrl, ocsf_emit, +}; +use std::path::PathBuf; +use tokio::io::{AsyncRead, AsyncWrite}; + +pub enum MiddlewareApplyResult { + Allowed(crate::l7::provider::L7Request), + Denied { + denial: Option, + }, +} + +/// How traffic a middleware chain can never inspect (h2c, non-HTTP TCP, +/// protocols without an L7 relay) must be handled for a matching chain. +/// +/// This is derived from each entry's `on_error` today. A future per-config +/// `on_uninspectable` knob could let an operator keep `fail_closed` error +/// handling for HTTP traffic while allowing uninspectable protocols through +/// without maintaining host excludes. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum UninspectableTrafficGate { + /// No middleware matches this destination; raw relay is unaffected. + Unrestricted, + /// Every matching entry is `fail_open`: relay raw bytes but emit a bypass + /// detection finding. + BypassWithFinding, + /// At least one matching entry is `fail_closed`: deny, the middleware + /// must be able to see the traffic for it to flow. + Deny, +} + +pub fn uninspectable_traffic_gate( + chain: &[openshell_supervisor_middleware::ChainEntry], +) -> UninspectableTrafficGate { + if chain.is_empty() { + return UninspectableTrafficGate::Unrestricted; + } + if chain + .iter() + .all(|entry| entry.on_error == openshell_supervisor_middleware::OnError::FailOpen) + { + UninspectableTrafficGate::BypassWithFinding + } else { + UninspectableTrafficGate::Deny + } +} + +/// Emit the detection finding for traffic a matching middleware chain cannot +/// inspect: denied under a fail-closed chain, bypassed under fail-open. +pub fn emit_middleware_uninspectable(ctx: &L7EvalContext, detail: &str, denied: bool) { + let event = DetectionFindingBuilder::new(openshell_ocsf::ctx::ctx()) + .severity(if denied { + SeverityId::High + } else { + SeverityId::Medium + }) + .finding_info(FindingInfo::new( + "openshell.middleware.traffic_uninspectable", + "Supervisor middleware cannot inspect this traffic", + )) + .evidence_pairs(&[ + ("policy", ctx.policy_name.as_str()), + ("host", ctx.host.as_str()), + ("protocol", detail), + ("disposition", if denied { "denied" } else { "fail_open" }), + ]) + .message(if denied { + "Uninspectable traffic to host with required middleware; denied" + } else { + "Uninspectable traffic bypassed middleware (fail_open)" + }) + .build(); + ocsf_emit!(event); +} + +/// Largest body-buffering limit across the entries that actually resolved to a +/// registered binding. Buffering for the most capable stage lets every stage +/// that can handle the body run; stages whose own limit is smaller are failed +/// individually with `request_body_over_capacity` through their `on_error` +/// policy in `evaluate_described`, instead of one undersized stage forcing the +/// whole chain onto the unbuffered path. Unresolved entries +/// (`is_resolved() == false`) report a zero limit and are excluded here: they +/// are handled by their `on_error` policy without inspecting the body. +/// Returns `None` when no entry resolved, so the caller can skip buffering. +pub(super) fn middleware_chain_body_limit( + chain: &[openshell_supervisor_middleware::DescribedChainEntry], +) -> Option { + chain + .iter() + .filter(|entry| entry.is_resolved()) + .map(openshell_supervisor_middleware::DescribedChainEntry::max_body_bytes) + .max() +} + +pub async fn apply_middleware_chain( + req: crate::l7::provider::L7Request, + client: &mut C, + ctx: &L7EvalContext, + chain: Vec, + runner: &openshell_supervisor_middleware::ChainRunner, + generation_guard: &PolicyGenerationGuard, + transformed_body_policy: openshell_supervisor_middleware::TransformedBodyPolicy<'_>, +) -> Result { + apply_middleware_chain_for_scheme( + req, + client, + ctx, + "https", + chain, + runner, + generation_guard, + transformed_body_policy, + ) + .await +} + +#[allow(clippy::too_many_arguments)] +pub async fn apply_middleware_chain_for_scheme( + req: crate::l7::provider::L7Request, + client: &mut C, + ctx: &L7EvalContext, + scheme: &str, + chain: Vec, + runner: &openshell_supervisor_middleware::ChainRunner, + generation_guard: &PolicyGenerationGuard, + transformed_body_policy: openshell_supervisor_middleware::TransformedBodyPolicy<'_>, +) -> Result { + if chain.is_empty() { + return Ok(MiddlewareApplyResult::Allowed(req)); + } + let chain = runner.describe_chain(&chain).await?; + let Some(max_body_bytes) = middleware_chain_body_limit(&chain) else { + // No entry resolved to a registered binding, so nothing inspects the + // body. Apply each entry's `on_error` policy without buffering (an + // unresolved binding is handled before the body is read) and forward + // the original request unchanged if the chain allows. + let input = middleware_request_input( + scheme, + &req, + ctx, + Vec::new(), + Vec::new(), + String::new(), + Vec::new(), + ); + let outcome = runner.evaluate_described(&chain, input).await?; + emit_middleware_events(ctx, &req, &outcome); + return Ok(if outcome.allowed { + MiddlewareApplyResult::Allowed(req) + } else { + MiddlewareApplyResult::Denied { + denial: outcome.denial, + } + }); + }; + let buffered = match crate::l7::rest::buffer_request_body_for_middleware( + &req, + client, + Some(generation_guard), + max_body_bytes, + ) + .await? + { + crate::l7::rest::BufferResult::Buffered(buffered) => buffered, + crate::l7::rest::BufferResult::OverCapacity { recoverable } => { + return Ok(resolve_unbuffered_body(ctx, req, &chain, recoverable)); + } + }; + let headers = safe_middleware_headers(&buffered.headers)?; + let query = raw_query_from_request_headers(&buffered.headers)?; + let input = middleware_request_input( + scheme, + &req, + ctx, + headers.visible, + headers.connection_nominated, + query, + buffered.body, + ); + // The explicitly selected transformation policy either re-checks every + // replacement or documents that this protocol's policy is body-independent. + // An ALLOW outcome therefore means the final body is policy-compliant. + let outcome = runner + .evaluate_described_with_policy(&chain, input, transformed_body_policy) + .await?; + emit_middleware_events(ctx, &req, &outcome); + if !outcome.allowed { + return Ok(MiddlewareApplyResult::Denied { + denial: outcome.denial, + }); + } + let rebuilt = crate::l7::rest::rebuild_request_with_buffered_body( + &req, + &buffered.headers, + &outcome.body, + &outcome.header_mutations, + )?; + Ok(MiddlewareApplyResult::Allowed(rebuilt)) +} + +pub async fn send_middleware_rejection_response( + req: &crate::l7::provider::L7Request, + client: &mut C, + ctx: &L7EvalContext, + denial: Option<&openshell_supervisor_middleware::MiddlewareDenial>, + redacted_target: &str, +) -> Result<()> { + let context = Some(crate::l7::rest::DenyResponseContext { + host: Some(&ctx.host), + port: Some(ctx.port), + binary: Some(&ctx.binary_path), + }); + if let Some(denial) = denial { + crate::l7::rest::send_middleware_deny_response( + req, + &ctx.policy_name, + denial, + client, + Some(redacted_target), + context, + ) + .await + } else { + crate::l7::rest::send_middleware_failure_response( + req, + &ctx.policy_name, + client, + Some(redacted_target), + context, + ) + .await + } +} + +pub(super) fn middleware_request_input( + scheme: &str, + req: &crate::l7::provider::L7Request, + ctx: &L7EvalContext, + headers: Vec<(String, String)>, + connection_nominated_headers: Vec, + query: String, + body: Vec, +) -> openshell_supervisor_middleware::HttpRequestInput { + openshell_supervisor_middleware::HttpRequestInput { + request_id: uuid::Uuid::new_v4().to_string(), + sandbox_id: openshell_ocsf::ctx::ctx().sandbox_id.clone(), + scheme: scheme.into(), + host: ctx.host.clone(), + port: ctx.port, + method: req.action.clone(), + path: req.target.clone(), + query, + headers, + connection_nominated_headers, + body, + } +} + +pub(super) fn raw_query_from_request_headers(headers: &[u8]) -> Result { + let header_str = + std::str::from_utf8(headers).map_err(|_| miette!("HTTP headers contain invalid UTF-8"))?; + let target = header_str + .lines() + .next() + .and_then(|line| line.split_whitespace().nth(1)) + .ok_or_else(|| miette!("HTTP request line is missing a target"))?; + Ok(target + .split_once('?') + .map_or_else(String::new, |(_, query)| query.to_string())) +} + +/// Apply the chain's `on_error` policy when the request body exceeds every +/// stage's buffering limit. No stage can inspect such a body, so each stage +/// would individually fail with `request_body_over_capacity`; the aggregate is +/// a deny unless every attached middleware is `fail_open`, and passing the +/// body through is only safe when no bytes were consumed. +pub(super) fn resolve_unbuffered_body( + ctx: &L7EvalContext, + req: crate::l7::provider::L7Request, + chain: &[openshell_supervisor_middleware::DescribedChainEntry], + recoverable: bool, +) -> MiddlewareApplyResult { + let all_fail_open = chain + .iter() + .all(|entry| entry.on_error() == openshell_supervisor_middleware::OnError::FailOpen); + if recoverable && all_fail_open { + emit_middleware_body_unavailable(ctx, false); + return MiddlewareApplyResult::Allowed(req); + } + emit_middleware_body_unavailable(ctx, true); + MiddlewareApplyResult::Denied { denial: None } +} + +fn emit_middleware_body_unavailable(ctx: &L7EvalContext, denied: bool) { + let event = DetectionFindingBuilder::new(openshell_ocsf::ctx::ctx()) + .severity(if denied { + SeverityId::High + } else { + SeverityId::Medium + }) + .finding_info(FindingInfo::new( + "openshell.middleware.body_unavailable", + "Supervisor middleware could not inspect request body", + )) + .evidence_pairs(&[ + ("policy", ctx.policy_name.as_str()), + ("host", ctx.host.as_str()), + ("disposition", if denied { "denied" } else { "fail_open" }), + ]) + .message(if denied { + "Request body exceeded middleware inspection cap; denied" + } else { + "Request body exceeded middleware inspection cap; passed through (fail_open)" + }) + .build(); + ocsf_emit!(event); +} + +/// Parse the raw header block into middleware-visible headers, preserving +/// wire order and repeated names so middleware inspects every value the +/// upstream will receive. Credential-bearing and hop-by-hop headers are +/// omitted, while dynamically nominated names are retained separately for +/// mutation validation. +struct SafeMiddlewareHeaders { + visible: Vec<(String, String)>, + connection_nominated: Vec, +} + +fn safe_middleware_headers(headers: &[u8]) -> Result { + crate::l7::rest::validate_http_request_header_block(headers)?; + let header_str = + std::str::from_utf8(headers).map_err(|_| miette!("HTTP headers contain invalid UTF-8"))?; + let header_block = header_str + .strip_suffix("\r\n\r\n") + .expect("validated header block has terminator"); + let connection_nominated = crate::l7::rest::connection_nominated_header_names(headers)?; + + let visible = header_block + .split("\r\n") + .skip(1) + .map(|line| { + let (name, value) = line + .split_once(':') + .expect("validated header field contains colon"); + (name.to_ascii_lowercase(), value.trim().to_string()) + }) + .filter(|(name, _)| { + !name.is_empty() + && !matches!( + name.as_str(), + "authorization" + | "proxy-authorization" + | "proxy-authenticate" + | "cookie" + | "host" + | "content-length" + | "transfer-encoding" + | "connection" + | "proxy-connection" + | "keep-alive" + | "te" + | "trailer" + | "upgrade" + ) + && !name.starts_with("x-amz-") + && !name.starts_with("x-openshell-credential") + && !connection_nominated.contains(name) + }) + .collect(); + let mut connection_nominated: Vec<_> = connection_nominated.into_iter().collect(); + connection_nominated.sort(); + Ok(SafeMiddlewareHeaders { + visible, + connection_nominated, + }) +} + +pub fn middleware_network_input(ctx: &L7EvalContext) -> crate::opa::NetworkInput { + crate::opa::NetworkInput { + host: ctx.host.clone(), + port: ctx.port, + binary_path: PathBuf::from(&ctx.binary_path), + binary_sha256: String::new(), + ancestors: ctx.ancestors.iter().map(PathBuf::from).collect(), + cmdline_paths: ctx.cmdline_paths.iter().map(PathBuf::from).collect(), + } +} + +/// Build the OCSF events describing a middleware chain outcome, in emission +/// order. Separated from `emit_middleware_events` so tests can assert on the +/// events deterministically without routing through the global tracing pipeline, +/// whose callsite-interest cache is process-global and races under parallel +/// tests. +pub(super) fn middleware_events( + ctx: &L7EvalContext, + req: &crate::l7::provider::L7Request, + outcome: &openshell_supervisor_middleware::ChainOutcome, +) -> Vec { + let mut events = Vec::new(); + for invocation in &outcome.applied { + let allowed = invocation.decision == openshell_core::proto::Decision::Allow; + let mut event = HttpActivityBuilder::new(openshell_ocsf::ctx::ctx()) + .activity(ActivityId::Other) + .action(if allowed { + ActionId::Allowed + } else { + ActionId::Denied + }) + .disposition(if allowed { + DispositionId::Allowed + } else { + DispositionId::Blocked + }) + .severity(if allowed { + SeverityId::Informational + } else { + SeverityId::Medium + }) + .http_request(HttpRequest::new( + &req.action, + OcsfUrl::new("http", &ctx.host, &req.target, ctx.port), + )) + .dst_endpoint(Endpoint::from_domain(&ctx.host, ctx.port)) + .firewall_rule(&ctx.policy_name, "middleware") + .unmapped("transformed", invocation.transformed) + .unmapped("failed", invocation.failed) + .message(format!( + "MIDDLEWARE {} {} decision={:?}", + invocation.name, invocation.implementation, invocation.decision + )); + if !allowed && !outcome.reason.is_empty() { + event = event + .status(StatusId::Failure) + .status_detail(&outcome.reason); + } + let event = event.build(); + events.push(event); + + // A middleware that failed but was bypassed under `fail_open` is an + // enforcement failure operators must be able to alert on, even though the + // request proceeded. + if invocation.failed && allowed { + let event = DetectionFindingBuilder::new(openshell_ocsf::ctx::ctx()) + .severity(SeverityId::Medium) + .finding_info(FindingInfo::new( + "openshell.middleware.failure", + "Supervisor middleware failed open", + )) + .evidence_pairs(&[ + ("middleware", invocation.name.as_str()), + ("implementation", invocation.implementation.as_str()), + ]) + .unmapped("middleware", invocation.name.as_str()) + .unmapped("implementation", invocation.implementation.as_str()) + .message(format!( + "Middleware {} failed and was bypassed (fail_open)", + invocation.name + )) + .build(); + events.push(event); + } + } + if !outcome.allowed && outcome.reason.starts_with("middleware_failed:") { + let event = DetectionFindingBuilder::new(openshell_ocsf::ctx::ctx()) + .severity(SeverityId::High) + .finding_info(FindingInfo::new( + "openshell.middleware.failure", + "Supervisor middleware failure", + )) + .message("Required supervisor middleware failed closed") + .build(); + events.push(event); + } + if !outcome.allowed + && outcome + .reason + .starts_with("transformed_body_policy_evaluation_failed:") + { + let event = DetectionFindingBuilder::new(openshell_ocsf::ctx::ctx()) + .severity(SeverityId::High) + .finding_info(FindingInfo::new( + "openshell.middleware.policy_evaluation_failure", + "Post-middleware policy evaluation failed", + )) + .evidence_pairs(&[ + ("policy", ctx.policy_name.as_str()), + ("host", ctx.host.as_str()), + ]) + .message("Transformed request denied because policy evaluation failed") + .build(); + events.push(event); + } + // Each stage and the selected chain are independently bounded by the + // runner. Keep the derived chain-wide emission bound as defense in depth + // for manually constructed or future outcome producers. + for finding in outcome + .findings + .iter() + .take(openshell_supervisor_middleware::MAX_MIDDLEWARE_CHAIN_FINDINGS) + { + let event = DetectionFindingBuilder::new(openshell_ocsf::ctx::ctx()) + .severity(match finding.finding.severity.as_str() { + "high" => SeverityId::High, + "low" => SeverityId::Low, + _ => SeverityId::Medium, + }) + .finding_info(FindingInfo::new( + &finding.finding.r#type, + &finding.finding.label, + )) + .evidence_pairs(&[ + ("middleware", &finding.middleware), + ("count", &finding.finding.count.to_string()), + ]) + .unmapped("middleware", finding.middleware.as_str()) + .unmapped("count", finding.finding.count) + .message(format!( + "Middleware finding {} count={}", + finding.finding.r#type, finding.finding.count + )) + .build(); + events.push(event); + } + events +} + +/// Emit the OCSF events describing a middleware chain outcome through the +/// tracing pipeline. +fn emit_middleware_events( + ctx: &L7EvalContext, + req: &crate::l7::provider::L7Request, + outcome: &openshell_supervisor_middleware::ChainOutcome, +) { + for event in middleware_events(ctx, req, outcome) { + ocsf_emit!(event); + } +} + +#[cfg(test)] +mod tests { + use super::{safe_middleware_headers, send_middleware_rejection_response}; + use crate::l7::relay::L7EvalContext; + use tokio::io::AsyncReadExt; + + #[tokio::test] + async fn direct_denial_uses_middleware_response_without_service_text() { + let ctx = L7EvalContext { + host: "api.example.test".into(), + port: 443, + policy_name: "api-policy".into(), + binary_path: "/usr/bin/curl".into(), + ancestors: Vec::new(), + cmdline_paths: Vec::new(), + secret_resolver: None, + activity_tx: None, + dynamic_credentials: None, + token_grant_resolver: None, + }; + let req = crate::l7::provider::L7Request { + action: "POST".into(), + target: "/v1/messages".into(), + query_params: std::collections::HashMap::new(), + raw_header: Vec::new(), + body_length: crate::l7::provider::BodyLength::None, + }; + let denial = openshell_supervisor_middleware::MiddlewareDenial { + config_name: "prototype-content-guard".into(), + reason_code: Some("content_match".into()), + }; + let (mut client, mut server) = tokio::io::duplex(4096); + + send_middleware_rejection_response(&req, &mut server, &ctx, Some(&denial), "/v1/messages") + .await + .expect("send denial"); + drop(server); + + let mut response = Vec::new(); + client + .read_to_end(&mut response) + .await + .expect("read denial"); + let response = String::from_utf8(response).expect("UTF-8 response"); + let (_, body) = response.split_once("\r\n\r\n").expect("HTTP response"); + let body: serde_json::Value = serde_json::from_str(body).expect("JSON response"); + assert_eq!(body["error"], "middleware_denied"); + assert_eq!(body["middleware"], "prototype-content-guard"); + assert_eq!(body["reason_code"], "content_match"); + assert!(body.get("rule_missing").is_none()); + assert!(body.get("next_steps").is_none()); + assert!(!body.to_string().contains("secret-value")); + } + + #[tokio::test] + async fn middleware_failure_uses_platform_response_without_policy_guidance() { + let _proposals = + openshell_core::proposals::test_helpers::ProposalsFlagGuard::set(true).await; + let ctx = L7EvalContext { + host: "api.example.test".into(), + port: 443, + policy_name: "api-policy".into(), + binary_path: "/usr/bin/curl".into(), + ancestors: Vec::new(), + cmdline_paths: Vec::new(), + secret_resolver: None, + activity_tx: None, + dynamic_credentials: None, + token_grant_resolver: None, + }; + let req = crate::l7::provider::L7Request { + action: "POST".into(), + target: "/v1/messages".into(), + query_params: std::collections::HashMap::new(), + raw_header: Vec::new(), + body_length: crate::l7::provider::BodyLength::None, + }; + let (mut client, mut server) = tokio::io::duplex(4096); + + send_middleware_rejection_response(&req, &mut server, &ctx, None, "/v1/messages") + .await + .expect("send failure"); + drop(server); + + let mut response = Vec::new(); + client + .read_to_end(&mut response) + .await + .expect("read failure"); + let response = String::from_utf8(response).expect("UTF-8 response"); + let (_, body) = response.split_once("\r\n\r\n").expect("HTTP response"); + let body: serde_json::Value = serde_json::from_str(body).expect("JSON response"); + assert_eq!(body["error"], "middleware_failed"); + assert_eq!( + body["detail"], + "Request could not be processed by configured middleware" + ); + assert!(body.get("rule").is_none()); + assert!(body.get("rule_missing").is_none()); + assert!(body.get("next_steps").is_none()); + assert!(body.get("agent_guidance").is_none()); + } + + #[test] + fn middleware_headers_exclude_origin_and_proxy_credentials() { + let headers = safe_middleware_headers( + b"GET http://api.example.test/v1 HTTP/1.1\r\n\ + Authorization: Bearer origin-secret\r\n\ + Proxy-Authorization: Basic proxy-secret\r\n\ + X-Request-ID: request-123\r\n\r\n", + ) + .expect("headers should parse"); + + assert_eq!( + headers.visible, + vec![("x-request-id".to_string(), "request-123".to_string())] + ); + } + + #[test] + fn middleware_headers_preserve_repeated_names_in_wire_order() { + // Repeated header names must reach middleware as separate entries in + // wire order: keeping only one value would let a request smuggle a + // differently-positioned duplicate past inspection while the upstream + // still receives every original value. + let headers = safe_middleware_headers( + b"POST /v1 HTTP/1.1\r\n\ + X-Api-Key: first-value\r\n\ + Accept: application/json\r\n\ + X-Api-Key: second-value\r\n\r\n", + ) + .expect("headers should parse"); + + assert_eq!( + headers.visible, + vec![ + ("x-api-key".to_string(), "first-value".to_string()), + ("accept".to_string(), "application/json".to_string()), + ("x-api-key".to_string(), "second-value".to_string()), + ] + ); + } + + #[test] + fn middleware_headers_omit_standard_and_connection_nominated_hop_by_hop_fields() { + let headers = safe_middleware_headers( + b"GET /v1 HTTP/1.1\r\n\ + X-Hop: secret-hop-value\r\n\ + Connection: keep-alive, x-hop\r\n\ + Keep-Alive: timeout=5\r\n\ + TE: trailers\r\n\ + Trailer: X-Checksum\r\n\ + Upgrade: websocket\r\n\ + X-Visible: visible-value\r\n\r\n", + ) + .expect("headers should parse"); + + assert_eq!( + headers.visible, + vec![("x-visible".to_string(), "visible-value".to_string())] + ); + assert_eq!(headers.connection_nominated, vec!["keep-alive", "x-hop"]); + } + + #[test] + fn middleware_headers_reject_malformed_fields_instead_of_dropping_them() { + for headers in [ + b"GET /v1 HTTP/1.1\r\nX-Test: first\r\n continued\r\n\r\n".as_slice(), + b"GET /v1 HTTP/1.1\r\nX-Test value\r\n\r\n".as_slice(), + b"GET /v1 HTTP/1.1\r\nX-Test : value\r\n\r\n".as_slice(), + b"GET /v1 HTTP/1.1\r\nX@Test: value\r\n\r\n".as_slice(), + ] { + assert!( + safe_middleware_headers(headers).is_err(), + "middleware must reject malformed header fields" + ); + } + } +} diff --git a/crates/openshell-supervisor-network/src/l7/mod.rs b/crates/openshell-supervisor-network/src/l7/mod.rs index 005e37ff6e..c9330a3de1 100644 --- a/crates/openshell-supervisor-network/src/l7/mod.rs +++ b/crates/openshell-supervisor-network/src/l7/mod.rs @@ -12,6 +12,7 @@ pub mod graphql; pub(crate) mod http; pub mod inference; pub mod jsonrpc; +pub(crate) mod middleware; pub mod path; pub mod provider; pub mod relay; diff --git a/crates/openshell-supervisor-network/src/l7/relay.rs b/crates/openshell-supervisor-network/src/l7/relay.rs index 3efdc80057..4bf1bb0bc0 100644 --- a/crates/openshell-supervisor-network/src/l7/relay.rs +++ b/crates/openshell-supervisor-network/src/l7/relay.rs @@ -7,6 +7,15 @@ //! Parses each request within the tunnel, evaluates it against OPA policy, //! and either forwards or denies the request. +use crate::l7::middleware::{ + MiddlewareApplyResult, UninspectableTrafficGate, apply_middleware_chain, + emit_middleware_uninspectable, middleware_network_input, uninspectable_traffic_gate, +}; +#[cfg(test)] +use crate::l7::middleware::{ + middleware_chain_body_limit, middleware_events, middleware_request_input, + raw_query_from_request_headers, resolve_unbuffered_body, +}; use crate::l7::provider::{L7Provider, RelayOutcome}; use crate::l7::rest::WebSocketExtensionMode; use crate::l7::{EnforcementMode, L7EndpointConfig, L7Protocol, L7RequestInfo}; @@ -18,6 +27,8 @@ use openshell_ocsf::{ ActionId, ActivityId, DispositionId, Endpoint, HttpActivityBuilder, HttpRequest, NetworkActivityBuilder, SeverityId, StatusId, Url as OcsfUrl, ocsf_emit, }; +#[cfg(test)] +use std::collections::BTreeMap; use std::sync::Arc; use tokio::io::{AsyncRead, AsyncWrite, AsyncWriteExt}; use tracing::{debug, warn}; @@ -202,6 +213,20 @@ where if close_if_stale(engine.generation_guard(), ctx) { return Ok(()); } + // The SQL relay is not implemented, so a matching middleware + // chain can never inspect this stream: gate it like any other + // uninspectable protocol. + let chain = engine.query_middleware_chain(&middleware_network_input(ctx))?; + match uninspectable_traffic_gate(&chain) { + UninspectableTrafficGate::Deny => { + emit_middleware_uninspectable(ctx, "sql passthrough", true); + return Ok(()); + } + UninspectableTrafficGate::BypassWithFinding => { + emit_middleware_uninspectable(ctx, "sql passthrough", false); + } + UninspectableTrafficGate::Unrestricted => {} + } // SQL provider is Phase 3 — fall through to passthrough with warning { let event = NetworkActivityBuilder::new(openshell_ocsf::ctx::ctx()) @@ -401,18 +426,9 @@ where return Ok(()); } - let parse_error_reason = graphql_info - .as_ref() - .and_then(|info| info.error.as_deref()) - .map(|error| format!("GraphQL request rejected: {error}")) - .or_else(|| { - jsonrpc_info - .as_ref() - .and_then(|info| info.error.as_ref()) - .map(crate::l7::jsonrpc::JsonRpcInspectionError::rejection_reason) - }); - let force_deny = parse_error_reason.is_some(); - let (allowed, reason) = if let Some(reason) = parse_error_reason { + let hard_deny_reason = l7_request_hard_deny_reason(config.protocol, &request_info); + let force_deny = hard_deny_reason.is_some(); + let (allowed, reason) = if let Some(reason) = hard_deny_reason { (false, reason) } else { evaluate_l7_request(&engine, ctx, &request_info)? @@ -450,6 +466,43 @@ where let _ = &eval_target; if allowed || (config.enforcement == EnforcementMode::Audit && !force_deny) { + let chain = engine.query_middleware_chain(&middleware_network_input(ctx))?; + // Route selection resolved `config` per request, so re-check the + // body against that protocol's policy after every transforming + // stage (a no-op for REST and websocket, whose policy inputs the + // chain cannot mutate). + let validate = transformed_body_validator(config, &engine, ctx, &request_info); + let req = match apply_middleware_chain( + req, + client, + ctx, + chain, + engine.middleware_runner(), + engine.generation_guard(), + openshell_supervisor_middleware::TransformedBodyPolicy::Reevaluate(&validate), + ) + .await? + { + MiddlewareApplyResult::Allowed(request) => request, + MiddlewareApplyResult::Denied { denial, .. } => { + let denied_request = crate::l7::provider::L7Request { + action: request_info.action.clone(), + target: redacted_target.clone(), + query_params: request_info.query_params.clone(), + raw_header: Vec::new(), + body_length: crate::l7::provider::BodyLength::None, + }; + crate::l7::middleware::send_middleware_rejection_response( + &denied_request, + client, + ctx, + denial.as_ref(), + &redacted_target, + ) + .await?; + return Ok(()); + } + }; let outcome = crate::l7::rest::relay_http_request_with_options_guarded( &req, client, @@ -907,6 +960,41 @@ where let _ = &eval_target; if allowed || config.enforcement == EnforcementMode::Audit { + let chain = engine.query_middleware_chain(&middleware_network_input(ctx))?; + // REST and websocket-upgrade policy evaluates only the method, + // path, and query, which a middleware result cannot mutate, so no + // per-stage body re-check is needed. + let req = match apply_middleware_chain( + req, + client, + ctx, + chain, + engine.middleware_runner(), + engine.generation_guard(), + openshell_supervisor_middleware::TransformedBodyPolicy::NotPolicyRelevant, + ) + .await? + { + MiddlewareApplyResult::Allowed(request) => request, + MiddlewareApplyResult::Denied { denial, .. } => { + let denied_request = crate::l7::provider::L7Request { + action: request_info.action.clone(), + target: redacted_target.clone(), + query_params: request_info.query_params.clone(), + raw_header: Vec::new(), + body_length: crate::l7::provider::BodyLength::None, + }; + crate::l7::middleware::send_middleware_rejection_response( + &denied_request, + client, + ctx, + denial.as_ref(), + &redacted_target, + ) + .await?; + return Ok(()); + } + }; let req_with_auth = match crate::l7::token_grant_injection::inject_if_needed(req, ctx).await { Ok(req) => req, @@ -1083,16 +1171,9 @@ where jsonrpc: Some(jsonrpc_info.clone()), }; - let parse_error_reason = jsonrpc_info - .error - .as_ref() - .map(crate::l7::jsonrpc::JsonRpcInspectionError::rejection_reason); - let response_frame_reason = - jsonrpc_response_frame_hard_deny_reason(config.protocol, &jsonrpc_info); - let force_deny = parse_error_reason.is_some() || response_frame_reason.is_some(); - let (allowed, reason, jsonrpc_log_info) = if let Some(reason) = parse_error_reason { - (false, reason, jsonrpc_info.clone()) - } else if let Some(reason) = response_frame_reason { + let hard_deny_reason = l7_request_hard_deny_reason(config.protocol, &request_info); + let force_deny = hard_deny_reason.is_some(); + let (allowed, reason, jsonrpc_log_info) = if let Some(reason) = hard_deny_reason { (false, reason, jsonrpc_info.clone()) } else { let evaluation = @@ -1146,6 +1227,43 @@ where } if allowed || (config.enforcement == EnforcementMode::Audit && !force_deny) { + let chain = engine.query_middleware_chain(&middleware_network_input(ctx))?; + // Policy admitted the original body above; re-check the body + // against the same body-aware policy after every transforming + // stage so a middleware cannot smuggle a denied operation to the + // upstream or the next stage. + let validate = transformed_body_validator(config, engine, ctx, &request_info); + let req = match apply_middleware_chain( + req, + client, + ctx, + chain, + engine.middleware_runner(), + engine.generation_guard(), + openshell_supervisor_middleware::TransformedBodyPolicy::Reevaluate(&validate), + ) + .await? + { + MiddlewareApplyResult::Allowed(request) => request, + MiddlewareApplyResult::Denied { denial, .. } => { + let denied_request = crate::l7::provider::L7Request { + action: request_info.action.clone(), + target: redacted_target.clone(), + query_params: request_info.query_params.clone(), + raw_header: Vec::new(), + body_length: crate::l7::provider::BodyLength::None, + }; + crate::l7::middleware::send_middleware_rejection_response( + &denied_request, + client, + ctx, + denial.as_ref(), + &redacted_target, + ) + .await?; + return Ok(()); + } + }; // Future MCP response/SSE introspection or rewrite would hook here // before returning upstream bytes. The current policy schema has no // trusted-annotations or version-profile field, so MCP responses and @@ -1281,12 +1399,9 @@ where // control parameters, are rejected before policy evaluation. This // keeps parser-differential cases fail-closed even if the endpoint is // otherwise in audit mode. - let parse_error_reason = graphql_info - .error - .as_deref() - .map(|error| format!("GraphQL request rejected: {error}")); - let force_deny = parse_error_reason.is_some(); - let (allowed, reason) = if let Some(reason) = parse_error_reason { + let hard_deny_reason = l7_request_hard_deny_reason(config.protocol, &request_info); + let force_deny = hard_deny_reason.is_some(); + let (allowed, reason) = if let Some(reason) = hard_deny_reason { (false, reason) } else { evaluate_l7_request(engine, ctx, &request_info)? @@ -1340,6 +1455,43 @@ where let _ = &eval_target; if allowed || (config.enforcement == EnforcementMode::Audit && !force_deny) { + let chain = engine.query_middleware_chain(&middleware_network_input(ctx))?; + // Policy admitted the original body above; re-check the body + // against the same body-aware policy after every transforming + // stage so a middleware cannot smuggle a denied operation to the + // upstream or the next stage. + let validate = transformed_body_validator(config, engine, ctx, &request_info); + let req = match apply_middleware_chain( + req, + client, + ctx, + chain, + engine.middleware_runner(), + engine.generation_guard(), + openshell_supervisor_middleware::TransformedBodyPolicy::Reevaluate(&validate), + ) + .await? + { + MiddlewareApplyResult::Allowed(request) => request, + MiddlewareApplyResult::Denied { denial, .. } => { + let denied_request = crate::l7::provider::L7Request { + action: request_info.action.clone(), + target: redacted_target.clone(), + query_params: request_info.query_params.clone(), + raw_header: Vec::new(), + body_length: crate::l7::provider::BodyLength::None, + }; + crate::l7::middleware::send_middleware_rejection_response( + &denied_request, + client, + ctx, + denial.as_ref(), + &redacted_target, + ) + .await?; + return Ok(()); + } + }; let outcome = crate::l7::rest::relay_http_request_with_resolver_guarded( &req, client, @@ -1487,6 +1639,31 @@ pub(crate) fn jsonrpc_response_frame_hard_deny_reason( .then(|| JSONRPC_RESPONSE_FRAME_DENY_REASON.to_string()) } +/// Classify malformed or protocol-invalid requests that must be denied even +/// when the selected endpoint is in audit mode. +/// +/// All HTTP entry points use this helper so dedicated relays, route-selected +/// relays, forward proxying, and post-middleware re-evaluation cannot drift on +/// hard-deny semantics. +pub(crate) fn l7_request_hard_deny_reason( + protocol: L7Protocol, + request: &L7RequestInfo, +) -> Option { + request + .graphql + .as_ref() + .and_then(|info| info.error.as_deref()) + .map(|error| format!("GraphQL request rejected: {error}")) + .or_else(|| { + request.jsonrpc.as_ref().and_then(|info| { + info.error + .as_ref() + .map(crate::l7::jsonrpc::JsonRpcInspectionError::rejection_reason) + .or_else(|| jsonrpc_response_frame_hard_deny_reason(protocol, info)) + }) + }) +} + /// Check if a miette error represents a benign connection close. /// /// TLS handshake EOF, missing `close_notify`, connection resets, and broken @@ -1611,6 +1788,130 @@ fn jsonrpc_request_for_call( item_request } +/// Re-evaluate body-aware policy against a middleware-transformed body. Policy +/// admits the original body before the chain runs, so each replaced body must +/// be checked again before the next stage or the upstream sees it: a +/// transformation cannot smuggle a denied or unparseable operation past the +/// policy. Returns the deny reason, or `None` when the transformed body is +/// admissible. An unparseable replacement or a response frame denies even +/// under audit, mirroring `force_deny` for the original body; a policy deny +/// respects the endpoint's enforcement mode. Method, path, and query come from +/// `request_info` because a middleware result cannot mutate them. +/// +/// The match is exhaustive over `L7Protocol` on purpose: adding a protocol +/// does not compile until its transformed-body re-evaluation is defined here, +/// either by re-deriving the body-dependent policy inputs or by documenting +/// why none exist. Build the per-request validator with +/// [`transformed_body_validator`]. +fn reevaluate_transformed_body( + config: &L7EndpointConfig, + engine: &TunnelPolicyEngine, + ctx: &L7EvalContext, + request_info: &L7RequestInfo, + body: &[u8], +) -> Result> { + let (engine_type, transformed_info) = match config.protocol { + // REST and websocket-upgrade policy evaluates only the method, path, + // and query, which a middleware result cannot mutate; the body is not + // a policy input. SQL has no body-aware L7 policy either; the + // uninspectable-traffic gate keeps required middleware ahead of the + // unimplemented SQL relay. + L7Protocol::Rest | L7Protocol::Websocket | L7Protocol::Sql => return Ok(None), + L7Protocol::JsonRpc | L7Protocol::Mcp => { + let info = crate::l7::jsonrpc::parse_jsonrpc_body_with_options( + body, + crate::l7::jsonrpc::JsonRpcInspectionOptions::for_config(config), + ); + let mut transformed_info = request_info.clone(); + transformed_info.jsonrpc = Some(info); + (jsonrpc_engine_type(config.protocol), transformed_info) + } + L7Protocol::Graphql => { + // GraphQL classification needs the request method and query + // params; only the body was replaced, so rebuild from + // `request_info` and the new body. + let request = crate::l7::provider::L7Request { + action: request_info.action.clone(), + target: request_info.target.clone(), + query_params: request_info.query_params.clone(), + raw_header: Vec::new(), + body_length: crate::l7::provider::BodyLength::None, + }; + let info = crate::l7::graphql::classify_request(&request, body); + let mut transformed_info = request_info.clone(); + transformed_info.graphql = Some(info); + ("l7-graphql", transformed_info) + } + }; + + if let Some(reason) = l7_request_hard_deny_reason(config.protocol, &transformed_info) { + let reason = format!("middleware transformation rejected: {reason}"); + emit_transformed_body_decision(ctx, request_info, engine_type, "deny", &reason); + return Ok(Some(reason)); + } + + let (allowed, reason) = evaluate_l7_request(engine, ctx, &transformed_info)?; + if allowed { + return Ok(None); + } + let reason = format!("middleware transformation denied by policy: {reason}"); + if config.enforcement == EnforcementMode::Audit { + emit_transformed_body_decision(ctx, request_info, engine_type, "audit", &reason); + return Ok(None); + } + emit_transformed_body_decision(ctx, request_info, engine_type, "deny", &reason); + Ok(Some(reason)) +} + +/// Build the per-stage transformed-body validator the middleware chain calls +/// after every stage that replaces the body. Borrows the policy inputs, so it +/// lives only as long as this request's evaluation. +pub(crate) fn transformed_body_validator<'a>( + config: &'a L7EndpointConfig, + engine: &'a TunnelPolicyEngine, + ctx: &'a L7EvalContext, + request_info: &'a L7RequestInfo, +) -> impl Fn(&[u8]) -> Result> + Send + Sync + 'a { + move |body: &[u8]| reevaluate_transformed_body(config, engine, ctx, request_info, body) +} + +/// Log the post-transformation policy decision as an OCSF HTTP Activity +/// event, mirroring the pre-middleware decision logs. `request_info.target` +/// is already redacted by the callers. +fn emit_transformed_body_decision( + ctx: &L7EvalContext, + request_info: &L7RequestInfo, + engine_type: &str, + decision_str: &str, + reason: &str, +) { + let (action_id, disposition_id, severity) = match decision_str { + "deny" => (ActionId::Denied, DispositionId::Blocked, SeverityId::Medium), + _ => ( + ActionId::Allowed, + DispositionId::Allowed, + SeverityId::Informational, + ), + }; + let event = HttpActivityBuilder::new(openshell_ocsf::ctx::ctx()) + .activity(ActivityId::Other) + .action(action_id) + .disposition(disposition_id) + .severity(severity) + .http_request(HttpRequest::new( + &request_info.action, + OcsfUrl::new("http", &ctx.host, &request_info.target, ctx.port), + )) + .dst_endpoint(Endpoint::from_domain(&ctx.host, ctx.port)) + .firewall_rule(&ctx.policy_name, engine_type) + .message(format!( + "L7_REQUEST_TRANSFORMED {decision_str} {} {}:{}{} reason={}", + request_info.action, ctx.host, ctx.port, request_info.target, reason + )) + .build(); + ocsf_emit!(event); +} + fn jsonrpc_policy_input(info: &crate::l7::jsonrpc::JsonRpcRequestInfo) -> serde_json::Value { let call = if info.is_batch { None @@ -1704,6 +2005,7 @@ pub async fn relay_passthrough_with_credentials( upstream: &mut U, ctx: &L7EvalContext, generation_guard: &PolicyGenerationGuard, + middleware_engine: Option<&crate::opa::OpaEngine>, ) -> Result<()> where C: AsyncRead + AsyncWrite + Unpin + Send, @@ -1786,6 +2088,50 @@ where ocsf_emit!(event); } + let req = if let Some(engine) = middleware_engine { + let input = middleware_network_input(ctx); + let (chain, generation) = engine.query_middleware_chain_with_generation(&input)?; + if generation != generation_guard.captured_generation() { + return Ok(()); + } + let runner = engine.middleware_runner()?; + // The passthrough path enforces no L7 policy, so there is no + // body-aware decision to re-check after a transformation. + match apply_middleware_chain( + req, + client, + ctx, + chain, + &runner, + generation_guard, + openshell_supervisor_middleware::TransformedBodyPolicy::NotPolicyRelevant, + ) + .await? + { + MiddlewareApplyResult::Allowed(request) => request, + MiddlewareApplyResult::Denied { denial, .. } => { + let denied_request = crate::l7::provider::L7Request { + action: "HTTP".into(), + target: redacted_target.clone(), + query_params: std::collections::HashMap::new(), + raw_header: Vec::new(), + body_length: crate::l7::provider::BodyLength::None, + }; + crate::l7::middleware::send_middleware_rejection_response( + &denied_request, + client, + ctx, + denial.as_ref(), + &redacted_target, + ) + .await?; + return Ok(()); + } + } + } else { + req + }; + let req_with_auth = match crate::l7::token_grant_injection::inject_if_needed(req, ctx).await { Ok(req) => req, @@ -1862,6 +2208,31 @@ mod tests { const TEST_POLICY: &str = include_str!("../../data/sandbox-policy.rego"); + fn install_builtin_middleware(engine: &OpaEngine) { + engine.set_middleware_runner_for_tests(openshell_supervisor_middleware::ChainRunner::new( + openshell_supervisor_middleware_builtins::services() + .into_iter() + .next() + .expect("built-in middleware service"), + )); + } + + fn assert_middleware_failure_response(response: &str, policy_name: &str) { + assert!(response.contains("403 Forbidden"), "{response}"); + let (_, body) = response.split_once("\r\n\r\n").expect("HTTP response"); + let body: serde_json::Value = serde_json::from_str(body).expect("JSON response"); + assert_eq!(body["error"], "middleware_failed"); + assert_eq!( + body["detail"], + "Request could not be processed by configured middleware" + ); + assert_eq!(body["policy"], policy_name); + assert!(body.get("rule").is_none()); + assert!(body.get("rule_missing").is_none()); + assert!(body.get("next_steps").is_none()); + assert!(body.get("agent_guidance").is_none()); + } + fn rest_token_grant_relay_context( resolver_response: std::result::Result<&str, &str>, ) -> ( @@ -1931,6 +2302,73 @@ network_policies: (config, tunnel_engine, ctx, fixture) } + fn middleware_relay_context( + middleware_impl: &str, + on_error: &str, + ) -> (L7EndpointConfig, TunnelPolicyEngine, L7EvalContext) { + middleware_relay_context_with_enforcement(middleware_impl, on_error, "enforce") + } + + fn middleware_relay_context_with_enforcement( + middleware_impl: &str, + on_error: &str, + enforcement: &str, + ) -> (L7EndpointConfig, TunnelPolicyEngine, L7EvalContext) { + let data = format!( + r#" +network_middlewares: + request-middleware: + middleware: {middleware_impl} + on_error: {on_error} + endpoints: + include: ["api.example.test"] +network_policies: + rest_api: + name: rest_api + endpoints: + - host: api.example.test + port: 8080 + protocol: rest + enforcement: {enforcement} + rules: + - allow: + method: POST + path: "/v1/**" + binaries: + - {{ path: /usr/bin/curl }} +"# + ); + let engine = OpaEngine::from_strings(TEST_POLICY, &data).unwrap(); + install_builtin_middleware(&engine); + let input = NetworkInput { + host: "api.example.test".into(), + port: 8080, + binary_path: PathBuf::from("/usr/bin/curl"), + binary_sha256: "unused".into(), + ancestors: vec![], + cmdline_paths: vec![], + }; + let (endpoint_config, generation) = engine + .query_endpoint_config_with_generation(&input) + .unwrap(); + let config = crate::l7::parse_l7_config(&endpoint_config.unwrap()).unwrap(); + let tunnel_engine = engine.clone_engine_for_tunnel(generation).unwrap(); + let ctx = L7EvalContext { + host: "api.example.test".into(), + port: 8080, + policy_name: "rest_api".into(), + binary_path: "/usr/bin/curl".into(), + ancestors: vec![], + cmdline_paths: vec![], + secret_resolver: None, + activity_tx: None, + dynamic_credentials: None, + token_grant_resolver: None, + }; + + (config, tunnel_engine, ctx) + } + fn passthrough_token_grant_relay_context( resolver_response: std::result::Result<&str, &str>, ) -> ( @@ -2142,7 +2580,10 @@ network_policies: .unwrap(); let upstream_request = String::from_utf8_lossy(&upstream_request[..n]); - assert!(upstream_request.starts_with("GET /v1/projects HTTP/1.1\r\n")); + assert!( + upstream_request.starts_with("GET /v1/projects HTTP/1.1\r\n"), + "unexpected upstream request: {upstream_request:?}" + ); assert!(upstream_request.contains("Authorization: Bearer grant-token\r\n")); assert!(!upstream_request.contains("stale-token")); assert_eq!(authorization_header_count(&upstream_request), 1); @@ -2225,26 +2666,29 @@ network_policies: } #[tokio::test] - async fn passthrough_relay_injects_token_grant_authorization_header() { - let (generation_guard, ctx, fixture) = - passthrough_token_grant_relay_context(Ok("grant-token")); + async fn l7_rest_middleware_redacts_body_before_upstream() { + let (config, tunnel_engine, ctx) = + middleware_relay_context("openshell/regex", "fail_closed"); let (mut app, mut relay_client) = tokio::io::duplex(8192); let (mut relay_upstream, mut upstream) = tokio::io::duplex(8192); let relay = tokio::spawn(async move { - relay_passthrough_with_credentials( + relay_with_inspection( + &config, + tunnel_engine, &mut relay_client, &mut relay_upstream, &ctx, - &generation_guard, ) .await }); - app.write_all( - b"GET /v1/projects HTTP/1.1\r\nHost: api.example.test\r\nAuthorization: Bearer stale-token\r\nConnection: close\r\n\r\n", - ) - .await - .unwrap(); + let body = br#"{"api_key":"sk-1234567890abcdef"}"#; + let request = format!( + "POST /v1/messages HTTP/1.1\r\nHost: api.example.test\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", + body.len(), + std::str::from_utf8(body).unwrap() + ); + app.write_all(request.as_bytes()).await.unwrap(); let mut upstream_request = [0u8; 1024]; let n = tokio::time::timeout( @@ -2255,17 +2699,13 @@ network_policies: .expect("request should reach upstream") .unwrap(); let upstream_request = String::from_utf8_lossy(&upstream_request[..n]); - - assert!(upstream_request.starts_with("GET /v1/projects HTTP/1.1\r\n")); - assert!(upstream_request.contains("Authorization: Bearer grant-token\r\n")); - assert!(!upstream_request.contains("stale-token")); - assert_eq!(authorization_header_count(&upstream_request), 1); + assert!(upstream_request.contains(r#""api_key":"[REDACTED]""#)); + assert!(!upstream_request.contains("sk-1234567890abcdef")); upstream .write_all(b"HTTP/1.1 204 No Content\r\nContent-Length: 0\r\nConnection: close\r\n\r\n") .await .unwrap(); - let mut client_response = [0u8; 512]; let n = tokio::time::timeout( std::time::Duration::from_secs(1), @@ -2276,70 +2716,1767 @@ network_policies: .unwrap(); assert!(String::from_utf8_lossy(&client_response[..n]).contains("204 No Content")); drop(app); - tokio::time::timeout(std::time::Duration::from_secs(1), relay) .await .expect("relay should finish") .unwrap() .unwrap(); - - fixture.assert_one_request("api.example.test\t8080\t/v1/**\tprovider:access_token"); } #[tokio::test] - async fn passthrough_relay_token_grant_failure_returns_bad_gateway_without_forwarding() { - let (generation_guard, ctx, fixture) = - passthrough_token_grant_relay_context(Err("oauth unavailable")); + async fn l7_rest_middleware_acknowledges_expect_continue_before_reading_body() { + let (config, tunnel_engine, ctx) = + middleware_relay_context("openshell/regex", "fail_closed"); let (mut app, mut relay_client) = tokio::io::duplex(8192); let (mut relay_upstream, mut upstream) = tokio::io::duplex(8192); let relay = tokio::spawn(async move { - relay_passthrough_with_credentials( + relay_with_inspection( + &config, + tunnel_engine, &mut relay_client, &mut relay_upstream, &ctx, - &generation_guard, ) .await }); - app.write_all( - b"GET /v1/projects HTTP/1.1\r\nHost: api.example.test\r\nConnection: close\r\n\r\n", - ) - .await - .unwrap(); + let body = br#"{"api_key":"sk-1234567890abcdef"}"#; + let headers = format!( + "POST /v1/messages HTTP/1.1\r\nHost: api.example.test\r\nContent-Length: {}\r\nExpect: 100-continue\r\nConnection: close\r\n\r\n", + body.len() + ); + app.write_all(headers.as_bytes()).await.unwrap(); - tokio::time::timeout(std::time::Duration::from_secs(1), relay) + let mut interim = [0u8; 64]; + let n = tokio::time::timeout(std::time::Duration::from_secs(1), app.read(&mut interim)) .await - .expect("relay should finish") - .unwrap() + .expect("middleware buffering should acknowledge Expect before reading the body") .unwrap(); + assert_eq!(&interim[..n], b"HTTP/1.1 100 Continue\r\n\r\n"); - let mut client_response = [0u8; 512]; + app.write_all(body).await.unwrap(); + + let mut upstream_request = [0u8; 1024]; let n = tokio::time::timeout( std::time::Duration::from_secs(1), - app.read(&mut client_response), + upstream.read(&mut upstream_request), ) .await - .expect("bad gateway response should reach client") + .expect("request should reach upstream after the body is released") .unwrap(); - assert!(String::from_utf8_lossy(&client_response[..n]).contains("502 Bad Gateway")); + let upstream_request = String::from_utf8_lossy(&upstream_request[..n]); + assert!(upstream_request.contains(r#""api_key":"[REDACTED]""#)); + assert!(!upstream_request.contains("Expect: 100-continue")); - let mut upstream_request = [0u8; 128]; + upstream + .write_all(b"HTTP/1.1 204 No Content\r\nContent-Length: 0\r\nConnection: close\r\n\r\n") + .await + .unwrap(); + let mut client_response = [0u8; 512]; let n = tokio::time::timeout( std::time::Duration::from_secs(1), - upstream.read(&mut upstream_request), + app.read(&mut client_response), ) .await - .expect("upstream should close without forwarded data") + .expect("response should reach client") .unwrap(); - assert_eq!(n, 0, "unauthenticated request must not reach upstream"); - - fixture.assert_one_request("api.example.test\t8080\t/v1/**\tprovider:access_token"); - } - - #[test] - fn websocket_text_policy_requires_explicit_message_rule() { - let data = r#" + assert!(String::from_utf8_lossy(&client_response[..n]).contains("204 No Content")); + drop(app); + tokio::time::timeout(std::time::Duration::from_secs(1), relay) + .await + .expect("relay should finish") + .unwrap() + .unwrap(); + } + + #[tokio::test] + async fn l7_rest_middleware_fail_closed_does_not_reach_upstream() { + let (config, tunnel_engine, ctx) = + middleware_relay_context("example/unavailable", "fail_closed"); + let (mut app, mut relay_client) = tokio::io::duplex(8192); + let (mut relay_upstream, mut upstream) = tokio::io::duplex(8192); + let relay = tokio::spawn(async move { + relay_with_inspection( + &config, + tunnel_engine, + &mut relay_client, + &mut relay_upstream, + &ctx, + ) + .await + }); + + app.write_all( + b"POST /v1/messages HTTP/1.1\r\nHost: api.example.test\r\nContent-Length: 2\r\nConnection: close\r\n\r\n{}", + ) + .await + .unwrap(); + + let mut response = [0u8; 512]; + let n = tokio::time::timeout(std::time::Duration::from_secs(1), app.read(&mut response)) + .await + .expect("denial should reach client") + .unwrap(); + let response = String::from_utf8_lossy(&response[..n]); + assert!(response.contains("403 Forbidden")); + let (_, body) = response.split_once("\r\n\r\n").expect("HTTP response"); + let body: serde_json::Value = serde_json::from_str(body).expect("JSON response"); + assert_eq!(body["error"], "middleware_failed"); + assert_eq!( + body["detail"], + "Request could not be processed by configured middleware" + ); + assert_eq!(body["policy"], "rest_api"); + assert!(body.get("rule").is_none()); + assert!(body.get("rule_missing").is_none()); + assert!(body.get("next_steps").is_none()); + assert!(body.get("agent_guidance").is_none()); + + let mut upstream_request = [0u8; 32]; + let result = tokio::time::timeout( + std::time::Duration::from_millis(100), + upstream.read(&mut upstream_request), + ) + .await; + assert!( + matches!(result, Err(_) | Ok(Ok(0))), + "upstream should not receive request bytes" + ); + + drop(app); + tokio::time::timeout(std::time::Duration::from_secs(1), relay) + .await + .expect("relay should finish") + .unwrap() + .unwrap(); + } + + #[tokio::test] + async fn audit_endpoint_forwards_policy_denied_request_through_healthy_chain() { + // Baseline for audit semantics: a request the L7 policy denies is + // still forwarded on an `enforcement: audit` endpoint when the + // middleware chain is healthy and allows it. + let (config, tunnel_engine, ctx) = + middleware_relay_context_with_enforcement("openshell/regex", "fail_closed", "audit"); + let (mut app, mut relay_client) = tokio::io::duplex(8192); + let (mut relay_upstream, mut upstream) = tokio::io::duplex(8192); + let relay = tokio::spawn(async move { + relay_with_inspection( + &config, + tunnel_engine, + &mut relay_client, + &mut relay_upstream, + &ctx, + ) + .await + }); + + app.write_all( + b"GET /other HTTP/1.1\r\nHost: api.example.test\r\nConnection: close\r\n\r\n", + ) + .await + .unwrap(); + + let mut upstream_request = [0u8; 512]; + let n = tokio::time::timeout( + std::time::Duration::from_secs(1), + upstream.read(&mut upstream_request), + ) + .await + .expect("audited request should reach upstream") + .unwrap(); + assert!(String::from_utf8_lossy(&upstream_request[..n]).starts_with("GET /other")); + + upstream + .write_all(b"HTTP/1.1 204 No Content\r\nContent-Length: 0\r\nConnection: close\r\n\r\n") + .await + .unwrap(); + let mut client_response = [0u8; 512]; + let n = tokio::time::timeout( + std::time::Duration::from_secs(1), + app.read(&mut client_response), + ) + .await + .expect("response should reach client") + .unwrap(); + assert!(String::from_utf8_lossy(&client_response[..n]).contains("204 No Content")); + drop(app); + tokio::time::timeout(std::time::Duration::from_secs(1), relay) + .await + .expect("relay should finish") + .unwrap() + .unwrap(); + } + + #[tokio::test] + async fn audit_endpoint_still_enforces_middleware_deny() { + // `enforcement: audit` applies to the endpoint's L7 policy rules, not + // to middleware: a middleware deny (here a fail-closed failure) must + // block with 403 even though the same request would be forwarded + // under audit with a healthy chain. + let (config, tunnel_engine, ctx) = middleware_relay_context_with_enforcement( + "example/unavailable", + "fail_closed", + "audit", + ); + let (mut app, mut relay_client) = tokio::io::duplex(8192); + let (mut relay_upstream, mut upstream) = tokio::io::duplex(8192); + let relay = tokio::spawn(async move { + relay_with_inspection( + &config, + tunnel_engine, + &mut relay_client, + &mut relay_upstream, + &ctx, + ) + .await + }); + + app.write_all( + b"GET /other HTTP/1.1\r\nHost: api.example.test\r\nConnection: close\r\n\r\n", + ) + .await + .unwrap(); + + let mut response = [0u8; 512]; + let n = tokio::time::timeout(std::time::Duration::from_secs(1), app.read(&mut response)) + .await + .expect("denial should reach client") + .unwrap(); + let response = String::from_utf8_lossy(&response[..n]); + assert!(response.contains("403 Forbidden")); + assert!(response.contains("middleware_failed")); + + let mut upstream_request = [0u8; 32]; + let result = tokio::time::timeout( + std::time::Duration::from_millis(100), + upstream.read(&mut upstream_request), + ) + .await; + assert!( + matches!(result, Err(_) | Ok(Ok(0))), + "upstream should not receive request bytes" + ); + + drop(app); + tokio::time::timeout(std::time::Duration::from_secs(1), relay) + .await + .expect("relay should finish") + .unwrap() + .unwrap(); + } + + #[tokio::test] + async fn jsonrpc_middleware_fail_closed_does_not_reach_upstream() { + let data = r#" +network_middlewares: + request-middleware: + middleware: example/unavailable + on_error: fail_closed + endpoints: + include: ["api.example.test"] +network_policies: + jsonrpc_api: + name: jsonrpc_api + endpoints: + - host: api.example.test + port: 443 + protocol: json-rpc + enforcement: enforce + rules: + - allow: + method: reports.list + binaries: + - { path: /usr/bin/node } +"#; + let engine = OpaEngine::from_strings(TEST_POLICY, data).unwrap(); + let input = NetworkInput { + host: "api.example.test".into(), + port: 443, + binary_path: PathBuf::from("/usr/bin/node"), + binary_sha256: "unused".into(), + ancestors: vec![], + cmdline_paths: vec![], + }; + let (endpoint_config, generation) = engine + .query_endpoint_config_with_generation(&input) + .expect("endpoint config"); + let config = crate::l7::parse_l7_config(&endpoint_config.expect("json-rpc config")) + .expect("parse JSON-RPC config"); + let tunnel_engine = engine.clone_engine_for_tunnel(generation).unwrap(); + let ctx = L7EvalContext { + host: "api.example.test".into(), + port: 443, + policy_name: "jsonrpc_api".into(), + binary_path: "/usr/bin/node".into(), + ancestors: vec![], + cmdline_paths: vec![], + secret_resolver: None, + activity_tx: None, + dynamic_credentials: None, + token_grant_resolver: None, + }; + let (mut app, mut relay_client) = tokio::io::duplex(8192); + let (mut relay_upstream, mut upstream) = tokio::io::duplex(8192); + let relay = tokio::spawn(async move { + relay_jsonrpc( + &config, + &tunnel_engine, + &mut relay_client, + &mut relay_upstream, + &ctx, + ) + .await + }); + + let body = br#"{"jsonrpc":"2.0","id":1,"method":"reports.list"}"#; + let request = format!( + "POST /rpc HTTP/1.1\r\nHost: api.example.test\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", + body.len(), + std::str::from_utf8(body).unwrap() + ); + app.write_all(request.as_bytes()).await.unwrap(); + + let mut response = [0u8; 512]; + let n = tokio::time::timeout(std::time::Duration::from_secs(1), app.read(&mut response)) + .await + .expect("denial should reach client") + .unwrap(); + let response = String::from_utf8_lossy(&response[..n]); + assert!(response.contains("403 Forbidden")); + assert!(response.contains("middleware_failed")); + + let mut upstream_request = [0u8; 32]; + let result = tokio::time::timeout( + std::time::Duration::from_millis(100), + upstream.read(&mut upstream_request), + ) + .await; + assert!( + matches!(result, Err(_) | Ok(Ok(0))), + "upstream should not receive request bytes" + ); + + drop(app); + tokio::time::timeout(std::time::Duration::from_secs(1), relay) + .await + .expect("relay should finish") + .unwrap() + .unwrap(); + } + + #[tokio::test] + async fn l7_rest_middleware_over_capacity_fails_closed() { + let (config, tunnel_engine, ctx) = + middleware_relay_context("openshell/regex", "fail_closed"); + let (mut app, mut relay_client) = tokio::io::duplex(8192); + let (mut relay_upstream, mut upstream) = tokio::io::duplex(8192); + let relay = tokio::spawn(async move { + relay_with_inspection( + &config, + tunnel_engine, + &mut relay_client, + &mut relay_upstream, + &ctx, + ) + .await + }); + + // A declared body far above the 256 KiB inspection cap must be denied + // (fail-closed) before the body is read or reaches the upstream. + let request = format!( + "POST /v1/messages HTTP/1.1\r\nHost: api.example.test\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", + 300 * 1024 + ); + app.write_all(request.as_bytes()).await.unwrap(); + + let mut response = [0u8; 512]; + let n = tokio::time::timeout(std::time::Duration::from_secs(1), app.read(&mut response)) + .await + .expect("denial should reach client") + .unwrap(); + let response = String::from_utf8_lossy(&response[..n]); + assert_middleware_failure_response(&response, "rest_api"); + + let mut upstream_request = [0u8; 32]; + let result = tokio::time::timeout( + std::time::Duration::from_millis(100), + upstream.read(&mut upstream_request), + ) + .await; + assert!( + matches!(result, Err(_) | Ok(Ok(0))), + "upstream should not receive request bytes" + ); + + drop(app); + tokio::time::timeout(std::time::Duration::from_secs(1), relay) + .await + .expect("relay should finish") + .unwrap() + .unwrap(); + } + + #[tokio::test] + async fn over_capacity_resolution_honors_on_error() { + use openshell_supervisor_middleware::{ChainEntry, OnError}; + + let ctx = L7EvalContext { + host: "api.example.test".into(), + port: 443, + policy_name: "p".into(), + binary_path: "/usr/bin/curl".into(), + ancestors: vec![], + cmdline_paths: vec![], + secret_resolver: None, + activity_tx: None, + dynamic_credentials: None, + token_grant_resolver: None, + }; + let req = || crate::l7::provider::L7Request { + action: "POST".into(), + target: "/v1".into(), + query_params: std::collections::HashMap::new(), + raw_header: Vec::new(), + body_length: crate::l7::provider::BodyLength::None, + }; + let fail_open = ChainEntry { + name: "m".into(), + implementation: "openshell/regex".into(), + order: 0, + config: prost_types::Struct::default(), + on_error: OnError::FailOpen, + }; + let fail_closed = ChainEntry { + on_error: OnError::FailClosed, + ..fail_open.clone() + }; + + let runner = openshell_supervisor_middleware::ChainRunner::default(); + let open_chain = runner + .describe_chain(std::slice::from_ref(&fail_open)) + .await + .expect("describe fail-open chain"); + let mixed_chain = runner + .describe_chain(&[fail_open.clone(), fail_closed]) + .await + .expect("describe mixed chain"); + + // Recoverable (Content-Length over cap, nothing consumed) + all fail-open + // -> stream through unprocessed. + assert!(matches!( + resolve_unbuffered_body(&ctx, req(), &open_chain, true), + MiddlewareApplyResult::Allowed(_) + )); + // Any fail-closed entry -> deny. + assert!(matches!( + resolve_unbuffered_body(&ctx, req(), &mixed_chain, true), + MiddlewareApplyResult::Denied { .. } + )); + // Not recoverable (chunked overflow already consumed bytes) -> deny even + // when every entry is fail-open. + assert!(matches!( + resolve_unbuffered_body(&ctx, req(), &open_chain, false), + MiddlewareApplyResult::Denied { .. } + )); + } + + #[tokio::test] + async fn body_limit_ignores_unresolved_entries() { + use openshell_supervisor_middleware::{ChainEntry, ChainRunner, OnError}; + + let resolved = ChainEntry { + name: "redact".into(), + implementation: openshell_supervisor_middleware_builtins::BUILTIN_REGEX.into(), + order: 0, + config: prost_types::Struct::default(), + on_error: OnError::FailClosed, + }; + let unresolved = ChainEntry { + name: "missing".into(), + implementation: "third-party/missing".into(), + order: 0, + config: prost_types::Struct::default(), + on_error: OnError::FailOpen, + }; + + // A single unresolved (0-limit) entry must not drag the chain limit to + // zero: the buffer limit reflects only the resolved built-in. + let mixed = ChainRunner::new( + openshell_supervisor_middleware_builtins::services() + .into_iter() + .next() + .expect("built-in middleware service"), + ) + .describe_chain(&[resolved, unresolved.clone()]) + .await + .expect("describe mixed chain"); + assert_eq!(middleware_chain_body_limit(&mixed), Some(256 * 1024)); + + // When nothing resolves, there is no body limit and the caller skips + // buffering entirely. + let none = ChainRunner::default() + .describe_chain(std::slice::from_ref(&unresolved)) + .await + .expect("describe unresolved chain"); + assert_eq!(middleware_chain_body_limit(&none), None); + } + + /// A middleware service whose single binding replaces every request body + /// with a fixed payload, for exercising post-transformation policy + /// re-evaluation. + struct BodyReplacingService { + replacement: &'static [u8], + } + + #[tonic::async_trait] + impl openshell_core::proto::middleware::v1::supervisor_middleware_server::SupervisorMiddleware + for BodyReplacingService + { + async fn describe( + &self, + _request: tonic::Request<()>, + ) -> std::result::Result< + tonic::Response, + tonic::Status, + > { + Ok(tonic::Response::new( + openshell_core::proto::MiddlewareManifest { + name: "test/rewriter".into(), + service_version: "test".into(), + bindings: vec![openshell_core::proto::MiddlewareBinding { + operation: openshell_core::proto::SupervisorMiddlewareOperation::HttpRequest + as i32, + phase: openshell_core::proto::SupervisorMiddlewarePhase::PreCredentials + as i32, + max_body_bytes: 8192, + timeout: String::new(), + }], + }, + )) + } + + async fn validate_config( + &self, + _request: tonic::Request, + ) -> std::result::Result< + tonic::Response, + tonic::Status, + > { + Ok(tonic::Response::new( + openshell_core::proto::ValidateConfigResponse { + valid: true, + reason: String::new(), + }, + )) + } + + async fn evaluate_http_request( + &self, + _request: tonic::Request, + ) -> std::result::Result< + tonic::Response, + tonic::Status, + > { + Ok(tonic::Response::new( + openshell_core::proto::HttpRequestResult { + decision: openshell_core::proto::Decision::Allow as i32, + body: self.replacement.to_vec(), + has_body: true, + ..Default::default() + }, + )) + } + } + + fn jsonrpc_transforming_relay_parts( + enforcement: &str, + replacement: &'static [u8], + ) -> (L7EndpointConfig, TunnelPolicyEngine, L7EvalContext) { + let data = format!( + r#" +network_middlewares: + rewriter: + middleware: test/rewriter + on_error: fail_closed + endpoints: + include: ["api.example.test"] +network_policies: + jsonrpc_api: + name: jsonrpc_api + endpoints: + - host: api.example.test + port: 443 + protocol: json-rpc + enforcement: {enforcement} + rules: + - allow: + method: reports.list + binaries: + - {{ path: /usr/bin/node }} +"# + ); + let engine = OpaEngine::from_strings(TEST_POLICY, &data).unwrap(); + engine.set_middleware_runner_for_tests(openshell_supervisor_middleware::ChainRunner::new( + Arc::new(BodyReplacingService { replacement }), + )); + let input = NetworkInput { + host: "api.example.test".into(), + port: 443, + binary_path: PathBuf::from("/usr/bin/node"), + binary_sha256: "unused".into(), + ancestors: vec![], + cmdline_paths: vec![], + }; + let (endpoint_config, generation) = engine + .query_endpoint_config_with_generation(&input) + .expect("endpoint config"); + let config = crate::l7::parse_l7_config(&endpoint_config.expect("json-rpc config")) + .expect("parse JSON-RPC config"); + let tunnel_engine = engine.clone_engine_for_tunnel(generation).unwrap(); + let ctx = L7EvalContext { + host: "api.example.test".into(), + port: 443, + policy_name: "jsonrpc_api".into(), + binary_path: "/usr/bin/node".into(), + ancestors: vec![], + cmdline_paths: vec![], + secret_resolver: None, + activity_tx: None, + dynamic_credentials: None, + token_grant_resolver: None, + }; + (config, tunnel_engine, ctx) + } + + async fn run_jsonrpc_transform_case( + enforcement: &str, + replacement: &'static [u8], + ) -> (String, Option) { + let (config, tunnel_engine, ctx) = + jsonrpc_transforming_relay_parts(enforcement, replacement); + let (mut app, mut relay_client) = tokio::io::duplex(8192); + let (mut relay_upstream, mut upstream) = tokio::io::duplex(8192); + let relay = tokio::spawn(async move { + relay_jsonrpc( + &config, + &tunnel_engine, + &mut relay_client, + &mut relay_upstream, + &ctx, + ) + .await + }); + + let body = br#"{"jsonrpc":"2.0","id":1,"method":"reports.list"}"#; + let request = format!( + "POST /rpc HTTP/1.1\r\nHost: api.example.test\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", + body.len(), + std::str::from_utf8(body).unwrap() + ); + app.write_all(request.as_bytes()).await.unwrap(); + + // Give the relay a moment to either deny (client sees a response) or + // forward (upstream sees the request). + let mut upstream_request = [0u8; 1024]; + let upstream_read = tokio::time::timeout( + std::time::Duration::from_millis(300), + upstream.read(&mut upstream_request), + ) + .await; + let upstream_seen = match upstream_read { + Ok(Ok(n)) if n > 0 => { + let seen = String::from_utf8_lossy(&upstream_request[..n]).to_string(); + upstream + .write_all( + b"HTTP/1.1 204 No Content\r\nContent-Length: 0\r\nConnection: close\r\n\r\n", + ) + .await + .unwrap(); + Some(seen) + } + _ => None, + }; + + let mut response = [0u8; 1024]; + let n = tokio::time::timeout(std::time::Duration::from_secs(1), app.read(&mut response)) + .await + .expect("client should receive a response") + .unwrap(); + let response = String::from_utf8_lossy(&response[..n]).to_string(); + + drop(app); + tokio::time::timeout(std::time::Duration::from_secs(1), relay) + .await + .expect("relay should finish") + .unwrap() + .unwrap(); + (response, upstream_seen) + } + + #[tokio::test] + async fn transformed_jsonrpc_body_is_reevaluated_and_denied() { + // Policy allows reports.list; the middleware replaces the body with a + // method the policy denies. The transformed body must be re-evaluated + // and the request denied before anything reaches the upstream. + let (response, upstream_seen) = run_jsonrpc_transform_case( + "enforce", + br#"{"jsonrpc":"2.0","id":1,"method":"admin.delete"}"#, + ) + .await; + assert_middleware_failure_response(&response, "jsonrpc_api"); + assert!(upstream_seen.is_none(), "upstream must not see the request"); + } + + #[tokio::test] + async fn transformed_jsonrpc_body_policy_deny_forwards_under_audit() { + // Under enforcement: audit a policy deny of the transformed body is + // logged but forwarded, mirroring audit semantics for original + // bodies. + let (response, upstream_seen) = run_jsonrpc_transform_case( + "audit", + br#"{"jsonrpc":"2.0","id":1,"method":"admin.delete"}"#, + ) + .await; + assert!(response.contains("204 No Content"), "{response}"); + let upstream_seen = upstream_seen.expect("audited request reaches upstream"); + assert!(upstream_seen.contains("admin.delete"), "{upstream_seen}"); + } + + #[tokio::test] + async fn unparseable_transformation_denies_even_under_audit() { + // An unparseable replacement mirrors force_deny for original parse + // errors: denied even on an audit endpoint. + let (response, upstream_seen) = run_jsonrpc_transform_case("audit", b"not json").await; + assert_middleware_failure_response(&response, "jsonrpc_api"); + assert!(upstream_seen.is_none(), "upstream must not see the request"); + } + + #[tokio::test] + async fn transformed_graphql_body_is_reevaluated_and_denied() { + // GraphQL counterpart: policy allows query { viewer }; the middleware + // rewrites the body into a denied mutation. + let data = r#" +network_middlewares: + rewriter: + middleware: test/rewriter + on_error: fail_closed + endpoints: + include: ["api.example.test"] +network_policies: + graphql_api: + name: graphql_api + endpoints: + - host: api.example.test + port: 443 + protocol: graphql + enforcement: enforce + rules: + - allow: + operation_type: query + fields: [viewer] + binaries: + - { path: /usr/bin/node } +"#; + let engine = OpaEngine::from_strings(TEST_POLICY, data).unwrap(); + engine.set_middleware_runner_for_tests(openshell_supervisor_middleware::ChainRunner::new( + Arc::new(BodyReplacingService { + replacement: br#"{"query":"mutation { deleteRepository }"}"#, + }), + )); + let input = NetworkInput { + host: "api.example.test".into(), + port: 443, + binary_path: PathBuf::from("/usr/bin/node"), + binary_sha256: "unused".into(), + ancestors: vec![], + cmdline_paths: vec![], + }; + let (endpoint_config, generation) = engine + .query_endpoint_config_with_generation(&input) + .expect("endpoint config"); + let config = crate::l7::parse_l7_config(&endpoint_config.expect("graphql config")) + .expect("parse GraphQL config"); + let tunnel_engine = engine.clone_engine_for_tunnel(generation).unwrap(); + let ctx = L7EvalContext { + host: "api.example.test".into(), + port: 443, + policy_name: "graphql_api".into(), + binary_path: "/usr/bin/node".into(), + ancestors: vec![], + cmdline_paths: vec![], + secret_resolver: None, + activity_tx: None, + dynamic_credentials: None, + token_grant_resolver: None, + }; + let (mut app, mut relay_client) = tokio::io::duplex(8192); + let (mut relay_upstream, mut upstream) = tokio::io::duplex(8192); + let relay = tokio::spawn(async move { + relay_graphql( + &config, + &tunnel_engine, + &mut relay_client, + &mut relay_upstream, + &ctx, + ) + .await + }); + + let body = br#"{"query":"query { viewer }"}"#; + let request = format!( + "POST /graphql HTTP/1.1\r\nHost: api.example.test\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", + body.len(), + std::str::from_utf8(body).unwrap() + ); + app.write_all(request.as_bytes()).await.unwrap(); + + let mut response = [0u8; 1024]; + let n = tokio::time::timeout(std::time::Duration::from_secs(1), app.read(&mut response)) + .await + .expect("denial should reach client") + .unwrap(); + let response = String::from_utf8_lossy(&response[..n]); + assert_middleware_failure_response(&response, "graphql_api"); + + let mut upstream_request = [0u8; 32]; + let result = tokio::time::timeout( + std::time::Duration::from_millis(100), + upstream.read(&mut upstream_request), + ) + .await; + assert!( + matches!(result, Err(_) | Ok(Ok(0))), + "upstream should not receive request bytes" + ); + + drop(app); + tokio::time::timeout(std::time::Duration::from_secs(1), relay) + .await + .expect("relay should finish") + .unwrap() + .unwrap(); + } + + fn sql_middleware_relay_context( + on_error: &str, + ) -> (L7EndpointConfig, TunnelPolicyEngine, L7EvalContext) { + let data = format!( + r#" +network_middlewares: + guard: + middleware: example/unavailable + on_error: {on_error} + endpoints: + include: ["db.example.test"] +network_policies: + sql_db: + name: sql_db + endpoints: + - host: db.example.test + port: 5432 + protocol: sql + enforcement: audit + rules: + - allow: + command: SELECT + binaries: + - {{ path: /usr/bin/psql }} +"# + ); + let engine = OpaEngine::from_strings(TEST_POLICY, &data).unwrap(); + let input = NetworkInput { + host: "db.example.test".into(), + port: 5432, + binary_path: PathBuf::from("/usr/bin/psql"), + binary_sha256: "unused".into(), + ancestors: vec![], + cmdline_paths: vec![], + }; + let (endpoint_config, generation) = engine + .query_endpoint_config_with_generation(&input) + .expect("endpoint config"); + let config = crate::l7::parse_l7_config(&endpoint_config.expect("sql config")) + .expect("parse SQL config"); + let tunnel_engine = engine.clone_engine_for_tunnel(generation).unwrap(); + let ctx = L7EvalContext { + host: "db.example.test".into(), + port: 5432, + policy_name: "sql_db".into(), + binary_path: "/usr/bin/psql".into(), + ancestors: vec![], + cmdline_paths: vec![], + secret_resolver: None, + activity_tx: None, + dynamic_credentials: None, + token_grant_resolver: None, + }; + (config, tunnel_engine, ctx) + } + + #[tokio::test] + async fn sql_passthrough_denies_with_fail_closed_middleware() { + // The SQL relay is unimplemented, so a fail-closed chain can never + // inspect the stream: the connection must be closed instead of + // silently bypassing the middleware. + let (config, tunnel_engine, ctx) = sql_middleware_relay_context("fail_closed"); + let (mut app, mut relay_client) = tokio::io::duplex(8192); + let (mut relay_upstream, mut upstream) = tokio::io::duplex(8192); + let relay = tokio::spawn(async move { + relay_with_inspection( + &config, + tunnel_engine, + &mut relay_client, + &mut relay_upstream, + &ctx, + ) + .await + }); + + app.write_all(b"\x00\x00\x00\x08\x04\xd2\x16\x2f") + .await + .ok(); + + tokio::time::timeout(std::time::Duration::from_secs(1), relay) + .await + .expect("relay should close the connection") + .unwrap() + .unwrap(); + + let mut upstream_bytes = [0u8; 16]; + let result = tokio::time::timeout( + std::time::Duration::from_millis(100), + upstream.read(&mut upstream_bytes), + ) + .await; + assert!( + matches!(result, Err(_) | Ok(Ok(0))), + "upstream should not receive SQL bytes" + ); + } + + #[tokio::test] + async fn sql_passthrough_relays_with_fail_open_middleware() { + // An all-fail-open chain accepts the bypass (with a detection + // finding) and the raw stream flows. + let (config, tunnel_engine, ctx) = sql_middleware_relay_context("fail_open"); + let (mut app, mut relay_client) = tokio::io::duplex(8192); + let (mut relay_upstream, mut upstream) = tokio::io::duplex(8192); + let _relay = tokio::spawn(async move { + relay_with_inspection( + &config, + tunnel_engine, + &mut relay_client, + &mut relay_upstream, + &ctx, + ) + .await + }); + + app.write_all(b"\x00\x00\x00\x08\x04\xd2\x16\x2f") + .await + .unwrap(); + + let mut upstream_bytes = [0u8; 16]; + let n = tokio::time::timeout( + std::time::Duration::from_secs(1), + upstream.read(&mut upstream_bytes), + ) + .await + .expect("fail-open chain must relay SQL bytes") + .unwrap(); + assert_eq!(&upstream_bytes[..n], b"\x00\x00\x00\x08\x04\xd2\x16\x2f"); + } + + #[test] + fn uninspectable_gate_reflects_chain_on_error() { + use openshell_supervisor_middleware::{ChainEntry, OnError}; + + let entry = |on_error| ChainEntry { + name: "m".into(), + implementation: "example/guard".into(), + order: 0, + config: prost_types::Struct::default(), + on_error, + }; + + assert_eq!( + uninspectable_traffic_gate(&[]), + UninspectableTrafficGate::Unrestricted + ); + assert_eq!( + uninspectable_traffic_gate(&[entry(OnError::FailOpen), entry(OnError::FailOpen)]), + UninspectableTrafficGate::BypassWithFinding + ); + assert_eq!( + uninspectable_traffic_gate(&[entry(OnError::FailOpen), entry(OnError::FailClosed)]), + UninspectableTrafficGate::Deny + ); + } + + /// One named middleware with one HTTP/pre-credentials binding. Two + /// instances exercise mixed-limit chain buffering at the relay level. + struct LimitService { + name: &'static str, + max_body_bytes: u64, + replacement: Option<&'static [u8]>, + } + + #[tonic::async_trait] + impl openshell_core::proto::middleware::v1::supervisor_middleware_server::SupervisorMiddleware + for LimitService + { + async fn describe( + &self, + _request: tonic::Request<()>, + ) -> std::result::Result< + tonic::Response, + tonic::Status, + > { + use openshell_core::proto::{ + MiddlewareBinding, MiddlewareManifest, SupervisorMiddlewareOperation, + SupervisorMiddlewarePhase, + }; + Ok(tonic::Response::new(MiddlewareManifest { + name: self.name.into(), + service_version: "test".into(), + bindings: vec![MiddlewareBinding { + operation: SupervisorMiddlewareOperation::HttpRequest as i32, + phase: SupervisorMiddlewarePhase::PreCredentials as i32, + max_body_bytes: self.max_body_bytes, + timeout: String::new(), + }], + })) + } + + async fn validate_config( + &self, + _request: tonic::Request, + ) -> std::result::Result< + tonic::Response, + tonic::Status, + > { + Ok(tonic::Response::new( + openshell_core::proto::ValidateConfigResponse { + valid: true, + reason: String::new(), + }, + )) + } + + async fn evaluate_http_request( + &self, + request: tonic::Request, + ) -> std::result::Result< + tonic::Response, + tonic::Status, + > { + let _evaluation = request.into_inner(); + let mut result = openshell_core::proto::HttpRequestResult { + decision: openshell_core::proto::Decision::Allow as i32, + ..Default::default() + }; + if let Some(replacement) = self.replacement { + result.body = replacement.to_vec(); + result.has_body = true; + } + Ok(tonic::Response::new(result)) + } + } + + #[tokio::test] + async fn body_over_smallest_stage_limit_is_buffered_and_evaluated() { + use openshell_supervisor_middleware::{ChainEntry, ChainRunner, OnError}; + + // A 64-byte body exceeds the 16-byte guard limit but fits the 8 KiB + // redactor. The chain must buffer for its largest stage so the + // redactor runs and replaces the body, while the undersized fail-open + // guard is skipped through its own on_error, instead of the whole + // chain taking the unbuffered over-capacity path. + let (_config, tunnel_engine, ctx) = + middleware_relay_context("openshell/regex", "fail_closed"); + let registry = openshell_supervisor_middleware::MiddlewareRegistry::connect_services( + vec![ + Arc::new(LimitService { + name: "test/redactor", + max_body_bytes: 8192, + replacement: Some(b"[SCRUBBED BY TEST REDACTOR]"), + }), + Arc::new(LimitService { + name: "test/guard", + max_body_bytes: 16, + replacement: None, + }), + ], + Vec::new(), + ) + .await + .expect("connect named middleware services"); + let runner = ChainRunner::from_registry(registry); + let chain = vec![ + ChainEntry { + name: "redact".into(), + implementation: "test/redactor".into(), + order: 0, + config: prost_types::Struct::default(), + on_error: OnError::FailClosed, + }, + ChainEntry { + name: "guard".into(), + implementation: "test/guard".into(), + order: 10, + config: prost_types::Struct::default(), + on_error: OnError::FailOpen, + }, + ]; + let described = runner.describe_chain(&chain).await.expect("describe chain"); + assert_eq!(middleware_chain_body_limit(&described), Some(8192)); + + let body = [b'a'; 64]; + let raw_header = format!( + "POST /v1/messages HTTP/1.1\r\nHost: api.example.test\r\nContent-Length: {}\r\n\r\n", + body.len() + ); + let req = crate::l7::provider::L7Request { + action: "POST".into(), + target: "/v1/messages".into(), + query_params: std::collections::HashMap::new(), + raw_header: raw_header.into_bytes(), + body_length: crate::l7::provider::BodyLength::ContentLength(body.len() as u64), + }; + let (mut app, mut relay_client) = tokio::io::duplex(8192); + app.write_all(&body).await.unwrap(); + + let result = crate::l7::middleware::apply_middleware_chain_for_scheme( + req, + &mut relay_client, + &ctx, + "https", + chain, + &runner, + tunnel_engine.generation_guard(), + openshell_supervisor_middleware::TransformedBodyPolicy::NotPolicyRelevant, + ) + .await + .expect("apply middleware chain"); + + match result { + MiddlewareApplyResult::Allowed(rebuilt) => { + let raw = String::from_utf8(rebuilt.raw_header).expect("utf8 request"); + assert!( + raw.ends_with("[SCRUBBED BY TEST REDACTOR]"), + "redactor must replace the body: {raw}" + ); + } + MiddlewareApplyResult::Denied { .. } => { + panic!("body within the largest stage limit must not fail the chain") + } + } + } + + #[tokio::test] + async fn all_unresolved_fail_open_forwards_body_unbuffered() { + // A chain whose only entry is an unregistered binding has no resolvable + // body limit. Under fail_open the request must pass through with its + // body intact rather than being denied over a phantom zero-byte cap. + let (config, tunnel_engine, ctx) = + middleware_relay_context("third-party/missing", "fail_open"); + let (mut app, mut relay_client) = tokio::io::duplex(8192); + let (mut relay_upstream, mut upstream) = tokio::io::duplex(8192); + let relay = tokio::spawn(async move { + relay_with_inspection( + &config, + tunnel_engine, + &mut relay_client, + &mut relay_upstream, + &ctx, + ) + .await + }); + + let body = br#"{"api_key":"sk-1234567890abcdef"}"#; + let request = format!( + "POST /v1/messages HTTP/1.1\r\nHost: api.example.test\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", + body.len(), + std::str::from_utf8(body).unwrap() + ); + app.write_all(request.as_bytes()).await.unwrap(); + + let mut upstream_request = [0u8; 1024]; + let n = tokio::time::timeout( + std::time::Duration::from_secs(1), + upstream.read(&mut upstream_request), + ) + .await + .expect("request should reach upstream") + .unwrap(); + let upstream_request = String::from_utf8_lossy(&upstream_request[..n]); + // No middleware ran, so the body is forwarded verbatim. + assert!(upstream_request.contains(r#""api_key":"sk-1234567890abcdef""#)); + + upstream + .write_all(b"HTTP/1.1 204 No Content\r\nContent-Length: 0\r\nConnection: close\r\n\r\n") + .await + .unwrap(); + let mut client_response = [0u8; 512]; + let n = tokio::time::timeout( + std::time::Duration::from_secs(1), + app.read(&mut client_response), + ) + .await + .expect("response should reach client") + .unwrap(); + assert!(String::from_utf8_lossy(&client_response[..n]).contains("204 No Content")); + drop(app); + tokio::time::timeout(std::time::Duration::from_secs(1), relay) + .await + .expect("relay should finish") + .unwrap() + .unwrap(); + } + + #[test] + fn middleware_keeps_the_raw_request_query() { + let query = raw_query_from_request_headers( + b"POST /v1/messages?token=a%2Bb&scope=private HTTP/1.1\r\nHost: api.example.test\r\n\r\n", + ) + .expect("query from request headers"); + + assert_eq!(query, "token=a%2Bb&scope=private"); + } + + #[test] + fn middleware_request_input_preserves_plain_http_scheme() { + let req = crate::l7::provider::L7Request { + action: "POST".into(), + target: "/v1/messages".into(), + query_params: std::collections::HashMap::new(), + raw_header: Vec::new(), + body_length: crate::l7::provider::BodyLength::None, + }; + let ctx = L7EvalContext { + host: "api.example.test".into(), + port: 80, + policy_name: "api".into(), + binary_path: "/usr/bin/curl".into(), + ancestors: Vec::new(), + cmdline_paths: Vec::new(), + secret_resolver: None, + activity_tx: None, + dynamic_credentials: None, + token_grant_resolver: None, + }; + + let input = middleware_request_input( + "http", + &req, + &ctx, + Vec::new(), + Vec::new(), + String::new(), + Vec::new(), + ); + + assert_eq!(input.scheme, "http"); + } + + #[test] + fn middleware_ocsf_events_are_audit_safe() { + use openshell_supervisor_middleware::{ + ChainOutcome, MiddlewareInvocation, NamespacedFinding, + }; + + const RAW_SECRET: &str = "sk-RAWSECRETVALUE0123456789"; + + let ctx = L7EvalContext { + host: "api.example.test".into(), + port: 443, + policy_name: "rest_api".into(), + binary_path: "/usr/bin/curl".into(), + ancestors: vec![], + cmdline_paths: vec![], + secret_resolver: None, + activity_tx: None, + dynamic_credentials: None, + token_grant_resolver: None, + }; + let req = crate::l7::provider::L7Request { + action: "POST".into(), + target: "/v1/messages".into(), + query_params: std::collections::HashMap::new(), + raw_header: Vec::new(), + body_length: crate::l7::provider::BodyLength::None, + }; + let outcome = ChainOutcome { + allowed: true, + reason: String::new(), + // The transformed body still holds the raw secret; emission must never + // serialize it. + body: format!(r#"{{"api_key":"{RAW_SECRET}"}}"#).into_bytes(), + header_mutations: Vec::new(), + findings: vec![NamespacedFinding { + middleware: "regex-redactor".into(), + finding: openshell_core::proto::Finding { + r#type: "regex.keyword".into(), + label: "keyword regex match".into(), + count: 1, + confidence: "medium".into(), + severity: "medium".into(), + }, + }], + metadata: BTreeMap::new(), + applied: vec![MiddlewareInvocation { + name: "regex-redactor".into(), + implementation: "openshell/regex".into(), + decision: openshell_core::proto::Decision::Allow, + transformed: true, + failed: false, + }], + denial: None, + }; + + // Build the events directly rather than routing through the global + // tracing pipeline: its callsite-interest cache is process-global, so a + // parallel test that emits OCSF with no subscriber installed can cache + // the callsite as disabled and make captured-event assertions flaky. + let events = middleware_events(&ctx, &req, &outcome); + + // Per-invocation decisions are HTTP Activity (class 4002). + assert!( + events.iter().any(|e| e.class_uid() == 4002), + "expected an HTTP Activity event for the middleware invocation" + ); + // Findings are Detection Finding (class 2004) with the finding's severity. + let finding_event = events + .iter() + .find(|e| e.class_uid() == 2004) + .expect("expected a Detection Finding event"); + assert_eq!(finding_event.base().severity, SeverityId::Medium); + + // No raw payload material may appear in any emitted event. + let serialized = serde_json::to_string(&events).expect("serialize events"); + assert!( + !serialized.contains(RAW_SECRET), + "raw secret leaked into OCSF events: {serialized}" + ); + // Safe finding metadata is still present. + assert!(serialized.contains("regex.keyword")); + + let mut bounded_outcome = outcome; + bounded_outcome.findings = (0 + ..openshell_supervisor_middleware::MAX_MIDDLEWARE_CHAIN_STAGES) + .flat_map(|stage| { + (0..openshell_supervisor_middleware::MAX_MIDDLEWARE_FINDINGS_PER_STAGE).map( + move |_| NamespacedFinding { + middleware: format!("external-guard-{stage}"), + finding: openshell_core::proto::Finding { + r#type: "example/content-guard.finding".into(), + label: "External middleware finding".into(), + count: 1, + confidence: String::new(), + severity: "medium".into(), + }, + }, + ) + }) + .chain(std::iter::once(NamespacedFinding { + middleware: "over-capacity".into(), + finding: openshell_core::proto::Finding { + r#type: "example/content-guard.finding".into(), + label: "External middleware finding".into(), + count: 1, + confidence: String::new(), + severity: "medium".into(), + }, + })) + .collect(); + let bounded_events = middleware_events(&ctx, &req, &bounded_outcome); + assert_eq!( + bounded_events + .iter() + .filter(|event| event.class_uid() == 2004) + .count(), + openshell_supervisor_middleware::MAX_MIDDLEWARE_CHAIN_FINDINGS, + "finding emission must remain bounded even if an invalid outcome bypasses the runner" + ); + + let denied_outcome = ChainOutcome { + allowed: false, + reason: "middleware_denied:content-guard:content_match".into(), + body: Vec::new(), + header_mutations: Vec::new(), + findings: Vec::new(), + metadata: BTreeMap::new(), + applied: vec![MiddlewareInvocation { + name: "content-guard".into(), + implementation: "example/content-guard".into(), + decision: openshell_core::proto::Decision::Deny, + transformed: false, + failed: false, + }], + denial: Some(openshell_supervisor_middleware::MiddlewareDenial { + config_name: "content-guard".into(), + reason_code: Some("content_match".into()), + }), + }; + let denied_events = middleware_events(&ctx, &req, &denied_outcome); + let denied_http = denied_events + .iter() + .find(|event| event.class_uid() == 4002) + .expect("expected denied HTTP Activity event"); + assert_eq!( + denied_http.base().status_detail.as_deref(), + Some("middleware_denied:content-guard:content_match") + ); + let denied_json = denied_http.to_json().expect("serialize denied event"); + assert_eq!(denied_json["unmapped"]["transformed"], false); + assert_eq!(denied_json["unmapped"]["failed"], false); + assert_eq!( + denied_http.format_shorthand(), + "HTTP:POST [MED] DENIED POST http://api.example.test:443/v1/messages \ + [policy:rest_api engine:middleware] \ + [failed:false transformed:false \ + reason:middleware_denied:content-guard:content_match]" + ); + + let external_failure_outcome = ChainOutcome { + reason: "middleware_failed: header_mutation_invalid_name".into(), + denial: None, + applied: vec![MiddlewareInvocation { + failed: true, + ..denied_outcome.applied[0].clone() + }], + ..denied_outcome + }; + let failure_events = middleware_events(&ctx, &req, &external_failure_outcome); + let serialized = serde_json::to_string(&failure_events).expect("serialize failure events"); + assert!(serialized.contains("header_mutation_invalid_name")); + assert!(!serialized.contains(RAW_SECRET)); + } + + #[tokio::test] + async fn passthrough_relay_runs_middleware_redaction() { + // A no-protocol endpoint takes the credential-injection passthrough path; + // host-selected middleware must still inspect and redact its body. + let data = r#" +network_middlewares: + request-middleware: + middleware: openshell/regex + on_error: fail_closed + endpoints: + include: ["api.example.test"] +network_policies: + passthrough_api: + name: passthrough_api + endpoints: + - host: api.example.test + port: 8080 + binaries: + - { path: /usr/bin/curl } +"#; + let engine = Arc::new(OpaEngine::from_strings(TEST_POLICY, data).unwrap()); + install_builtin_middleware(engine.as_ref()); + let generation_guard = engine + .generation_guard(engine.current_generation()) + .unwrap(); + let ctx = L7EvalContext { + host: "api.example.test".into(), + port: 8080, + policy_name: "passthrough_api".into(), + binary_path: "/usr/bin/curl".into(), + ancestors: vec![], + cmdline_paths: vec![], + secret_resolver: None, + activity_tx: None, + dynamic_credentials: None, + token_grant_resolver: None, + }; + + let (mut app, mut relay_client) = tokio::io::duplex(8192); + let (mut relay_upstream, mut upstream) = tokio::io::duplex(8192); + let engine_task = Arc::clone(&engine); + let relay = tokio::spawn(async move { + relay_passthrough_with_credentials( + &mut relay_client, + &mut relay_upstream, + &ctx, + &generation_guard, + Some(engine_task.as_ref()), + ) + .await + }); + + let body = br#"{"api_key":"sk-1234567890abcdef"}"#; + let request = format!( + "POST /v1/messages HTTP/1.1\r\nHost: api.example.test\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", + body.len(), + std::str::from_utf8(body).unwrap() + ); + app.write_all(request.as_bytes()).await.unwrap(); + + let mut upstream_request = [0u8; 1024]; + let n = tokio::time::timeout( + std::time::Duration::from_secs(1), + upstream.read(&mut upstream_request), + ) + .await + .expect("request should reach upstream") + .unwrap(); + let upstream_request = String::from_utf8_lossy(&upstream_request[..n]); + assert!( + upstream_request.contains(r#""api_key":"[REDACTED]""#), + "unexpected upstream request: {upstream_request:?}" + ); + assert!(!upstream_request.contains("sk-1234567890abcdef")); + + upstream + .write_all(b"HTTP/1.1 204 No Content\r\nContent-Length: 0\r\nConnection: close\r\n\r\n") + .await + .unwrap(); + let mut client_response = [0u8; 512]; + let n = tokio::time::timeout( + std::time::Duration::from_secs(1), + app.read(&mut client_response), + ) + .await + .expect("response should reach client") + .unwrap(); + assert!(String::from_utf8_lossy(&client_response[..n]).contains("204 No Content")); + drop(app); + tokio::time::timeout(std::time::Duration::from_secs(1), relay) + .await + .expect("relay should finish") + .unwrap() + .unwrap(); + } + + #[tokio::test] + async fn websocket_upgrade_request_is_inspected_and_denied() { + // The WebSocket upgrade handshake is an HTTP request the hook can inspect + // and deny: a fail-closed middleware blocks the upgrade before it is + // forwarded. + let data = r#" +network_middlewares: + request-middleware: + middleware: example/unavailable + on_error: fail_closed + endpoints: + include: ["gateway.example.test"] +network_policies: + ws_api: + name: ws_api + endpoints: + - host: gateway.example.test + port: 443 + protocol: websocket + enforcement: enforce + rules: + - allow: + method: GET + path: "/ws" + binaries: + - { path: /usr/bin/node } +"#; + let engine = OpaEngine::from_strings(TEST_POLICY, data).unwrap(); + let input = NetworkInput { + host: "gateway.example.test".into(), + port: 443, + binary_path: PathBuf::from("/usr/bin/node"), + binary_sha256: "unused".into(), + ancestors: vec![], + cmdline_paths: vec![], + }; + let (endpoint_config, generation) = engine + .query_endpoint_config_with_generation(&input) + .unwrap(); + let config = crate::l7::parse_l7_config(&endpoint_config.unwrap()).unwrap(); + let tunnel_engine = engine.clone_engine_for_tunnel(generation).unwrap(); + let ctx = L7EvalContext { + host: "gateway.example.test".into(), + port: 443, + policy_name: "ws_api".into(), + binary_path: "/usr/bin/node".into(), + ancestors: vec![], + cmdline_paths: vec![], + secret_resolver: None, + activity_tx: None, + dynamic_credentials: None, + token_grant_resolver: None, + }; + + let (mut app, mut relay_client) = tokio::io::duplex(8192); + let (mut relay_upstream, mut upstream) = tokio::io::duplex(8192); + let relay = tokio::spawn(async move { + relay_with_inspection( + &config, + tunnel_engine, + &mut relay_client, + &mut relay_upstream, + &ctx, + ) + .await + }); + + app.write_all( + b"GET /ws HTTP/1.1\r\nHost: gateway.example.test\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\nSec-WebSocket-Version: 13\r\n\r\n", + ) + .await + .unwrap(); + + // Accumulate until the reason marker arrives: the deny response can be + // delivered in more than one write, so a single read may return only the + // status line and flake the body assertion. + let mut response = Vec::new(); + let mut buf = [0u8; 512]; + while !String::from_utf8_lossy(&response).contains("middleware_failed") { + match tokio::time::timeout(std::time::Duration::from_secs(1), app.read(&mut buf)).await + { + Ok(Ok(0)) | Err(_) => break, // clean EOF, or no more data before the deadline + Ok(Ok(n)) => response.extend_from_slice(&buf[..n]), + Ok(Err(e)) => panic!("read from relay failed: {e}"), + } + } + let response = String::from_utf8_lossy(&response); + assert!(response.contains("403 Forbidden")); + assert!(response.contains("middleware_failed")); + + let mut upstream_request = [0u8; 32]; + let result = tokio::time::timeout( + std::time::Duration::from_millis(100), + upstream.read(&mut upstream_request), + ) + .await; + assert!( + matches!(result, Err(_) | Ok(Ok(0))), + "upstream should not receive the upgrade request" + ); + + drop(app); + tokio::time::timeout(std::time::Duration::from_secs(1), relay) + .await + .expect("relay should finish") + .unwrap() + .unwrap(); + } + + #[tokio::test] + async fn passthrough_relay_injects_token_grant_authorization_header() { + let (generation_guard, ctx, fixture) = + passthrough_token_grant_relay_context(Ok("grant-token")); + let (mut app, mut relay_client) = tokio::io::duplex(8192); + let (mut relay_upstream, mut upstream) = tokio::io::duplex(8192); + let relay = tokio::spawn(async move { + relay_passthrough_with_credentials( + &mut relay_client, + &mut relay_upstream, + &ctx, + &generation_guard, + None, + ) + .await + }); + + app.write_all( + b"GET /v1/projects HTTP/1.1\r\nHost: api.example.test\r\nAuthorization: Bearer stale-token\r\nConnection: close\r\n\r\n", + ) + .await + .unwrap(); + + let mut upstream_request = [0u8; 1024]; + let n = tokio::time::timeout( + std::time::Duration::from_secs(1), + upstream.read(&mut upstream_request), + ) + .await + .expect("request should reach upstream") + .unwrap(); + let upstream_request = String::from_utf8_lossy(&upstream_request[..n]); + + assert!(upstream_request.starts_with("GET /v1/projects HTTP/1.1\r\n")); + assert!(upstream_request.contains("Authorization: Bearer grant-token\r\n")); + assert!(!upstream_request.contains("stale-token")); + assert_eq!(authorization_header_count(&upstream_request), 1); + + upstream + .write_all(b"HTTP/1.1 204 No Content\r\nContent-Length: 0\r\nConnection: close\r\n\r\n") + .await + .unwrap(); + + let mut client_response = [0u8; 512]; + let n = tokio::time::timeout( + std::time::Duration::from_secs(1), + app.read(&mut client_response), + ) + .await + .expect("response should reach client") + .unwrap(); + assert!(String::from_utf8_lossy(&client_response[..n]).contains("204 No Content")); + drop(app); + + tokio::time::timeout(std::time::Duration::from_secs(1), relay) + .await + .expect("relay should finish") + .unwrap() + .unwrap(); + + fixture.assert_one_request("api.example.test\t8080\t/v1/**\tprovider:access_token"); + } + + #[tokio::test] + async fn passthrough_relay_token_grant_failure_returns_bad_gateway_without_forwarding() { + let (generation_guard, ctx, fixture) = + passthrough_token_grant_relay_context(Err("oauth unavailable")); + let (mut app, mut relay_client) = tokio::io::duplex(8192); + let (mut relay_upstream, mut upstream) = tokio::io::duplex(8192); + let relay = tokio::spawn(async move { + relay_passthrough_with_credentials( + &mut relay_client, + &mut relay_upstream, + &ctx, + &generation_guard, + None, + ) + .await + }); + + app.write_all( + b"GET /v1/projects HTTP/1.1\r\nHost: api.example.test\r\nConnection: close\r\n\r\n", + ) + .await + .unwrap(); + + tokio::time::timeout(std::time::Duration::from_secs(1), relay) + .await + .expect("relay should finish") + .unwrap() + .unwrap(); + + let mut client_response = [0u8; 512]; + let n = tokio::time::timeout( + std::time::Duration::from_secs(1), + app.read(&mut client_response), + ) + .await + .expect("bad gateway response should reach client") + .unwrap(); + assert!(String::from_utf8_lossy(&client_response[..n]).contains("502 Bad Gateway")); + + let mut upstream_request = [0u8; 128]; + let n = tokio::time::timeout( + std::time::Duration::from_secs(1), + upstream.read(&mut upstream_request), + ) + .await + .expect("upstream should close without forwarded data") + .unwrap(); + assert_eq!(n, 0, "unauthenticated request must not reach upstream"); + + fixture.assert_one_request("api.example.test\t8080\t/v1/**\tprovider:access_token"); + } + + #[test] + fn websocket_text_policy_requires_explicit_message_rule() { + let data = r#" network_policies: ws_api: name: ws_api @@ -2762,6 +4899,102 @@ network_policies: assert!(no_params_message.contains("rule_methods=initialize")); } + #[tokio::test] + async fn route_selected_jsonrpc_response_frame_hard_denies_under_audit() { + let data = r" +network_policies: + route_api: + name: route_api + endpoints: + - host: gateway.example.test + port: 443 + path: /rpc + protocol: json-rpc + enforcement: audit + rules: + - allow: + method: initialize + binaries: + - { path: /usr/bin/node } +"; + let engine = OpaEngine::from_strings(TEST_POLICY, data).unwrap(); + let input = NetworkInput { + host: "gateway.example.test".into(), + port: 443, + binary_path: PathBuf::from("/usr/bin/node"), + binary_sha256: "unused".into(), + ancestors: vec![], + cmdline_paths: vec![], + }; + let (endpoint, generation) = engine + .query_endpoint_config_with_generation(&input) + .expect("endpoint config"); + let configs = vec![ + crate::l7::parse_l7_config(&endpoint.expect("JSON-RPC endpoint")) + .expect("parse JSON-RPC config"), + ]; + let tunnel_engine = engine.clone_engine_for_tunnel(generation).unwrap(); + let ctx = L7EvalContext { + host: "gateway.example.test".into(), + port: 443, + policy_name: "route_api".into(), + binary_path: "/usr/bin/node".into(), + ancestors: vec![], + cmdline_paths: vec![], + secret_resolver: None, + activity_tx: None, + dynamic_credentials: None, + token_grant_resolver: None, + }; + let (mut app, mut relay_client) = tokio::io::duplex(8192); + let (mut relay_upstream, mut upstream) = tokio::io::duplex(8192); + let relay = tokio::spawn(async move { + relay_with_route_selection( + &configs, + tunnel_engine, + &mut relay_client, + &mut relay_upstream, + &ctx, + ) + .await + }); + + let body = br#"{"jsonrpc":"2.0","id":7,"result":{"ok":true}}"#; + let request = format!( + "POST /rpc HTTP/1.1\r\nHost: gateway.example.test\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", + body.len() + ); + app.write_all(request.as_bytes()).await.unwrap(); + app.write_all(body).await.unwrap(); + + let mut response = [0u8; 1024]; + let n = tokio::time::timeout(std::time::Duration::from_secs(1), app.read(&mut response)) + .await + .expect("hard denial should reach client") + .unwrap(); + let response = String::from_utf8_lossy(&response[..n]); + assert!(response.contains("403 Forbidden"), "{response}"); + assert!(response.contains("response frames"), "{response}"); + + let mut upstream_bytes = [0u8; 16]; + let result = tokio::time::timeout( + std::time::Duration::from_millis(100), + upstream.read(&mut upstream_bytes), + ) + .await; + assert!( + matches!(result, Err(_) | Ok(Ok(0))), + "hard-denied response frame must not reach upstream" + ); + + drop(app); + tokio::time::timeout(std::time::Duration::from_secs(1), relay) + .await + .expect("relay should finish") + .unwrap() + .unwrap(); + } + #[tokio::test] async fn route_selected_websocket_upgrade_rejects_invalid_accept_without_forwarding_101() { let data = r#" @@ -3251,7 +5484,10 @@ network_policies: .expect("first request should reach upstream") .unwrap(); let first_upstream = String::from_utf8_lossy(&first_upstream[..n]); - assert!(first_upstream.starts_with("POST /write HTTP/1.1")); + assert!( + first_upstream.starts_with("POST /write HTTP/1.1"), + "unexpected upstream request: {first_upstream:?}" + ); upstream .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: keep-alive\r\n\r\nOK") @@ -3321,6 +5557,7 @@ network_policies: &mut relay_upstream, &ctx, &generation_guard, + None, ) .await }); diff --git a/crates/openshell-supervisor-network/src/l7/rest.rs b/crates/openshell-supervisor-network/src/l7/rest.rs index 99f2f328eb..0c1346bf2e 100644 --- a/crates/openshell-supervisor-network/src/l7/rest.rs +++ b/crates/openshell-supervisor-network/src/l7/rest.rs @@ -12,6 +12,7 @@ use crate::opa::PolicyGenerationGuard; use aws_sigv4::http_request::SignableBody; use base64::Engine as _; use miette::{IntoDiagnostic, Result, miette}; +use openshell_core::proto::{ExistingHeaderAction, HeaderMutation, header_mutation}; use openshell_core::secrets::{ SecretResolver, contains_reserved_credential_marker, rewrite_http_header_block, }; @@ -27,6 +28,25 @@ const MAX_REWRITE_BODY_BYTES: usize = 256 * 1024; /// Maximum body bytes for `SigV4` body-signing mode. Larger than the credential /// rewrite limit because Bedrock payloads can be several megabytes. const MAX_SIGV4_BODY_BYTES: usize = 10 * 1024 * 1024; +#[cfg(test)] +async fn max_middleware_body_bytes() -> usize { + let chain = openshell_supervisor_middleware::ChainRunner::new( + openshell_supervisor_middleware_builtins::services() + .into_iter() + .next() + .expect("built-in middleware service"), + ) + .describe_chain(&[openshell_supervisor_middleware::ChainEntry { + name: "test".into(), + implementation: openshell_supervisor_middleware_builtins::BUILTIN_REGEX.into(), + order: 0, + config: prost_types::Struct::default(), + on_error: openshell_supervisor_middleware::OnError::FailClosed, + }]) + .await + .expect("describe built-in middleware"); + chain[0].max_body_bytes() +} const RELAY_BUF_SIZE: usize = 8192; const HTTP_METHOD_PREFIXES: &[&[u8]] = &[ b"GET ", @@ -183,6 +203,7 @@ async fn parse_http_request( // bytes with U+FFFD, creating an interpretation gap between this proxy // (which parses the lossy string) and upstream servers (which receive the // raw bytes). This gap enables request smuggling via mutated header names. + validate_http_request_header_block(&buf[..header_end])?; let header_str = std::str::from_utf8(&buf[..header_end]) .map_err(|_| miette!("HTTP headers contain invalid UTF-8"))?; @@ -245,6 +266,169 @@ async fn parse_http_request( })) } +/// Build an L7 request from a request already buffered by another proxy path. +/// +/// The forward proxy needs this after it has consumed the incoming HTTP/1 +/// headers itself. Keep the framing and query parsing here so it matches the +/// stream-based REST parser rather than growing another local parser. +pub(crate) fn request_from_buffered_http( + action: impl Into, + target: impl Into, + query_target: &str, + raw_header: Vec, +) -> Result { + let header_end = raw_header + .windows(4) + .position(|window| window == b"\r\n\r\n") + .ok_or_else(|| miette!("HTTP request headers are missing the CRLF terminator"))? + + 4; + validate_http_request_header_block(&raw_header[..header_end])?; + let header_str = std::str::from_utf8(&raw_header[..header_end]) + .map_err(|_| miette!("HTTP headers contain invalid UTF-8"))?; + let body_length = parse_body_length(header_str)?; + let (_, query_params) = parse_target_query(query_target)?; + + Ok(L7Request { + action: action.into(), + target: target.into(), + query_params, + raw_header, + body_length, + }) +} + +/// Validate an HTTP/1 request line and header fields before policy evaluation or forwarding. +/// +/// This parser deliberately rejects malformed request lines, obsolete line +/// folding, and malformed field names rather than allowing policy, middleware, +/// and the upstream server to interpret the same wire bytes differently. +pub(crate) fn validate_http_request_header_block(headers: &[u8]) -> Result<()> { + let headers = + std::str::from_utf8(headers).map_err(|_| miette!("HTTP headers contain invalid UTF-8"))?; + let header_block = headers + .strip_suffix("\r\n\r\n") + .ok_or_else(|| miette!("HTTP request headers are missing the CRLF terminator"))?; + let mut lines = header_block.split("\r\n"); + let request_line = lines + .next() + .ok_or_else(|| miette!("HTTP request is missing a request line"))?; + validate_http_request_line(request_line)?; + let mut connection_nominated = HashSet::new(); + + for line in lines { + if line + .as_bytes() + .first() + .is_some_and(|byte| matches!(byte, b' ' | b'\t')) + { + return Err(miette!( + "HTTP request header continuation lines are not supported" + )); + } + let (name, value) = line + .split_once(':') + .ok_or_else(|| miette!("HTTP request header field is missing ':'"))?; + if name + .as_bytes() + .last() + .is_some_and(|byte| matches!(byte, b' ' | b'\t')) + { + return Err(miette!( + "HTTP request header field contains whitespace before ':'" + )); + } + if name.is_empty() || !name.bytes().all(is_http_field_name_byte) { + return Err(miette!( + "HTTP request header field name is not a valid HTTP token" + )); + } + if !value.bytes().all(is_http_field_value_byte) { + return Err(miette!( + "HTTP request header field value contains an invalid control byte" + )); + } + if name.eq_ignore_ascii_case("connection") { + for token in value.split(',') { + let token = token.trim(); + if token.is_empty() || !token.bytes().all(is_http_field_name_byte) { + return Err(miette!( + "HTTP Connection header contains an invalid option token" + )); + } + connection_nominated.insert(token.to_ascii_lowercase()); + } + } + } + if connection_nominated.iter().any(|name| { + matches!( + name.as_str(), + "host" | "content-length" | "transfer-encoding" + ) + }) { + return Err(miette!( + "HTTP Connection header nominates a request framing or routing field" + )); + } + Ok(()) +} + +fn validate_http_request_line(request_line: &str) -> Result<()> { + let mut parts = request_line.split(' '); + let method = parts + .next() + .ok_or_else(|| miette!("HTTP request line is missing a method"))?; + let target = parts + .next() + .ok_or_else(|| miette!("HTTP request line is missing a target"))?; + let version = parts + .next() + .ok_or_else(|| miette!("HTTP request line is missing a version"))?; + + if parts.next().is_some() || method.is_empty() || target.is_empty() || version.is_empty() { + return Err(miette!( + "HTTP request line must be exactly 'METHOD SP target SP HTTP/1.0|HTTP/1.1'" + )); + } + if !method.bytes().all(is_http_field_name_byte) { + return Err(miette!("HTTP request method is not a valid HTTP token")); + } + if target.bytes().any(|byte| byte <= b' ' || byte == 0x7f) { + return Err(miette!( + "HTTP request target contains whitespace or a control byte" + )); + } + if !matches!(version, "HTTP/1.0" | "HTTP/1.1") { + return Err(miette!("Unsupported HTTP version: {version}")); + } + + Ok(()) +} + +fn is_http_field_name_byte(byte: u8) -> bool { + byte.is_ascii_alphanumeric() + || matches!( + byte, + b'!' | b'#' + | b'$' + | b'%' + | b'&' + | b'\'' + | b'*' + | b'+' + | b'-' + | b'.' + | b'^' + | b'_' + | b'`' + | b'|' + | b'~' + ) +} + +fn is_http_field_value_byte(byte: u8) -> bool { + byte == b'\t' || (b' '..=b'~').contains(&byte) || byte >= 0x80 +} + /// Rebuild the request line in a raw HTTP header block with a canonicalized /// target. Called when the canonical path differs from what the client sent, /// so the upstream dispatches on the exact bytes the policy engine evaluated. @@ -447,6 +631,7 @@ where let header_str = std::str::from_utf8(&req.raw_header[..header_end]) .map_err(|_| miette!("HTTP headers contain invalid UTF-8"))?; let client_requested_upgrade = client_requested_upgrade(header_str); + let is_websocket_request = request_is_websocket_upgrade(&req.raw_header[..header_end]); let websocket_request = if options.websocket_extensions == WebSocketExtensionMode::Preserve { None } else { @@ -469,6 +654,7 @@ where options.websocket_extensions, websocket_request.is_some(), )?; + let header_bytes = strip_connection_nominated_headers(&header_bytes, is_websocket_request)?; let websocket_response = websocket_request .as_ref() @@ -778,6 +964,214 @@ struct PreparedRequestBody { body: Vec, } +#[derive(Debug)] +pub(crate) struct BufferedRequestBody { + pub(crate) headers: Vec, + pub(crate) body: Vec, +} + +/// Result of attempting to buffer a request body for middleware inspection. +#[derive(Debug)] +pub(crate) enum BufferResult { + /// The full body was buffered within the size cap. + Buffered(BufferedRequestBody), + /// The body exceeded the inspection cap. `recoverable` is true when no body + /// bytes were consumed yet (a declared `Content-Length` over the cap), so the + /// request can still be streamed through unprocessed under fail-open. It is + /// false once bytes have been consumed (chunked overflow), where denying is + /// the only safe outcome. + OverCapacity { recoverable: bool }, +} + +pub(crate) async fn buffer_request_body_for_middleware( + req: &L7Request, + client: &mut C, + generation_guard: Option<&PolicyGenerationGuard>, + max_body_bytes: usize, +) -> Result { + let header_end = req + .raw_header + .windows(4) + .position(|w| w == b"\r\n\r\n") + .map_or(req.raw_header.len(), |p| p + 4); + let mut headers = req.raw_header[..header_end].to_vec(); + let already_read = &req.raw_header[header_end..]; + match req.body_length { + BodyLength::None => { + // Leftover bytes after `\r\n\r\n` on a no-body request are + // read-ahead or pipelined data, not a framed body. Promoting them + // into `body` would later stamp `Content-Length` and forward them + // upstream as if they belonged to this request. + if !already_read.is_empty() { + return Err(miette!( + "HTTP request with no body framing has {} unread byte(s) after headers; \ + refusing to treat read-ahead bytes as a request body", + already_read.len() + )); + } + handle_buffered_expect_continue(client, &mut headers, false).await?; + Ok(BufferResult::Buffered(BufferedRequestBody { + headers, + body: Vec::new(), + })) + } + BodyLength::ContentLength(len) => { + // The declared length is known before any further reads, so an + // over-cap body here has not consumed the stream and can be passed + // through unprocessed if every middleware is fail-open. + let Ok(len) = usize::try_from(len) else { + return Ok(BufferResult::OverCapacity { recoverable: true }); + }; + if len > max_body_bytes { + return Ok(BufferResult::OverCapacity { recoverable: true }); + } + let initial_len = already_read.len().min(len); + let mut body = Vec::new(); + body.try_reserve_exact(len).map_err(|_| { + miette!("unable to allocate {len} bytes for middleware request body") + })?; + body.extend_from_slice(&already_read[..initial_len]); + let mut remaining = len.saturating_sub(initial_len); + handle_buffered_expect_continue(client, &mut headers, remaining > 0).await?; + let mut buf = [0u8; RELAY_BUF_SIZE]; + while remaining > 0 { + let to_read = remaining.min(buf.len()); + let n = client.read(&mut buf[..to_read]).await.into_diagnostic()?; + if n == 0 { + return Err(miette!( + "Connection closed with {remaining} body bytes remaining" + )); + } + if let Some(guard) = generation_guard { + guard.ensure_current()?; + } + body.extend_from_slice(&buf[..n]); + remaining -= n; + } + Ok(BufferResult::Buffered(BufferedRequestBody { + headers, + body, + })) + } + BodyLength::Chunked => { + // Chunked bodies are decoded incrementally into the payload bytes + // middleware expects, but the middleware cap counts the complete + // wire representation, including framing and trailers. On overflow, + // we have already consumed wire bytes from the client stream and + // cannot re-enter the normal raw relay path without a separate + // splice-through buffer. + let needs_client_read = !chunked_body_is_fully_buffered(already_read); + handle_buffered_expect_continue(client, &mut headers, needs_client_read).await?; + match collect_chunked_body(client, already_read, generation_guard, Some(max_body_bytes)) + .await + { + Ok(body) => Ok(BufferResult::Buffered(BufferedRequestBody { + headers, + body, + })), + Err(CollectChunkedError::OverCapacity) => { + Ok(BufferResult::OverCapacity { recoverable: false }) + } + Err(CollectChunkedError::Failed(error)) => Err(error), + } + } + } +} + +async fn handle_buffered_expect_continue( + client: &mut C, + headers: &mut Vec, + needs_client_read: bool, +) -> Result<()> { + let header_str = + std::str::from_utf8(headers).map_err(|_| miette!("HTTP headers contain invalid UTF-8"))?; + if needs_client_read && has_expect_continue(header_str) { + client + .write_all(b"HTTP/1.1 100 Continue\r\n\r\n") + .await + .into_diagnostic()?; + client.flush().await.into_diagnostic()?; + } + // Middleware has taken responsibility for collecting the body. Never + // forward Expect upstream alongside the completed, normalized request. + *headers = strip_header(headers, "expect")?; + Ok(()) +} + +fn chunked_body_is_fully_buffered(bytes: &[u8]) -> bool { + let mut pos = 0usize; + loop { + let Some(line_end) = bytes[pos..].windows(2).position(|window| window == b"\r\n") else { + return false; + }; + let line_end = pos + line_end; + let Ok(size_line) = std::str::from_utf8(&bytes[pos..line_end]) else { + return false; + }; + let size_token = size_line + .split(';') + .next() + .map(str::trim) + .unwrap_or_default(); + let Ok(chunk_size) = usize::from_str_radix(size_token, 16) else { + return false; + }; + pos = line_end + 2; + if chunk_size == 0 { + return bytes.get(pos..pos.saturating_add(2)) == Some(b"\r\n"); + } + let Some(chunk_end) = pos.checked_add(chunk_size) else { + return false; + }; + let Some(terminator_end) = chunk_end.checked_add(2) else { + return false; + }; + if bytes.get(chunk_end..terminator_end) != Some(b"\r\n") { + return false; + } + pos = terminator_end; + } +} + +pub(crate) fn rebuild_request_with_buffered_body( + req: &L7Request, + headers: &[u8], + body: &[u8], + header_mutations: &[HeaderMutation], +) -> Result { + // Preserve no-body framing when middleware did not introduce a body. + // Stamping `Content-Length: 0` onto GET/HEAD-style requests is unnecessary + // and would mask the BodyLength::None overshoot bug if leftovers were ever + // accepted as an empty-looking rewrite. + if matches!(req.body_length, BodyLength::None) && body.is_empty() { + let mut header_bytes = strip_header(headers, "content-length")?; + header_bytes = strip_header(&header_bytes, "transfer-encoding")?; + header_bytes = apply_header_mutations(&header_bytes, header_mutations)?; + return Ok(L7Request { + action: req.action.clone(), + target: req.target.clone(), + query_params: req.query_params.clone(), + raw_header: header_bytes, + body_length: BodyLength::None, + }); + } + + let mut header_bytes = set_content_length(headers, body.len())?; + header_bytes = strip_header(&header_bytes, "transfer-encoding")?; + if matches!(req.body_length, BodyLength::Chunked) { + header_bytes = strip_header(&header_bytes, "trailer")?; + } + header_bytes = apply_header_mutations(&header_bytes, header_mutations)?; + header_bytes.extend_from_slice(body); + Ok(L7Request { + action: req.action.clone(), + target: req.target.clone(), + query_params: req.query_params.clone(), + raw_header: header_bytes, + body_length: BodyLength::ContentLength(body.len() as u64), + }) +} + async fn collect_and_rewrite_request_body( req: &L7Request, client: &mut C, @@ -831,16 +1225,20 @@ async fn collect_and_rewrite_request_body( Ok(PreparedRequestBody { headers, body }) } BodyLength::Chunked => { - let body = collect_chunked_body(client, already_read, generation_guard).await?; - if body_bytes_contain_reserved_marker(&body) { - return Err(miette!( - "request body credential rewrite does not support chunked bodies containing credential placeholders" - )); - } - Ok(PreparedRequestBody { - headers: rewritten_headers.to_vec(), - body, - }) + let body = collect_chunked_body( + client, + already_read, + generation_guard, + Some(MAX_REWRITE_BODY_BYTES), + ) + .await + .map_err(CollectChunkedError::into_report)?; + let (mut headers, body) = + rewrite_buffered_body(rewritten_headers, original_header_str, body, resolver)?; + headers = set_content_length(&headers, body.len())?; + headers = strip_header(&headers, "transfer-encoding")?; + headers = strip_header(&headers, "trailer")?; + Ok(PreparedRequestBody { headers, body }) } } } @@ -1003,108 +1401,239 @@ fn hex_value(byte: u8) -> Option { } } +/// Outcome of collecting a chunked request body for buffering. +#[derive(Debug)] +enum CollectChunkedError { + /// The caller-supplied wire/decoded cap was exceeded. Bytes may already + /// have been consumed from the client stream, so fail-open streaming is + /// unsafe. + OverCapacity, + /// Protocol, I/O, or policy-generation failure. Not an over-capacity event. + Failed(miette::Error), +} + +impl CollectChunkedError { + fn context(self, f: impl FnOnce(miette::Error) -> miette::Error) -> Self { + match self { + Self::OverCapacity => Self::OverCapacity, + Self::Failed(error) => Self::Failed(f(error)), + } + } + + fn into_report(self) -> miette::Error { + match self { + Self::OverCapacity => { + miette!("chunked body wire representation exceeds configured buffer limit") + } + Self::Failed(error) => error, + } + } +} + async fn collect_chunked_body( client: &mut C, already_read: &[u8], generation_guard: Option<&PolicyGenerationGuard>, -) -> Result> { - let mut read_buf = [0u8; RELAY_BUF_SIZE]; - let mut parse_buf = Vec::from(already_read); - let mut pos = 0usize; + max_wire_bytes: Option, +) -> std::result::Result, CollectChunkedError> { + let max_decoded_bytes = max_wire_bytes.unwrap_or(MAX_REWRITE_BODY_BYTES); + let mut read_state = ChunkedReadState { + buffered_pos: 0, + wire_bytes: 0, + max_wire_bytes, + }; + let mut body = Vec::new(); loop { - if parse_buf.len() > MAX_REWRITE_BODY_BYTES { - return Err(miette!( - "request body credential rewrite buffers at most {MAX_REWRITE_BODY_BYTES} bytes" - )); - } - - let size_line_end = loop { - if let Some(end) = find_crlf(&parse_buf, pos) { - break end; - } - let n = client.read(&mut read_buf).await.into_diagnostic()?; - if n == 0 { - return Err(miette!("Chunked body ended before chunk-size line")); - } - if let Some(guard) = generation_guard { - guard.ensure_current()?; - } - parse_buf.extend_from_slice(&read_buf[..n]); - if parse_buf.len() > MAX_REWRITE_BODY_BYTES { - return Err(miette!( - "request body credential rewrite buffers at most {MAX_REWRITE_BODY_BYTES} bytes" - )); - } - }; - - let size_line = std::str::from_utf8(&parse_buf[pos..size_line_end]) - .into_diagnostic() - .map_err(|_| miette!("Invalid UTF-8 in chunk-size line"))?; + let size_line = read_chunked_line(client, already_read, &mut read_state, generation_guard) + .await + .map_err(|error| { + error.context(|e| miette!("Chunked body ended before chunk-size line: {e}")) + })?; + let size_line = std::str::from_utf8(&size_line).map_err(|_| { + CollectChunkedError::Failed(miette!("Invalid UTF-8 in chunk-size line")) + })?; let size_token = size_line .split(';') .next() .map(str::trim) .unwrap_or_default(); - let chunk_size = usize::from_str_radix(size_token, 16) - .into_diagnostic() - .map_err(|_| miette!("Invalid chunk size token: {size_token:?}"))?; - pos = size_line_end + 2; + let chunk_size = usize::from_str_radix(size_token, 16).map_err(|_| { + CollectChunkedError::Failed(miette!("Invalid chunk size token: {size_token:?}")) + })?; if chunk_size == 0 { - loop { - let trailer_end = loop { - if let Some(end) = find_crlf(&parse_buf, pos) { - break end; - } - let n = client.read(&mut read_buf).await.into_diagnostic()?; - if n == 0 { - return Err(miette!("Chunked body ended before trailer terminator")); - } - if let Some(guard) = generation_guard { - guard.ensure_current()?; - } - parse_buf.extend_from_slice(&read_buf[..n]); - if parse_buf.len() > MAX_REWRITE_BODY_BYTES { - return Err(miette!( - "request body credential rewrite buffers at most {MAX_REWRITE_BODY_BYTES} bytes" - )); - } - }; - let trailer_line = &parse_buf[pos..trailer_end]; - pos = trailer_end + 2; - if trailer_line.is_empty() { - return Ok(parse_buf); - } + let trailer_line = + read_chunked_line(client, already_read, &mut read_state, generation_guard) + .await + .map_err(|error| { + error.context(|e| { + miette!("Chunked body ended before trailer terminator: {e}") + }) + })?; + if trailer_line.is_empty() { + return Ok(body); } + return Err(CollectChunkedError::Failed(miette!( + "chunked request trailers are not supported when buffering or transforming request bodies" + ))); + } + + if body.len().saturating_add(chunk_size) > max_decoded_bytes { + return Err(if max_wire_bytes.is_some() { + CollectChunkedError::OverCapacity + } else { + CollectChunkedError::Failed(miette!( + "decoded chunked body exceeds {max_decoded_bytes} byte buffer limit" + )) + }); + } + read_buffered_exact( + client, + already_read, + &mut read_state, + chunk_size, + &mut body, + generation_guard, + ) + .await + .map_err(|error| error.context(|e| miette!("Chunked body ended mid-chunk: {e}")))?; + + let mut chunk_crlf = Vec::with_capacity(2); + read_buffered_exact( + client, + already_read, + &mut read_state, + 2, + &mut chunk_crlf, + generation_guard, + ) + .await + .map_err(|error| { + error.context(|e| miette!("Chunked body ended before chunk terminator: {e}")) + })?; + if chunk_crlf.as_slice() != b"\r\n" { + return Err(CollectChunkedError::Failed(miette!( + "Chunk missing terminating CRLF" + ))); + } + } +} + +struct ChunkedReadState { + buffered_pos: usize, + wire_bytes: usize, + max_wire_bytes: Option, +} + +async fn read_chunked_line( + client: &mut C, + already_read: &[u8], + state: &mut ChunkedReadState, + generation_guard: Option<&PolicyGenerationGuard>, +) -> std::result::Result, CollectChunkedError> { + let mut line = Vec::new(); + loop { + let byte = read_buffered_byte(client, already_read, state, generation_guard).await?; + line.push(byte); + if line.len() > MAX_REWRITE_BODY_BYTES { + return Err(CollectChunkedError::Failed(miette!( + "request body credential rewrite buffers at most {MAX_REWRITE_BODY_BYTES} bytes" + ))); + } + if line.ends_with(b"\r\n") { + line.truncate(line.len() - 2); + return Ok(line); } + } +} - let chunk_end = pos - .checked_add(chunk_size) - .ok_or_else(|| miette!("Chunk size overflow"))?; - let chunk_with_crlf_end = chunk_end - .checked_add(2) - .ok_or_else(|| miette!("Chunk size overflow"))?; - while parse_buf.len() < chunk_with_crlf_end { - let n = client.read(&mut read_buf).await.into_diagnostic()?; - if n == 0 { - return Err(miette!("Chunked body ended mid-chunk")); - } - if let Some(guard) = generation_guard { - guard.ensure_current()?; - } - parse_buf.extend_from_slice(&read_buf[..n]); - if parse_buf.len() > MAX_REWRITE_BODY_BYTES { - return Err(miette!( - "request body credential rewrite buffers at most {MAX_REWRITE_BODY_BYTES} bytes" - )); - } +async fn read_buffered_exact( + client: &mut C, + already_read: &[u8], + state: &mut ChunkedReadState, + len: usize, + out: &mut Vec, + generation_guard: Option<&PolicyGenerationGuard>, +) -> std::result::Result<(), CollectChunkedError> { + if state + .max_wire_bytes + .is_some_and(|max| len > max.saturating_sub(state.wire_bytes)) + { + return Err(CollectChunkedError::OverCapacity); + } + out.try_reserve_exact(len).map_err(|_| { + CollectChunkedError::Failed(miette!( + "unable to allocate {len} bytes for chunked request body" + )) + })?; + + let buffered = len.min(already_read.len().saturating_sub(state.buffered_pos)); + if buffered > 0 { + let end = state.buffered_pos + buffered; + out.extend_from_slice(&already_read[state.buffered_pos..end]); + state.buffered_pos = end; + state.wire_bytes += buffered; + } + + let mut remaining = len - buffered; + let mut buf = [0u8; RELAY_BUF_SIZE]; + while remaining > 0 { + let to_read = remaining.min(buf.len()); + let read = client + .read(&mut buf[..to_read]) + .await + .into_diagnostic() + .map_err(CollectChunkedError::Failed)?; + if read == 0 { + return Err(CollectChunkedError::Failed(miette!( + "connection closed with {remaining} bytes remaining" + ))); } - if &parse_buf[chunk_end..chunk_with_crlf_end] != b"\r\n" { - return Err(miette!("Chunk missing terminating CRLF")); + if let Some(guard) = generation_guard { + guard + .ensure_current() + .map_err(CollectChunkedError::Failed)?; } - pos = chunk_with_crlf_end; + out.extend_from_slice(&buf[..read]); + state.wire_bytes += read; + remaining -= read; + } + Ok(()) +} + +async fn read_buffered_byte( + client: &mut C, + already_read: &[u8], + state: &mut ChunkedReadState, + generation_guard: Option<&PolicyGenerationGuard>, +) -> std::result::Result { + if state + .max_wire_bytes + .is_some_and(|max| state.wire_bytes >= max) + { + return Err(CollectChunkedError::OverCapacity); } + + let byte = if state.buffered_pos < already_read.len() { + let byte = already_read[state.buffered_pos]; + state.buffered_pos += 1; + byte + } else { + let byte = client + .read_u8() + .await + .into_diagnostic() + .map_err(CollectChunkedError::Failed)?; + if let Some(guard) = generation_guard { + guard + .ensure_current() + .map_err(CollectChunkedError::Failed)?; + } + byte + }; + state.wire_bytes += 1; + Ok(byte) } fn content_type(headers: &str) -> Option { @@ -1170,6 +1699,117 @@ fn set_content_length(headers: &[u8], len: usize) -> Result> { Ok(out.into_bytes()) } +fn strip_header(headers: &[u8], strip_name: &str) -> Result> { + let header_str = + std::str::from_utf8(headers).map_err(|_| miette!("HTTP headers contain invalid UTF-8"))?; + let mut out = String::with_capacity(header_str.len()); + for line in header_str.split("\r\n") { + if line.is_empty() { + out.push_str("\r\n"); + break; + } + if line + .split_once(':') + .is_some_and(|(name, _)| name.trim().eq_ignore_ascii_case(strip_name)) + { + continue; + } + out.push_str(line); + out.push_str("\r\n"); + } + Ok(out.into_bytes()) +} + +pub(crate) fn connection_nominated_header_names(headers: &[u8]) -> Result> { + validate_http_request_header_block(headers)?; + let header_str = + std::str::from_utf8(headers).map_err(|_| miette!("HTTP headers contain invalid UTF-8"))?; + Ok(header_str + .strip_suffix("\r\n\r\n") + .expect("validated header block has terminator") + .split("\r\n") + .skip(1) + .filter_map(|line| line.split_once(':')) + .filter(|(name, _)| name.eq_ignore_ascii_case("connection")) + .flat_map(|(_, value)| value.split(',')) + .map(|token| token.trim().to_ascii_lowercase()) + .filter(|token| !token.is_empty()) + .collect()) +} + +fn strip_connection_nominated_headers( + headers: &[u8], + preserve_websocket_upgrade: bool, +) -> Result> { + let nominated = connection_nominated_header_names(headers)?; + let mut out = headers.to_vec(); + for name in nominated { + out = strip_header(&out, &name)?; + } + out = strip_header(&out, "connection")?; + out = strip_header(&out, "upgrade")?; + if preserve_websocket_upgrade { + out = append_header(&out, "Connection", "Upgrade"); + out = append_header(&out, "Upgrade", "websocket"); + } + Ok(out) +} + +fn append_header(headers: &[u8], name: &str, value: &str) -> Vec { + let split = headers + .windows(4) + .position(|w| w == b"\r\n\r\n") + .map_or(headers.len(), |pos| pos); + let mut out = Vec::with_capacity(headers.len() + name.len() + value.len() + 4); + out.extend_from_slice(&headers[..split]); + out.extend_from_slice(b"\r\n"); + out.extend_from_slice(name.as_bytes()); + out.extend_from_slice(b": "); + out.extend_from_slice(value.as_bytes()); + out.extend_from_slice(b"\r\n\r\n"); + out +} + +fn apply_header_mutations(headers: &[u8], mutations: &[HeaderMutation]) -> Result> { + let mut out = headers.to_vec(); + for mutation in mutations { + match mutation.operation.as_ref() { + Some(header_mutation::Operation::Write(write)) => { + let action = ExistingHeaderAction::try_from(write.on_existing) + .map_err(|_| miette!("invalid middleware header on_existing action"))?; + if action == ExistingHeaderAction::Unspecified { + return Err(miette!( + "middleware header mutation has unspecified on_existing action" + )); + } + let exists = has_header(&out, &write.name)?; + if !exists || action == ExistingHeaderAction::Append { + out = append_header(&out, &write.name, &write.value); + } else if action == ExistingHeaderAction::Overwrite { + out = strip_header(&out, &write.name)?; + out = append_header(&out, &write.name, &write.value); + } else if action != ExistingHeaderAction::Skip { + return Err(miette!("unsupported middleware header on_existing action")); + } + } + Some(header_mutation::Operation::Remove(remove)) => { + out = strip_header(&out, &remove.name)?; + } + None => return Err(miette!("empty middleware header mutation")), + } + } + Ok(out) +} + +fn has_header(headers: &[u8], name: &str) -> Result { + let header_str = + std::str::from_utf8(headers).map_err(|_| miette!("HTTP headers contain invalid UTF-8"))?; + Ok(header_str.lines().skip(1).any(|line| { + line.split_once(':') + .is_some_and(|(candidate, _)| candidate.trim().eq_ignore_ascii_case(name)) + })) +} + pub(crate) fn request_is_websocket_upgrade(raw_header: &[u8]) -> bool { let header_end = raw_header .windows(4) @@ -1531,6 +2171,46 @@ async fn send_deny_response( context: Option>, ) -> Result<()> { let body = deny_response_body(req, policy_name, reason, redacted_target, context); + send_forbidden_json(policy_name, body, client).await +} + +/// Send a middleware-specific 403 response without policy-advisor guidance. +/// +/// The policy config identity and optional reason code are validated platform +/// inputs. Free-form middleware reason text is intentionally absent. +pub(crate) async fn send_middleware_deny_response( + req: &L7Request, + policy_name: &str, + denial: &openshell_supervisor_middleware::MiddlewareDenial, + client: &mut C, + redacted_target: Option<&str>, + context: Option>, +) -> Result<()> { + let body = middleware_deny_response_body(req, policy_name, denial, redacted_target, context); + send_forbidden_json(policy_name, body, client).await +} + +/// Send a platform-owned response for fail-closed middleware failures. +/// +/// Unlike an L7 policy denial, a middleware failure does not indicate a +/// missing policy rule. The response therefore omits policy-advisor guidance +/// and does not include the middleware runtime's diagnostic text. +pub(crate) async fn send_middleware_failure_response( + req: &L7Request, + policy_name: &str, + client: &mut C, + redacted_target: Option<&str>, + context: Option>, +) -> Result<()> { + let body = middleware_failure_response_body(req, policy_name, redacted_target, context); + send_forbidden_json(policy_name, body, client).await +} + +async fn send_forbidden_json( + policy_name: &str, + body: serde_json::Value, + client: &mut C, +) -> Result<()> { let body_bytes = body.to_string(); let response = format!( "HTTP/1.1 403 Forbidden\r\n\ @@ -1552,6 +2232,76 @@ async fn send_deny_response( Ok(()) } +fn middleware_deny_response_body( + req: &L7Request, + policy_name: &str, + denial: &openshell_supervisor_middleware::MiddlewareDenial, + redacted_target: Option<&str>, + context: Option>, +) -> serde_json::Value { + let target = redacted_target.unwrap_or(&req.target); + let context = context.unwrap_or_default(); + let mut body = serde_json::Map::new(); + body.insert("error".to_string(), serde_json::json!("middleware_denied")); + body.insert( + "detail".to_string(), + serde_json::json!("Request rejected by configured middleware"), + ); + body.insert("policy".to_string(), serde_json::json!(policy_name)); + body.insert( + "middleware".to_string(), + serde_json::json!(denial.config_name), + ); + if let Some(reason_code) = &denial.reason_code { + body.insert("reason_code".to_string(), serde_json::json!(reason_code)); + } + body.insert("layer".to_string(), serde_json::json!("l7")); + body.insert("method".to_string(), serde_json::json!(req.action)); + body.insert("path".to_string(), serde_json::json!(target)); + if let Some(host) = non_empty(context.host) { + body.insert("host".to_string(), serde_json::json!(host)); + } + if let Some(port) = context.port { + body.insert("port".to_string(), serde_json::json!(port)); + } + if let Some(binary) = non_empty(context.binary) { + body.insert("binary".to_string(), serde_json::json!(binary)); + } + + serde_json::Value::Object(body) +} + +fn middleware_failure_response_body( + req: &L7Request, + policy_name: &str, + redacted_target: Option<&str>, + context: Option>, +) -> serde_json::Value { + let target = redacted_target.unwrap_or(&req.target); + let context = context.unwrap_or_default(); + let mut body = serde_json::Map::new(); + body.insert("error".to_string(), serde_json::json!("middleware_failed")); + body.insert( + "detail".to_string(), + serde_json::json!("Request could not be processed by configured middleware"), + ); + body.insert("policy".to_string(), serde_json::json!(policy_name)); + body.insert("layer".to_string(), serde_json::json!("l7")); + body.insert("method".to_string(), serde_json::json!(req.action)); + body.insert("path".to_string(), serde_json::json!(target)); + if let Some(host) = non_empty(context.host) { + body.insert("host".to_string(), serde_json::json!(host)); + } + if let Some(port) = context.port { + body.insert("port".to_string(), serde_json::json!(port)); + } + if let Some(binary) = non_empty(context.binary) { + body.insert("binary".to_string(), serde_json::json!(binary)); + } + + serde_json::Value::Object(body) +} + fn deny_response_body( req: &L7Request, policy_name: &str, @@ -1699,20 +2449,25 @@ fn detect_payload_mode(headers: &str) -> Result { /// `Content-Length` and `Transfer-Encoding` headers to prevent request /// smuggling via CL/TE ambiguity. pub(crate) fn parse_body_length(headers: &str) -> Result { - let mut has_te_chunked = false; + let mut transfer_codings = Vec::new(); let mut cl_value: Option = None; for line in headers.lines().skip(1) { - let lower = line.to_ascii_lowercase(); - if lower.starts_with("transfer-encoding:") { - let val = lower.split_once(':').map_or("", |(_, v)| v.trim()); - if val.split(',').any(|enc| enc.trim() == "chunked") { - has_te_chunked = true; + let Some((name, value)) = line.split_once(':') else { + continue; + }; + if name.eq_ignore_ascii_case("transfer-encoding") { + for coding in value.split(',') { + let coding = coding.trim(); + if coding.is_empty() { + return Err(miette!("Request contains an empty Transfer-Encoding value")); + } + transfer_codings.push(coding.to_ascii_lowercase()); } } - if lower.starts_with("content-length:") { - let val = lower.split_once(':').map_or("", |(_, v)| v.trim()); - let len: u64 = val + if name.eq_ignore_ascii_case("content-length") { + let len: u64 = value + .trim() .parse() .map_err(|_| miette!("Request contains invalid Content-Length value"))?; if let Some(prev) = cl_value @@ -1726,14 +2481,19 @@ pub(crate) fn parse_body_length(headers: &str) -> Result { } } - if has_te_chunked && cl_value.is_some() { + if !transfer_codings.is_empty() && cl_value.is_some() { return Err(miette!( "Request contains both Transfer-Encoding and Content-Length headers" )); } - if has_te_chunked { - return Ok(BodyLength::Chunked); + if !transfer_codings.is_empty() { + if transfer_codings.len() == 1 && transfer_codings[0] == "chunked" { + return Ok(BodyLength::Chunked); + } + return Err(miette!( + "Request contains an unsupported Transfer-Encoding sequence" + )); } if let Some(len) = cl_value { return Ok(BodyLength::ContentLength(len)); @@ -2424,13 +3184,113 @@ mod tests { use crate::opa::OpaEngine; use flate2::{Compress, Compression, Decompress, FlushCompress, FlushDecompress, Status}; use openshell_core::secrets::SecretResolver; + use std::pin::Pin; use std::sync::Arc; + use std::task::{Context, Poll}; + use tokio::io::ReadBuf; const TEST_POLICY: &str = include_str!("../../data/sandbox-policy.rego"); const VALID_WS_KEY: &str = "dGhlIHNhbXBsZSBub25jZQ=="; const VALID_WS_ACCEPT: &str = "s3pPLMBiTxaQ9kYGzzhZRbK+xOo="; const TEXT_OPCODE: u8 = 0x1; + struct CountingReader { + bytes: Vec, + position: usize, + reads: usize, + } + + impl CountingReader { + fn new(bytes: Vec) -> Self { + Self { + bytes, + position: 0, + reads: 0, + } + } + } + + impl AsyncRead for CountingReader { + fn poll_read( + mut self: Pin<&mut Self>, + _context: &mut Context<'_>, + buffer: &mut ReadBuf<'_>, + ) -> Poll> { + self.reads += 1; + let available = self.bytes.len().saturating_sub(self.position); + let amount = available.min(buffer.remaining()); + let end = self.position + amount; + buffer.put_slice(&self.bytes[self.position..end]); + self.position = end; + Poll::Ready(Ok(())) + } + } + + fn write_header(name: &str, value: &str, on_existing: ExistingHeaderAction) -> HeaderMutation { + HeaderMutation { + operation: Some(header_mutation::Operation::Write( + openshell_core::proto::WriteHeader { + name: name.into(), + value: value.into(), + on_existing: on_existing as i32, + }, + )), + } + } + + fn remove_header(name: &str) -> HeaderMutation { + HeaderMutation { + operation: Some(header_mutation::Operation::Remove( + openshell_core::proto::RemoveHeader { name: name.into() }, + )), + } + } + + #[test] + fn ordered_header_mutations_replay_against_raw_request() { + let raw = b"GET / HTTP/1.1\r\nHost: example.test\r\nX-OpenShell-Middleware-Chain: first\r\nX-Drop: one\r\nX-Drop: two\r\n\r\n"; + let mutations = [ + write_header( + "x-openshell-middleware-chain", + "second", + ExistingHeaderAction::Append, + ), + write_header( + "x-openshell-middleware-chain", + "ignored", + ExistingHeaderAction::Skip, + ), + write_header( + "x-openshell-middleware-chain", + "replacement", + ExistingHeaderAction::Overwrite, + ), + write_header( + "x-openshell-middleware-chain", + "tail", + ExistingHeaderAction::Append, + ), + remove_header("x-drop"), + ]; + + let updated = String::from_utf8( + apply_header_mutations(raw, &mutations).expect("apply ordered header mutations"), + ) + .expect("UTF-8 request"); + let values: Vec<&str> = updated + .lines() + .filter_map(|line| { + line.split_once(':').and_then(|(name, value)| { + name.eq_ignore_ascii_case("x-openshell-middleware-chain") + .then_some(value.trim()) + }) + }) + .collect(); + assert_eq!(values, vec!["replacement", "tail"]); + assert!(!updated.to_ascii_lowercase().contains("x-drop:")); + assert!(updated.contains("Host: example.test")); + } + #[derive(Debug)] struct CapturedFrame { fin_opcode: u8, @@ -2802,6 +3662,47 @@ mod tests { ); } + #[test] + fn middleware_deny_response_identifies_config_without_policy_remediation() { + let _proposals = + openshell_core::proposals::test_helpers::ProposalsFlagGuard::set_blocking(true); + let req = L7Request { + action: "POST".to_string(), + target: "/v1/messages?token=secret-token".to_string(), + query_params: HashMap::new(), + raw_header: Vec::new(), + body_length: BodyLength::ContentLength(64), + }; + let denial = openshell_supervisor_middleware::MiddlewareDenial { + config_name: "prototype-content-guard".into(), + reason_code: Some("content_match".into()), + }; + + let body = middleware_deny_response_body( + &req, + "api-policy", + &denial, + Some("/v1/messages"), + Some(DenyResponseContext { + host: Some("api.example.com"), + port: Some(443), + binary: Some("/usr/bin/curl"), + }), + ); + + assert_eq!(body["error"], "middleware_denied"); + assert_eq!(body["detail"], "Request rejected by configured middleware"); + assert_eq!(body["middleware"], "prototype-content-guard"); + assert_eq!(body["reason_code"], "content_match"); + assert_eq!(body["policy"], "api-policy"); + assert_eq!(body["path"], "/v1/messages"); + assert!(body.get("rule").is_none()); + assert!(body.get("rule_missing").is_none()); + assert!(body.get("next_steps").is_none()); + assert!(body.get("agent_guidance").is_none()); + assert!(!body.to_string().contains("secret-token")); + } + #[tokio::test] async fn send_deny_response_writes_structured_json_403() { // Agent-readable next_steps is gated on the proposals feature flag. @@ -2852,11 +3753,79 @@ mod tests { } #[test] - fn parse_content_length() { - let headers = "POST /api HTTP/1.1\r\nHost: example.com\r\nContent-Length: 42\r\n\r\n"; - match parse_body_length(headers).unwrap() { - BodyLength::ContentLength(42) => {} - other => panic!("Expected ContentLength(42), got {other:?}"), + fn parse_content_length() { + let headers = "POST /api HTTP/1.1\r\nHost: example.com\r\nContent-Length: 42\r\n\r\n"; + match parse_body_length(headers).unwrap() { + BodyLength::ContentLength(42) => {} + other => panic!("Expected ContentLength(42), got {other:?}"), + } + } + + #[test] + fn buffered_request_parser_uses_shared_framing_and_query_parsing() { + let request = request_from_buffered_http( + "POST", + "/v1/items", + "/v1/items?tag=first&tag=second", + b"POST /v1/items?tag=first&tag=second HTTP/1.1\r\nHost: api.example.com\r\nContent-Length: 3\r\n\r\nabc" + .to_vec(), + ) + .expect("parse buffered request"); + + assert_eq!(request.action, "POST"); + assert_eq!(request.target, "/v1/items"); + assert_eq!( + request.query_params.get("tag"), + Some(&vec!["first".to_string(), "second".to_string()]) + ); + assert!(matches!(request.body_length, BodyLength::ContentLength(3))); + } + + #[test] + fn buffered_request_parser_rejects_missing_header_terminator() { + let err = request_from_buffered_http( + "GET", + "/v1/items", + "/v1/items", + b"GET /v1/items HTTP/1.1\r\nHost: api.example.com\r\n".to_vec(), + ) + .expect_err("unterminated headers must be rejected"); + + assert!(err.to_string().contains("missing the CRLF terminator")); + } + + #[test] + fn buffered_request_parser_rejects_malformed_header_fields() { + for raw in [ + b"GET /v1/items HTTP/1.1\r\nX-Test: first\r\n continued\r\n\r\n".as_slice(), + b"GET /v1/items HTTP/1.1\r\nX-Test value\r\n\r\n".as_slice(), + b"GET /v1/items HTTP/1.1\r\nX-Test : value\r\n\r\n".as_slice(), + b"GET /v1/items HTTP/1.1\r\nX@Test: value\r\n\r\n".as_slice(), + b"GET /v1/items HTTP/1.1\r\nX-Test: before\0after\r\n\r\n".as_slice(), + b"GET /v1/items HTTP/1.1\r\nX-Test: before\x7fafter\r\n\r\n".as_slice(), + b"GET /v1/items HTTP/1.1\r\nX-Test: before\rafter\r\n\r\n".as_slice(), + b"GET /v1/items HTTP/1.1\r\nConnection: x guard\r\n\r\n".as_slice(), + b"GET /v1/items HTTP/1.1\r\nConnection: content-length\r\nContent-Length: 0\r\n\r\n" + .as_slice(), + ] { + request_from_buffered_http("GET", "/v1/items", "/v1/items", raw.to_vec()) + .expect_err("malformed buffered header fields must be rejected"); + } + } + + #[test] + fn buffered_request_parser_rejects_malformed_request_lines() { + for raw in [ + b"GET /v1/items HTTP/1.1 extra\r\nHost: api.example.com\r\n\r\n".as_slice(), + b"GET /v1/items HTTP/1.1\r\nHost: api.example.com\r\n\r\n".as_slice(), + b"GET\t/v1/items HTTP/1.1\r\nHost: api.example.com\r\n\r\n".as_slice(), + b"GE(T /v1/items HTTP/1.1\r\nHost: api.example.com\r\n\r\n".as_slice(), + b"GET /v1/\0items HTTP/1.1\r\nHost: api.example.com\r\n\r\n".as_slice(), + b"GET /v1/items HTTP/2\r\nHost: api.example.com\r\n\r\n".as_slice(), + b"GET /v1/items\r\nHost: api.example.com\r\n\r\n".as_slice(), + ] { + request_from_buffered_http("GET", "/v1/items", "/v1/items", raw.to_vec()) + .expect_err("malformed buffered request lines must be rejected"); } } @@ -3029,13 +3998,496 @@ mod tests { ); } - /// SEC: Transfer-Encoding substring match must not match partial tokens. + /// SEC: Unsupported transfer codings must not be silently treated as no body. #[test] - fn te_substring_not_chunked() { - let headers = "POST /api HTTP/1.1\r\nHost: x\r\nTransfer-Encoding: chunkedx\r\n\r\n"; - match parse_body_length(headers).unwrap() { - BodyLength::None => {} - other => panic!("Expected None for non-matching TE, got {other:?}"), + fn reject_unsupported_transfer_encoding_sequences() { + for value in [ + "gzip", + "gzip, chunked", + "chunked, gzip", + "chunked, chunked", + "chunkedx", + "chunked,", + ] { + let headers = + format!("POST /api HTTP/1.1\r\nHost: x\r\nTransfer-Encoding: {value}\r\n\r\n"); + assert!( + parse_body_length(&headers).is_err(), + "unsupported transfer coding must be rejected: {value}" + ); + } + } + + #[test] + fn reject_multiple_chunked_transfer_encoding_fields() { + let headers = "POST /api HTTP/1.1\r\nHost: x\r\nTransfer-Encoding: chunked\r\nTransfer-Encoding: chunked\r\n\r\n"; + assert!(parse_body_length(headers).is_err()); + } + + #[test] + fn reject_content_length_with_unsupported_transfer_encoding() { + let headers = + "POST /api HTTP/1.1\r\nHost: x\r\nContent-Length: 4\r\nTransfer-Encoding: gzip\r\n\r\n"; + assert!(parse_body_length(headers).is_err()); + } + + #[test] + fn strip_connection_nominated_headers_before_forwarding() { + let raw = b"GET /api HTTP/1.1\r\nHost: x\r\nX-Guard: hidden\r\nConnection: keep-alive, x-guard\r\nKeep-Alive: timeout=5\r\nX-Visible: yes\r\n\r\n"; + let sanitized = + strip_connection_nominated_headers(raw, false).expect("sanitize request headers"); + let sanitized = String::from_utf8(sanitized).unwrap(); + + assert!(!sanitized.to_ascii_lowercase().contains("x-guard:")); + assert!(!sanitized.to_ascii_lowercase().contains("keep-alive:")); + assert!(!sanitized.to_ascii_lowercase().contains("connection:")); + assert!(sanitized.contains("X-Visible: yes\r\n")); + } + + #[test] + fn connection_sanitization_preserves_only_websocket_upgrade_exception() { + let raw = b"GET /ws HTTP/1.1\r\nHost: x\r\nUpgrade: h2c\r\nUpgrade: h2c, websocket\r\nConnection: keep-alive, Upgrade, x-guard\r\nX-Guard: hidden\r\n\r\n"; + let sanitized = + strip_connection_nominated_headers(raw, true).expect("sanitize websocket headers"); + let sanitized = String::from_utf8(sanitized).unwrap(); + + assert_eq!(sanitized.matches("Upgrade: websocket\r\n").count(), 1); + assert_eq!(sanitized.matches("Connection: Upgrade\r\n").count(), 1); + assert!(!sanitized.to_ascii_lowercase().contains("upgrade: h2c")); + assert!(!sanitized.to_ascii_lowercase().contains("x-guard:")); + assert!(!sanitized.contains("keep-alive")); + } + + #[tokio::test] + async fn middleware_fixed_read_ahead_consumes_expect_continue() { + for (already_read, remaining, should_acknowledge) in [ + (b"hello".as_slice(), b"".as_slice(), false), + (b"he".as_slice(), b"llo".as_slice(), true), + ] { + let mut raw = b"POST /api HTTP/1.1\r\nHost: example.com\r\nContent-Length: 5\r\nExpect: 100-continue\r\n\r\n".to_vec(); + raw.extend_from_slice(already_read); + let req = L7Request { + action: "POST".into(), + target: "/api".into(), + query_params: HashMap::new(), + raw_header: raw, + body_length: BodyLength::ContentLength(5), + }; + let (mut client, mut peer) = tokio::io::duplex(128); + peer.write_all(remaining).await.unwrap(); + + let result = buffer_request_body_for_middleware(&req, &mut client, None, 1024) + .await + .expect("fixed body should buffer"); + let BufferResult::Buffered(buffered) = result else { + panic!("fixed body unexpectedly exceeded capacity") + }; + assert_eq!(buffered.body, b"hello"); + assert!( + !String::from_utf8_lossy(&buffered.headers) + .to_ascii_lowercase() + .contains("expect:") + ); + + let mut response = [0u8; 64]; + let read = tokio::time::timeout( + std::time::Duration::from_millis(20), + peer.read(&mut response), + ) + .await; + if should_acknowledge { + let count = read.expect("partial body should be acknowledged").unwrap(); + assert_eq!(&response[..count], b"HTTP/1.1 100 Continue\r\n\r\n"); + } else { + assert!( + read.is_err(), + "complete read-ahead should not be acknowledged" + ); + } + } + } + + #[tokio::test] + async fn middleware_chunked_read_ahead_consumes_expect_continue() { + for (already_read, remaining, should_acknowledge) in [ + (b"5\r\nhello\r\n0\r\n\r\n".as_slice(), b"".as_slice(), false), + (b"5\r\nhe".as_slice(), b"llo\r\n0\r\n\r\n".as_slice(), true), + ] { + let mut raw = b"POST /api HTTP/1.1\r\nHost: example.com\r\nTransfer-Encoding: chunked\r\nExpect: 100-continue\r\n\r\n".to_vec(); + raw.extend_from_slice(already_read); + let req = L7Request { + action: "POST".into(), + target: "/api".into(), + query_params: HashMap::new(), + raw_header: raw, + body_length: BodyLength::Chunked, + }; + let (mut client, mut peer) = tokio::io::duplex(128); + peer.write_all(remaining).await.unwrap(); + + let result = buffer_request_body_for_middleware(&req, &mut client, None, 1024) + .await + .expect("chunked body should buffer"); + let BufferResult::Buffered(buffered) = result else { + panic!("chunked body unexpectedly exceeded capacity") + }; + assert_eq!(buffered.body, b"hello"); + assert!( + !String::from_utf8_lossy(&buffered.headers) + .to_ascii_lowercase() + .contains("expect:") + ); + + let mut response = [0u8; 64]; + let read = tokio::time::timeout( + std::time::Duration::from_millis(20), + peer.read(&mut response), + ) + .await; + if should_acknowledge { + let count = read.expect("partial body should be acknowledged").unwrap(); + assert_eq!(&response[..count], b"HTTP/1.1 100 Continue\r\n\r\n"); + } else { + assert!( + read.is_err(), + "complete read-ahead should not be acknowledged" + ); + } + } + } + + #[tokio::test] + async fn collect_chunked_body_decodes_payload_bytes() { + let mut client = tokio::io::empty(); + let body = collect_chunked_body( + &mut client, + b"5\r\nhello\r\n6;ext=value\r\n world\r\n0\r\n\r\n", + None, + None, + ) + .await + .expect("chunked body should decode"); + + assert_eq!(body, b"hello world"); + } + + #[tokio::test] + async fn middleware_chunked_request_with_trailers_is_rejected() { + let mut raw = b"POST /api HTTP/1.1\r\nHost: example.com\r\nTransfer-Encoding: chunked\r\nTrailer: X-Checksum\r\n\r\n".to_vec(); + raw.extend_from_slice(b"5\r\nhello\r\n0\r\nX-Checksum: digest\r\n\r\n"); + let req = L7Request { + action: "POST".into(), + target: "/api".into(), + query_params: HashMap::new(), + raw_header: raw, + body_length: BodyLength::Chunked, + }; + + let error = + buffer_request_body_for_middleware(&req, &mut tokio::io::empty(), None, 64 * 1024) + .await + .expect_err("middleware must reject non-empty chunked trailers"); + assert!( + error.to_string().contains( + "chunked request trailers are not supported when buffering or transforming request bodies" + ), + "unexpected error: {error}" + ); + } + + #[tokio::test] + async fn credential_rewrite_rejects_aggregate_chunk_extension_overflow() { + let mut wire = Vec::new(); + let chunk = format!("1;pad={}\r\nx\r\n", "a".repeat(64)); + while wire.len() <= MAX_REWRITE_BODY_BYTES { + wire.extend_from_slice(chunk.as_bytes()); + } + wire.extend_from_slice(b"0\r\n\r\n"); + + let req = L7Request { + action: "POST".into(), + target: "/api".into(), + query_params: HashMap::new(), + raw_header: Vec::new(), + body_length: BodyLength::Chunked, + }; + let headers = + b"POST /api HTTP/1.1\r\nHost: example.com\r\nTransfer-Encoding: chunked\r\n\r\n"; + let result = collect_and_rewrite_request_body( + &req, + &mut tokio::io::empty(), + headers, + std::str::from_utf8(headers).expect("headers"), + &wire, + None, + None, + ) + .await; + let Err(error) = result else { + panic!("aggregate chunk extensions must be bounded") + }; + assert!( + error + .to_string() + .contains("chunked body wire representation exceeds configured buffer limit"), + "unexpected error: {error}" + ); + } + + #[tokio::test] + async fn credential_rewrite_chunked_request_with_trailers_is_rejected() { + let req = L7Request { + action: "POST".into(), + target: "/api".into(), + query_params: HashMap::new(), + raw_header: Vec::new(), + body_length: BodyLength::Chunked, + }; + let headers = + b"POST /api HTTP/1.1\r\nHost: example.com\r\nTransfer-Encoding: chunked\r\nTrailer: Digest\r\n\r\n"; + let result = collect_and_rewrite_request_body( + &req, + &mut tokio::io::empty(), + headers, + std::str::from_utf8(headers).expect("headers"), + b"1\r\nx\r\n0\r\nDigest: sha-256=:abc123:\r\n\r\n", + None, + None, + ) + .await; + let Err(error) = result else { + panic!("credential rewriting must reject non-empty chunked trailers") + }; + assert!( + error.to_string().contains( + "chunked request trailers are not supported when buffering or transforming request bodies" + ), + "unexpected error: {error}" + ); + } + + #[tokio::test] + async fn collect_chunked_body_reads_payload_in_blocks() { + let payload_len = 64 * 1024; + let mut wire = format!("{payload_len:x}\r\n").into_bytes(); + wire.extend(std::iter::repeat_n(b'x', payload_len)); + wire.extend_from_slice(b"\r\n0\r\n\r\n"); + let mut client = CountingReader::new(wire); + + let body = collect_chunked_body( + &mut client, + &[], + None, + Some(openshell_supervisor_middleware::MAX_MIDDLEWARE_BODY_BYTES), + ) + .await + .expect("chunked body should decode"); + + assert_eq!(body.len(), payload_len); + assert!( + client.reads <= 32, + "payload should be read in blocks, observed {} reads", + client.reads + ); + } + + #[tokio::test] + async fn extreme_content_length_is_rejected_before_allocation() { + let req = L7Request { + action: "POST".into(), + target: "/upload".into(), + query_params: HashMap::new(), + raw_header: b"POST /upload HTTP/1.1\r\nHost: example.com\r\nContent-Length: 18446744073709551615\r\n\r\n".to_vec(), + body_length: BodyLength::ContentLength(u64::MAX), + }; + let (mut client, _peer) = tokio::io::duplex(1); + + let result = buffer_request_body_for_middleware( + &req, + &mut client, + None, + openshell_supervisor_middleware::MAX_MIDDLEWARE_BODY_BYTES, + ) + .await + .expect("oversized body should produce a capacity result"); + + assert!(matches!( + result, + BufferResult::OverCapacity { recoverable: true } + )); + } + + #[tokio::test] + async fn middleware_chunked_wire_body_at_cap_is_allowed() { + let max_body_bytes = max_middleware_body_bytes().await; + let payload_len = max_body_bytes - 14; + let mut wire = format!("{payload_len:x}\r\n").into_bytes(); + wire.extend(std::iter::repeat_n(b'x', payload_len)); + wire.extend_from_slice(b"\r\n0\r\n\r\n"); + assert_eq!(wire.len(), max_body_bytes); + + let body = collect_chunked_body(&mut tokio::io::empty(), &wire, None, Some(max_body_bytes)) + .await + .expect("wire representation at the cap should be allowed"); + + assert_eq!(body.len(), payload_len); + } + + #[tokio::test] + async fn middleware_chunked_wire_body_over_cap_is_rejected() { + let max_body_bytes = max_middleware_body_bytes().await; + let payload_len = max_body_bytes - 13; + let mut wire = format!("{payload_len:x}\r\n").into_bytes(); + wire.extend(std::iter::repeat_n(b'x', payload_len)); + wire.extend_from_slice(b"\r\n0\r\n\r\n"); + assert_eq!(wire.len(), max_body_bytes + 1); + assert!(payload_len < max_body_bytes); + + let error = + collect_chunked_body(&mut tokio::io::empty(), &wire, None, Some(max_body_bytes)) + .await + .expect_err("wire framing over the cap must be rejected"); + + assert!( + matches!(error, CollectChunkedError::OverCapacity), + "over-cap wire body must be OverCapacity, got {error:?}" + ); + } + + #[tokio::test] + async fn middleware_chunked_body_can_exceed_credential_rewrite_limit() { + let max_body_bytes = 1024 * 1024; + let payload_len = 300 * 1024; + assert!(payload_len > MAX_REWRITE_BODY_BYTES); + let mut wire = format!("{payload_len:x}\r\n").into_bytes(); + wire.extend(std::iter::repeat_n(b'x', payload_len)); + wire.extend_from_slice(b"\r\n0\r\n\r\n"); + + let body = collect_chunked_body(&mut tokio::io::empty(), &wire, None, Some(max_body_bytes)) + .await + .expect("middleware cap should control chunked body collection"); + + assert_eq!(body.len(), payload_len); + } + + #[tokio::test] + async fn middleware_chunked_invalid_size_is_not_over_capacity() { + let mut raw = + b"POST /api HTTP/1.1\r\nHost: example.com\r\nTransfer-Encoding: chunked\r\n\r\n" + .to_vec(); + raw.extend_from_slice(b"xyz\r\n"); + let req = L7Request { + action: "POST".into(), + target: "/api".into(), + query_params: HashMap::new(), + raw_header: raw, + body_length: BodyLength::Chunked, + }; + let err = + buffer_request_body_for_middleware(&req, &mut tokio::io::empty(), None, 64 * 1024) + .await + .expect_err("invalid chunk framing must surface as an error"); + + assert!( + err.to_string().contains("Invalid chunk size token"), + "unexpected error: {err}" + ); + assert!( + !err.to_string().contains("over_capacity") + && !err.to_string().contains("exceeds configured buffer limit"), + "protocol errors must not be reported as over-capacity: {err}" + ); + } + + #[tokio::test] + async fn middleware_chunked_over_capacity_still_maps_to_buffer_over_capacity() { + let max_body_bytes = 32; + let payload = "hello world that is definitely over the tiny cap"; + let wire = format!("{:x}\r\n{payload}\r\n0\r\n\r\n", payload.len()); + let mut raw = + b"POST /api HTTP/1.1\r\nHost: example.com\r\nTransfer-Encoding: chunked\r\n\r\n" + .to_vec(); + raw.extend_from_slice(wire.as_bytes()); + let req = L7Request { + action: "POST".into(), + target: "/api".into(), + query_params: HashMap::new(), + raw_header: raw, + body_length: BodyLength::Chunked, + }; + + let result = + buffer_request_body_for_middleware(&req, &mut tokio::io::empty(), None, max_body_bytes) + .await + .expect("over-capacity is a BufferResult, not an Err"); + + assert!( + matches!(result, BufferResult::OverCapacity { recoverable: false }), + "expected OverCapacity, got {result:?}" + ); + } + + #[tokio::test] + async fn middleware_none_body_with_header_overshoot_is_rejected() { + // Mimic the forward-proxy multi-byte read: headers plus pipelined bytes + // after `\r\n\r\n` on a request with no body framing. + let raw = b"GET /api HTTP/1.1\r\nHost: example.com\r\n\r\nGET /other HTTP/1.1\r\n"; + let req = L7Request { + action: "GET".into(), + target: "/api".into(), + query_params: HashMap::new(), + raw_header: raw.to_vec(), + body_length: BodyLength::None, + }; + + let err = + buffer_request_body_for_middleware(&req, &mut tokio::io::empty(), None, 64 * 1024) + .await + .expect_err("read-ahead leftovers must not become a request body"); + + assert!( + err.to_string().contains("no body framing"), + "unexpected error: {err}" + ); + } + + #[tokio::test] + async fn middleware_none_body_without_overshoot_buffers_empty() { + let raw = b"GET /api HTTP/1.1\r\nHost: example.com\r\n\r\n"; + let req = L7Request { + action: "GET".into(), + target: "/api".into(), + query_params: HashMap::new(), + raw_header: raw.to_vec(), + body_length: BodyLength::None, + }; + + let result = + buffer_request_body_for_middleware(&req, &mut tokio::io::empty(), None, 64 * 1024) + .await + .expect("empty no-body request should buffer"); + + match result { + BufferResult::Buffered(buffered) => { + assert!(buffered.body.is_empty()); + let rebuilt = rebuild_request_with_buffered_body( + &req, + &buffered.headers, + &buffered.body, + &[], + ) + .expect("rebuild no-body request"); + assert!(matches!(rebuilt.body_length, BodyLength::None)); + let text = String::from_utf8(rebuilt.raw_header).unwrap(); + assert!( + !text.to_ascii_lowercase().contains("content-length"), + "rebuild must preserve no-body framing: {text}" + ); + assert!(!text.contains("GET /other")); + } + other @ BufferResult::OverCapacity { .. } => { + panic!("expected Buffered, got {other:?}") + } } } @@ -3077,6 +4529,43 @@ mod tests { assert!(result.is_err(), "Must reject headers with invalid UTF-8"); } + #[tokio::test] + async fn reject_malformed_header_fields_before_forwarding() { + let cases = [ + ( + "space continuation", + b"GET /api HTTP/1.1\r\nX-Test: first\r\n continued\r\nHost: x\r\n\r\n".as_slice(), + ), + ( + "tab continuation", + b"GET /api HTTP/1.1\r\nX-Test: first\r\n\tcontinued\r\nHost: x\r\n\r\n".as_slice(), + ), + ( + "missing colon", + b"GET /api HTTP/1.1\r\nX-Test value\r\nHost: x\r\n\r\n".as_slice(), + ), + ( + "whitespace before colon", + b"GET /api HTTP/1.1\r\nX-Test : value\r\nHost: x\r\n\r\n".as_slice(), + ), + ( + "invalid field-name token", + b"GET /api HTTP/1.1\r\nX@Test: value\r\nHost: x\r\n\r\n".as_slice(), + ), + ]; + + for (case, raw) in cases { + let (mut client, mut writer) = tokio::io::duplex(4096); + writer.write_all(raw).await.unwrap(); + let result = parse_http_request( + &mut client, + &crate::l7::path::CanonicalizeOptions::default(), + ) + .await; + assert!(result.is_err(), "{case} must be rejected before forwarding"); + } + } + /// SEC-009: Reject unsupported HTTP versions. #[tokio::test] async fn reject_invalid_http_version() { @@ -5096,6 +6585,33 @@ mod tests { .map_err(|e| miette!("upstream task failed: {e}")) } + #[tokio::test] + async fn connect_rest_relay_strips_connection_nominated_headers_upstream() { + let raw = b"GET /api HTTP/1.1\r\nHost: api.example.com\r\nX-Guard: hidden\r\nConnection: keep-alive, x-guard\r\nKeep-Alive: timeout=5\r\nX-Visible: yes\r\n\r\n".to_vec(); + let forwarded = relay_and_capture_with_options(raw, BodyLength::None, None, false) + .await + .expect("relay request"); + let lower = forwarded.to_ascii_lowercase(); + + assert!(!lower.contains("x-guard:")); + assert!(!lower.contains("keep-alive:")); + assert!(!lower.contains("connection:")); + assert!(forwarded.contains("X-Visible: yes\r\n")); + } + + #[tokio::test] + async fn connect_rest_relay_canonicalizes_websocket_upgrade_headers() { + let raw = b"GET /ws HTTP/1.1\r\nHost: api.example.com\r\nUpgrade: h2c\r\nUpgrade: h2c, websocket\r\nConnection: keep-alive, Upgrade\r\nSec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\nSec-WebSocket-Version: 13\r\n\r\n".to_vec(); + let forwarded = relay_and_capture_with_options(raw, BodyLength::None, None, false) + .await + .expect("relay websocket request"); + let lower = forwarded.to_ascii_lowercase(); + + assert_eq!(lower.matches("connection: upgrade\r\n").count(), 1); + assert_eq!(lower.matches("upgrade: websocket\r\n").count(), 1); + assert!(!lower.contains("upgrade: h2c")); + } + #[tokio::test] async fn relay_request_body_rewrites_provider_alias_header_and_urlencoded_token() { let (_, resolver) = SecretResolver::from_provider_env( @@ -5132,6 +6648,38 @@ mod tests { assert!(!forwarded.contains("OPENSHELL-RESOLVE-ENV")); } + #[tokio::test] + async fn relay_request_body_rewrite_normalizes_chunked_payload() { + let (_, resolver) = SecretResolver::from_provider_env( + [("API_TOKEN".to_string(), "provider-real-token".to_string())] + .into_iter() + .collect(), + ); + let resolver = resolver.expect("resolver"); + let alias = "provider.v1-OPENSHELL-RESOLVE-ENV-API_TOKEN"; + let raw = format!( + "POST /api/messages HTTP/1.1\r\n\ + Host: api.example.com\r\n\ + Authorization: Bearer {alias}\r\n\ + Transfer-Encoding: chunked\r\n\r\n\ + 5\r\nhello\r\n0\r\n\r\n", + ); + + let forwarded = relay_and_capture_with_options( + raw.into_bytes(), + BodyLength::Chunked, + Some(&resolver), + true, + ) + .await + .expect("relay should succeed"); + + assert!(forwarded.contains("Authorization: Bearer provider-real-token\r\n")); + assert!(forwarded.contains("Content-Length: 5\r\n")); + assert!(!forwarded.contains("Transfer-Encoding: chunked\r\n")); + assert!(forwarded.ends_with("hello")); + } + #[tokio::test] async fn relay_request_body_rewrites_percent_encoded_canonical_urlencoded_token() { let (_, resolver) = SecretResolver::from_provider_env( diff --git a/crates/openshell-supervisor-network/src/l7/token_grant_injection.rs b/crates/openshell-supervisor-network/src/l7/token_grant_injection.rs index 0d7c18e996..07a8c641f1 100644 --- a/crates/openshell-supervisor-network/src/l7/token_grant_injection.rs +++ b/crates/openshell-supervisor-network/src/l7/token_grant_injection.rs @@ -199,45 +199,16 @@ fn dynamic_credential_key_match_score( return None; } - let host_lc = host.to_ascii_lowercase(); - let endpoint_host_lc = endpoint_host.to_ascii_lowercase(); - if !host_pattern_matches(&endpoint_host_lc, &host_lc) + if !openshell_core::host_pattern::host_matches(endpoint_host, host).unwrap_or(false) || !crate::l7::endpoint_path_matches(endpoint_path, request_path) { return None; } - Some(host_pattern_specificity(&endpoint_host_lc) + endpoint_path_specificity(endpoint_path)) -} - -fn host_pattern_matches(pattern: &str, host: &str) -> bool { - if pattern == host { - return true; - } - if !pattern.contains('*') { - return false; - } - - let pattern_labels: Vec<&str> = pattern.split('.').collect(); - let host_labels: Vec<&str> = host.split('.').collect(); - host_pattern_labels_match(&pattern_labels, &host_labels) -} - -fn host_pattern_labels_match(pattern: &[&str], host: &[&str]) -> bool { - match pattern.split_first() { - None => host.is_empty(), - Some((label, rest)) if *label == "**" => { - host_pattern_labels_match(rest, host) - || (!host.is_empty() && host_pattern_labels_match(pattern, &host[1..])) - } - Some((label, rest)) if *label == "*" => { - !host.is_empty() && host_pattern_labels_match(rest, &host[1..]) - } - Some((literal, rest)) => { - host.first().is_some_and(|label| label == literal) - && host_pattern_labels_match(rest, &host[1..]) - } - } + Some( + host_pattern_specificity(&endpoint_host.to_ascii_lowercase()) + + endpoint_path_specificity(endpoint_path), + ) } fn host_pattern_specificity(pattern: &str) -> u32 { @@ -575,6 +546,24 @@ mod tests { )); } + #[test] + fn dynamic_credential_key_matches_case_insensitive_intra_label_wildcard() { + let key = "*-API.Example.COM\t443\t\tprovider:access_token"; + + assert!(dynamic_credential_key_matches( + key, + "tenant-api.example.com", + 443, + "/anything" + )); + assert!(!dynamic_credential_key_matches( + key, + "api.deep.example.com", + 443, + "/anything" + )); + } + #[test] fn dynamic_credential_key_matches_double_wildcard_hosts() { let key = "**.example.com\t443\t\tprovider:access_token"; diff --git a/crates/openshell-supervisor-network/src/opa.rs b/crates/openshell-supervisor-network/src/opa.rs index 935946920d..313548aedf 100644 --- a/crates/openshell-supervisor-network/src/opa.rs +++ b/crates/openshell-supervisor-network/src/opa.rs @@ -8,14 +8,16 @@ //! on every proxy CONNECT request. use miette::Result; +use openshell_core::host_pattern::HostSelector; use openshell_core::policy::{ FilesystemPolicy, LandlockCompatibility, LandlockPolicy, ProcessPolicy, }; use openshell_core::proto::SandboxPolicy as ProtoSandboxPolicy; use openshell_policy::L7ConfigStanza; +use openshell_supervisor_middleware::{ChainEntry, ChainRunner, MiddlewareRegistry}; use std::path::{Path, PathBuf}; use std::sync::{ - Arc, Mutex, + Arc, Mutex, RwLock, atomic::{AtomicU64, Ordering}, }; use tracing::info; @@ -25,6 +27,11 @@ use tracing::info; /// passthroughs. They reference `data.sandbox.*` for policy data. const BAKED_POLICY_RULES: &str = include_str!("../data/sandbox-policy.rego"); +/// Implementation-owned middleware config validation supplied by the active +/// in-process catalog for local policy files. +pub type MiddlewareConfigValidator = + dyn Fn(&str, &prost_types::Struct) -> Result<(), String> + Send + Sync; + /// Result of evaluating a network access request against OPA policy. pub struct PolicyDecision { pub allowed: bool, @@ -115,6 +122,7 @@ pub struct SandboxConfig { pub struct OpaEngine { engine: Mutex, generation: Arc, + middleware_runner: RwLock, } /// Generation guard captured when an HTTP tunnel or request path starts. @@ -154,6 +162,7 @@ impl PolicyGenerationGuard { pub struct TunnelPolicyEngine { engine: Mutex, generation_guard: PolicyGenerationGuard, + middleware_runner: ChainRunner, } impl TunnelPolicyEngine { @@ -176,6 +185,19 @@ impl TunnelPolicyEngine { pub(crate) fn engine(&self) -> &Mutex { &self.engine } + + pub(crate) fn middleware_runner(&self) -> &ChainRunner { + &self.middleware_runner + } + + /// Query the ordered middleware chain for a destination within this tunnel. + pub fn query_middleware_chain(&self, input: &NetworkInput) -> Result> { + let mut engine = self + .engine + .lock() + .map_err(|_| miette::miette!("OPA engine lock poisoned"))?; + query_middleware_chain_locked(&mut engine, input) + } } impl OpaEngine { @@ -183,6 +205,16 @@ impl OpaEngine { /// /// Preprocesses the YAML data to expand access presets and validate L7 config. pub fn from_files(policy_path: &Path, data_path: &Path) -> Result { + Self::from_files_with_middleware_config(policy_path, data_path, None) + } + + /// Load local policy files and validate implementation-owned middleware + /// config through the catalog installed by the supervisor. + pub fn from_files_with_middleware_config( + policy_path: &Path, + data_path: &Path, + validate_middleware_config: Option<&MiddlewareConfigValidator>, + ) -> Result { let yaml_str = std::fs::read_to_string(data_path).map_err(|e| { miette::miette!("failed to read YAML data from {}: {e}", data_path.display()) })?; @@ -192,13 +224,18 @@ impl OpaEngine { .map_err(|e| miette::miette!("{e}"))?; let require_binary_identity = network_binary_identity_required(); emit_binary_identity_mode(require_binary_identity, "files"); - let data_json = preprocess_yaml_data(&yaml_str, require_binary_identity)?; + let data_json = preprocess_yaml_data( + &yaml_str, + require_binary_identity, + validate_middleware_config, + )?; engine .add_data_json(&data_json) .map_err(|e| miette::miette!("{e}"))?; Ok(Self { engine: Mutex::new(engine), generation: Arc::new(AtomicU64::new(0)), + middleware_runner: RwLock::new(ChainRunner::default()), }) } @@ -206,30 +243,54 @@ impl OpaEngine { /// /// Preprocesses the YAML data to expand access presets and validate L7 config. pub fn from_strings(policy: &str, data_yaml: &str) -> Result { - Self::from_strings_with_binary_identity_required( + Self::from_strings_with_options(policy, data_yaml, network_binary_identity_required(), None) + } + + pub fn from_strings_with_middleware_config( + policy: &str, + data_yaml: &str, + validate_middleware_config: Option<&MiddlewareConfigValidator>, + ) -> Result { + Self::from_strings_with_options( policy, data_yaml, network_binary_identity_required(), + validate_middleware_config, ) } + #[cfg(test)] pub(crate) fn from_strings_with_binary_identity_required( policy: &str, data_yaml: &str, require_binary_identity: bool, + ) -> Result { + Self::from_strings_with_options(policy, data_yaml, require_binary_identity, None) + } + + fn from_strings_with_options( + policy: &str, + data_yaml: &str, + require_binary_identity: bool, + validate_middleware_config: Option<&MiddlewareConfigValidator>, ) -> Result { let mut engine = regorus::Engine::new(); engine .add_policy("policy.rego".into(), policy.into()) .map_err(|e| miette::miette!("{e}"))?; emit_binary_identity_mode(require_binary_identity, "strings"); - let data_json = preprocess_yaml_data(data_yaml, require_binary_identity)?; + let data_json = preprocess_yaml_data( + data_yaml, + require_binary_identity, + validate_middleware_config, + )?; engine .add_data_json(&data_json) .map_err(|e| miette::miette!("{e}"))?; Ok(Self { engine: Mutex::new(engine), generation: Arc::new(AtomicU64::new(0)), + middleware_runner: RwLock::new(ChainRunner::default()), }) } @@ -265,6 +326,15 @@ impl OpaEngine { require_binary_identity: bool, ) -> Result { emit_binary_identity_mode(require_binary_identity, "proto"); + if let Err(violations) = openshell_policy::validate_sandbox_policy(proto) { + let errors = violations + .iter() + .map(ToString::to_string) + .collect::>() + .join("\n"); + return Err(miette::miette!("policy validation failed:\n{errors}")); + } + let data_json_str = proto_to_opa_data_json(proto, entrypoint_pid); // Parse back to Value for preprocessing, then re-serialize @@ -308,6 +378,7 @@ impl OpaEngine { Ok(Self { engine: Mutex::new(engine), generation: Arc::new(AtomicU64::new(0)), + middleware_runner: RwLock::new(ChainRunner::default()), }) } @@ -317,27 +388,7 @@ impl OpaEngine { /// `allow_network` rule, and returns a `PolicyDecision` with the result, /// deny reason, and matched policy name. pub fn evaluate_network(&self, input: &NetworkInput) -> Result { - let ancestor_strs: Vec = input - .ancestors - .iter() - .map(|p| p.to_string_lossy().into_owned()) - .collect(); - let cmdline_strs: Vec = input - .cmdline_paths - .iter() - .map(|p| p.to_string_lossy().into_owned()) - .collect(); - let input_json = serde_json::json!({ - "exec": { - "path": input.binary_path.to_string_lossy(), - "ancestors": ancestor_strs, - "cmdline_paths": cmdline_strs, - }, - "network": { - "host": input.host, - "port": input.port, - } - }); + let input_json = network_input_json(input); let mut engine = self .engine @@ -387,27 +438,7 @@ impl OpaEngine { &self, input: &NetworkInput, ) -> Result<(NetworkAction, u64)> { - let ancestor_strs: Vec = input - .ancestors - .iter() - .map(|p| p.to_string_lossy().into_owned()) - .collect(); - let cmdline_strs: Vec = input - .cmdline_paths - .iter() - .map(|p| p.to_string_lossy().into_owned()) - .collect(); - let input_json = serde_json::json!({ - "exec": { - "path": input.binary_path.to_string_lossy(), - "ancestors": ancestor_strs, - "cmdline_paths": cmdline_strs, - }, - "network": { - "host": input.host, - "port": input.port, - } - }); + let input_json = network_input_json(input); let mut engine = self .engine @@ -500,11 +531,76 @@ impl OpaEngine { Ok(()) } + /// Reload the policy and middleware registry as one runtime generation. + /// + /// Both replacements are prepared before the live locks are acquired. The + /// engine and runner are then swapped while holding both locks, followed by + /// a single generation increment. A preparation or lock failure leaves the + /// live pair and generation untouched. + pub fn reload_policy_and_middleware_from_proto_with_pid( + &self, + proto: &ProtoSandboxPolicy, + entrypoint_pid: u32, + registry: MiddlewareRegistry, + ) -> Result<()> { + let new = Self::from_proto_with_pid(proto, entrypoint_pid)?; + let new_engine = new + .engine + .into_inner() + .map_err(|_| miette::miette!("lock poisoned on new engine"))?; + let new_runner = ChainRunner::from_registry(registry); + + // Match clone_engine_for_tunnel's lock order (engine, then runner) so + // readers can observe only the old pair or the new pair. + let mut engine = self + .engine + .lock() + .map_err(|_| miette::miette!("OPA engine lock poisoned"))?; + let mut runner = self + .middleware_runner + .write() + .map_err(|_| miette::miette!("middleware runner lock poisoned"))?; + *engine = new_engine; + *runner = new_runner; + self.generation.fetch_add(1, Ordering::AcqRel); + Ok(()) + } + /// Current policy generation. Successful reloads increment this value. pub fn current_generation(&self) -> u64 { self.generation.load(Ordering::Acquire) } + /// Replace the complete middleware service registry and invalidate + /// existing tunnels so subsequent requests use the new service set. + pub fn replace_middleware_registry(&self, registry: MiddlewareRegistry) -> Result<()> { + let mut runner = self + .middleware_runner + .write() + .map_err(|_| miette::miette!("middleware runner lock poisoned"))?; + *runner = ChainRunner::from_registry(registry); + self.generation.fetch_add(1, Ordering::AcqRel); + Ok(()) + } + + pub(crate) fn middleware_runner(&self) -> Result { + self.middleware_runner + .read() + .map(|runner| runner.clone()) + .map_err(|_| miette::miette!("middleware runner lock poisoned")) + } + + /// Test-only: swap the middleware runner without a connected registry, so + /// relay tests can inject scripted middleware services. Does not bump the + /// policy generation; call before capturing tunnel engines. + #[cfg(test)] + pub(crate) fn set_middleware_runner_for_tests(&self, runner: ChainRunner) { + *self + .middleware_runner + .write() + .expect("middleware runner lock") = runner; + } + /// Return a guard for a previously captured policy generation. pub fn generation_guard(&self, expected_generation: u64) -> Result { let generation = self.current_generation(); @@ -578,27 +674,7 @@ impl OpaEngine { &self, input: &NetworkInput, ) -> Result<(Vec, u64)> { - let ancestor_strs: Vec = input - .ancestors - .iter() - .map(|p| p.to_string_lossy().into_owned()) - .collect(); - let cmdline_strs: Vec = input - .cmdline_paths - .iter() - .map(|p| p.to_string_lossy().into_owned()) - .collect(); - let input_json = serde_json::json!({ - "exec": { - "path": input.binary_path.to_string_lossy(), - "ancestors": ancestor_strs, - "cmdline_paths": cmdline_strs, - }, - "network": { - "host": input.host, - "port": input.port, - } - }); + let input_json = network_input_json(input); let mut engine = self .engine @@ -621,6 +697,20 @@ impl OpaEngine { } } + /// Query the ordered middleware chain for an admitted destination. + pub fn query_middleware_chain_with_generation( + &self, + input: &NetworkInput, + ) -> Result<(Vec, u64)> { + let mut engine = self + .engine + .lock() + .map_err(|_| miette::miette!("OPA engine lock poisoned"))?; + let generation = self.current_generation(); + let chain = query_middleware_chain_locked(&mut engine, input)?; + Ok((chain, generation)) + } + /// Query `allowed_ips` from the matched endpoint config for a given request. /// /// Returns the list of CIDR/IP strings from the endpoint's `allowed_ips` @@ -642,27 +732,7 @@ impl OpaEngine { /// denial while preserving separate handling for `allowed_ips` and advisor /// proposals. pub fn query_exact_declared_endpoint_host(&self, input: &NetworkInput) -> Result { - let ancestor_strs: Vec = input - .ancestors - .iter() - .map(|p| p.to_string_lossy().into_owned()) - .collect(); - let cmdline_strs: Vec = input - .cmdline_paths - .iter() - .map(|p| p.to_string_lossy().into_owned()) - .collect(); - let input_json = serde_json::json!({ - "exec": { - "path": input.binary_path.to_string_lossy(), - "ancestors": ancestor_strs, - "cmdline_paths": cmdline_strs, - }, - "network": { - "host": input.host, - "port": input.port, - } - }); + let input_json = network_input_json(input); let mut engine = self .engine @@ -702,6 +772,7 @@ impl OpaEngine { captured_generation: generation, current_generation: Arc::clone(&self.generation), }, + middleware_runner: self.middleware_runner()?, }) } } @@ -760,6 +831,175 @@ fn get_str_array(val: ®orus::Value, key: &str) -> Vec { } } +fn network_input_json(input: &NetworkInput) -> serde_json::Value { + let ancestor_strs: Vec = input + .ancestors + .iter() + .map(|p| p.to_string_lossy().into_owned()) + .collect(); + let cmdline_strs: Vec = input + .cmdline_paths + .iter() + .map(|p| p.to_string_lossy().into_owned()) + .collect(); + serde_json::json!({ + "exec": { + "path": input.binary_path.to_string_lossy(), + "ancestors": ancestor_strs, + "cmdline_paths": cmdline_strs, + }, + "network": { + "host": input.host, + "port": input.port, + } + }) +} + +fn query_middleware_chain_locked( + engine: &mut regorus::Engine, + input: &NetworkInput, +) -> Result> { + let configs_val = engine + .eval_rule("data.openshell.sandbox.network_middlewares".into()) + .map_err(|e| miette::miette!("{e}"))?; + let configs = parse_middleware_configs(&configs_val)?; + if configs.is_empty() { + return Ok(Vec::new()); + } + global_middleware_entries(&configs, &input.host) +} + +fn parse_middleware_configs(value: ®orus::Value) -> Result> { + match value { + regorus::Value::Undefined => Ok(Vec::new()), + regorus::Value::Object(configs) => configs + .iter() + .map(|(name, config)| { + let regorus::Value::String(_) = name else { + return Err(miette::miette!("network_middlewares keys must be strings")); + }; + let regorus::Value::Object(fields) = config else { + return Err(miette::miette!( + "network middleware config {name:?} must be an object" + )); + }; + let fields = fields + .iter() + .map(|(key, value)| (key.clone(), value.clone())) + .chain(std::iter::once(( + regorus::Value::String("__openshell_policy_key".into()), + name.clone(), + ))) + .collect::>(); + Ok(fields.into()) + }) + .collect(), + other => Err(miette::miette!( + "network_middlewares must be an object, got {other:?}" + )), + } +} + +fn global_middleware_entries(configs: &[regorus::Value], host: &str) -> Result> { + let mut entries = Vec::new(); + for config in configs { + if middleware_selector_matches(config, host)? { + if entries.len() >= openshell_supervisor_middleware::MAX_MIDDLEWARE_CHAIN_STAGES { + return Err(miette::miette!( + "selected middleware stage count exceeds platform maximum {}", + openshell_supervisor_middleware::MAX_MIDDLEWARE_CHAIN_STAGES + )); + } + entries.push(chain_entry_from_value(config)?); + } + } + openshell_supervisor_middleware::sort_chain_entries(&mut entries); + Ok(entries) +} + +fn middleware_selector_matches(config: ®orus::Value, host: &str) -> Result { + let Some(selector) = get_field(config, "endpoints") else { + return Ok(false); + }; + let include = get_str_array(selector, "include"); + let exclude = get_str_array(selector, "exclude"); + let selector = HostSelector::new(&include, &exclude).map_err(|error| miette::miette!(error))?; + Ok(selector.matches(host)) +} + +fn chain_entry_from_value(value: ®orus::Value) -> Result { + let name = get_str(value, "__openshell_policy_key").unwrap_or_default(); + let implementation = get_str(value, "middleware").unwrap_or_default(); + Ok(ChainEntry { + name, + implementation, + order: get_field(value, "order") + .and_then(|value| match value { + regorus::Value::Number(number) => number.as_i64(), + _ => None, + }) + .and_then(|value| i32::try_from(value).ok()) + .unwrap_or_default(), + config: get_field(value, "config") + .map(regorus_value_to_struct) + .unwrap_or_default(), + on_error: openshell_supervisor_middleware::OnError::parse( + get_str(value, "on_error").as_deref().unwrap_or_default(), + )?, + }) +} + +fn get_field<'a>(val: &'a regorus::Value, key: &str) -> Option<&'a regorus::Value> { + let key_val = regorus::Value::String(key.into()); + match val { + regorus::Value::Object(map) => map.get(&key_val), + _ => None, + } +} + +fn regorus_value_to_struct(value: ®orus::Value) -> prost_types::Struct { + let regorus::Value::Object(map) = value else { + return prost_types::Struct::default(); + }; + prost_types::Struct { + fields: map + .iter() + .filter_map(|(key, value)| match key { + regorus::Value::String(key) => { + Some((key.to_string(), regorus_value_to_prost(value))) + } + _ => None, + }) + .collect(), + } +} + +fn regorus_value_to_prost(value: ®orus::Value) -> prost_types::Value { + use prost_types::{ListValue, Struct, Value, value::Kind}; + Value { + kind: Some(match value { + regorus::Value::Bool(value) => Kind::BoolValue(*value), + regorus::Value::Number(value) => Kind::NumberValue(value.as_f64().unwrap_or_default()), + regorus::Value::String(value) => Kind::StringValue(value.to_string()), + regorus::Value::Array(values) => Kind::ListValue(ListValue { + values: values.iter().map(regorus_value_to_prost).collect(), + }), + regorus::Value::Object(values) => Kind::StructValue(Struct { + fields: values + .iter() + .filter_map(|(key, value)| match key { + regorus::Value::String(key) => { + Some((key.to_string(), regorus_value_to_prost(value))) + } + _ => None, + }) + .collect(), + }), + _ => Kind::NullValue(0), + }), + } +} + fn parse_filesystem_policy(val: ®orus::Value) -> FilesystemPolicy { FilesystemPolicy { read_only: get_str_array(val, "read_only") @@ -793,7 +1033,11 @@ fn parse_process_policy(val: ®orus::Value) -> ProcessPolicy { } /// Preprocess YAML policy data: parse, normalize, validate, expand access presets, return JSON. -fn preprocess_yaml_data(yaml_str: &str, require_binary_identity: bool) -> Result { +fn preprocess_yaml_data( + yaml_str: &str, + require_binary_identity: bool, + validate_middleware_config: Option<&MiddlewareConfigValidator>, +) -> Result { let mut data: serde_json::Value = serde_yml::from_str(yaml_str) .map_err(|e| miette::miette!("failed to parse YAML data: {e}"))?; inject_runtime_policy_data(&mut data, require_binary_identity); @@ -809,6 +1053,25 @@ fn preprocess_yaml_data(yaml_str: &str, require_binary_identity: bool) -> Result } // Validate BEFORE expanding presets (catches user errors like rules+access) + let middleware_errors = validate_middleware_config + .map_or_else( + || openshell_policy::validate_network_middleware_json(&data), + |validate| { + openshell_policy::validate_network_middleware_json_with_config(&data, validate) + }, + ) + .map_err(|error| miette::miette!(error))?; + if !middleware_errors.is_empty() { + return Err(miette::miette!( + "middleware policy validation failed:\n{}", + middleware_errors + .iter() + .map(ToString::to_string) + .collect::>() + .join("\n") + )); + } + let (errors, warnings) = crate::l7::validate_l7_policies(&data); for w in &warnings { openshell_ocsf::ocsf_emit!( @@ -1415,14 +1678,44 @@ fn proto_to_opa_data_json(proto: &ProtoSandboxPolicy, entrypoint_pid: u32) -> St entries }) .collect(); - ( - key.clone(), - serde_json::json!({ - "name": rule.name, - "endpoints": endpoints, - "binaries": binaries, - }), - ) + let policy = serde_json::json!({ + "name": rule.name, + "endpoints": endpoints, + "binaries": binaries, + }); + (key.clone(), policy) + }) + .collect(); + + let mut middleware_entries: Vec<_> = proto.network_middlewares.iter().collect(); + middleware_entries.sort_by_key(|(name, _)| name.as_str()); + let network_middlewares: serde_json::Map = middleware_entries + .into_iter() + .map(|(name, mw)| { + let mut value = serde_json::json!({ + "middleware": mw.middleware, + "order": mw.order, + }); + if !mw.name.is_empty() { + value["name"] = mw.name.clone().into(); + } + if let Some(config) = &mw.config { + value["config"] = openshell_core::proto_struct::struct_to_json_value(config); + } + if !mw.on_error.is_empty() { + value["on_error"] = mw.on_error.clone().into(); + } + if let Some(selector) = &mw.endpoints { + let mut endpoints = serde_json::json!({}); + if !selector.include.is_empty() { + endpoints["include"] = selector.include.clone().into(); + } + if !selector.exclude.is_empty() { + endpoints["exclude"] = selector.exclude.clone().into(); + } + value["endpoints"] = endpoints; + } + (name.clone(), value) }) .collect(); @@ -1431,6 +1724,7 @@ fn proto_to_opa_data_json(proto: &ProtoSandboxPolicy, entrypoint_pid: u32) -> St "landlock": landlock, "process": process, "network_policies": network_policies, + "network_middlewares": network_middlewares, }) .to_string() } @@ -1448,7 +1742,7 @@ mod tests { use openshell_core::proto::{ FilesystemPolicy as ProtoFs, L7Allow, L7QueryMatcher, L7Rule, NetworkBinary, - NetworkEndpoint, NetworkPolicyRule, ProcessPolicy as ProtoProc, + NetworkEndpoint, NetworkMiddlewareConfig, NetworkPolicyRule, ProcessPolicy as ProtoProc, SandboxPolicy as ProtoSandboxPolicy, }; @@ -1513,6 +1807,7 @@ mod tests { run_as_group: "sandbox".to_string(), }), network_policies, + network_middlewares: std::collections::HashMap::default(), } } @@ -2430,6 +2725,7 @@ process: run_as_group: "sandbox".to_string(), }), network_policies, + network_middlewares: std::collections::HashMap::default(), }; let engine = OpaEngine::from_proto_with_pid_and_binary_identity_required(&proto, 0, false) .expect("engine from relaxed proto"); @@ -2754,6 +3050,7 @@ network_policies: let engine = OpaEngine { engine: Mutex::new(rego), generation: Arc::new(AtomicU64::new(0)), + middleware_runner: RwLock::new(ChainRunner::default()), }; let input = l7_websocket_graphql_input( "realtime.graphql.com", @@ -2971,6 +3268,7 @@ network_policies: run_as_group: "sandbox".to_string(), }), network_policies, + network_middlewares: std::collections::HashMap::default(), }; let engine = OpaEngine::from_proto(&proto).expect("engine from proto"); @@ -3042,6 +3340,7 @@ network_policies: run_as_group: "sandbox".to_string(), }), network_policies, + network_middlewares: std::collections::HashMap::default(), }; let engine = OpaEngine::from_proto(&proto).expect("engine from proto"); @@ -3114,6 +3413,7 @@ network_policies: run_as_group: "sandbox".to_string(), }), network_policies, + network_middlewares: std::collections::HashMap::default(), }; let engine = OpaEngine::from_proto(&proto).expect("engine from proto"); @@ -3990,6 +4290,7 @@ network_policies: run_as_group: "sandbox".to_string(), }), network_policies, + network_middlewares: std::collections::HashMap::default(), }; let engine = OpaEngine::from_proto(&proto).expect("engine from proto"); @@ -4047,6 +4348,7 @@ network_policies: run_as_group: "sandbox".to_string(), }), network_policies, + network_middlewares: std::collections::HashMap::default(), }; let engine = OpaEngine::from_proto(&proto).expect("engine from proto"); @@ -4105,6 +4407,7 @@ network_policies: run_as_group: "sandbox".to_string(), }), network_policies, + network_middlewares: std::collections::HashMap::default(), }; let engine = OpaEngine::from_proto(&proto).expect("engine from proto"); @@ -4165,6 +4468,7 @@ network_policies: run_as_group: "sandbox".to_string(), }), network_policies, + network_middlewares: std::collections::HashMap::default(), }; let engine = OpaEngine::from_proto(&proto).expect("engine from proto"); @@ -4224,6 +4528,7 @@ network_policies: run_as_group: "sandbox".to_string(), }), network_policies, + network_middlewares: std::collections::HashMap::default(), }; let engine = OpaEngine::from_proto(&proto).expect("engine from proto"); @@ -5213,6 +5518,7 @@ process: run_as_group: "sandbox".to_string(), }), network_policies, + network_middlewares: std::collections::HashMap::default(), }; let engine = OpaEngine::from_proto(&proto).expect("engine from proto"); let input = NetworkInput { @@ -5267,6 +5573,7 @@ process: run_as_group: "sandbox".to_string(), }), network_policies, + network_middlewares: std::collections::HashMap::default(), }; let engine = OpaEngine::from_proto(&proto).expect("engine from proto"); let input = NetworkInput { @@ -5337,6 +5644,7 @@ process: run_as_group: "sandbox".to_string(), }), network_policies, + network_middlewares: std::collections::HashMap::default(), }; let engine = OpaEngine::from_proto(&proto).expect("Failed to create engine from proto"); @@ -5567,6 +5875,7 @@ network_policies: run_as_group: "sandbox".to_string(), }), network_policies, + network_middlewares: std::collections::HashMap::default(), }; let engine = OpaEngine::from_proto(&proto).unwrap(); // Port 443 @@ -6391,6 +6700,183 @@ network_policies: ); } + #[tokio::test] + async fn policy_and_middleware_reload_commit_as_one_generation() { + let proto = test_proto(); + let engine = OpaEngine::from_proto(&proto).expect("initial load should succeed"); + let mut new_proto = proto; + new_proto.network_policies.insert( + "python_api".to_string(), + NetworkPolicyRule { + name: "python_api".to_string(), + endpoints: vec![NetworkEndpoint { + host: "pypi.org".to_string(), + port: 443, + ..Default::default() + }], + binaries: vec![NetworkBinary { + path: "/usr/bin/python3".to_string(), + ..Default::default() + }], + }, + ); + let registry = MiddlewareRegistry::connect_services( + openshell_supervisor_middleware_builtins::services(), + Vec::new(), + ) + .await + .expect("built-in registry"); + + engine + .reload_policy_and_middleware_from_proto_with_pid(&new_proto, 0, registry) + .expect("combined reload"); + + assert_eq!(engine.current_generation(), 1); + let python_input = NetworkInput { + host: "pypi.org".into(), + port: 443, + binary_path: PathBuf::from("/usr/bin/python3"), + binary_sha256: "unused".into(), + ancestors: vec![], + cmdline_paths: vec![], + }; + assert!(engine.evaluate_network(&python_input).unwrap().allowed); + + let entry = ChainEntry { + name: "regex".into(), + implementation: openshell_supervisor_middleware_builtins::BUILTIN_REGEX.into(), + order: 0, + config: prost_types::Struct::default(), + on_error: openshell_supervisor_middleware::OnError::FailClosed, + }; + let described = engine + .middleware_runner() + .expect("middleware runner") + .describe_chain(&[entry]) + .await + .expect("describe chain"); + assert!(described[0].is_resolved()); + } + + #[tokio::test] + async fn policy_only_reload_keeps_connected_middleware_registry() { + let proto = test_proto(); + let engine = OpaEngine::from_proto(&proto).expect("initial load should succeed"); + let registry = MiddlewareRegistry::connect_services( + openshell_supervisor_middleware_builtins::services(), + Vec::new(), + ) + .await + .expect("built-in registry"); + engine + .replace_middleware_registry(registry) + .expect("install registry"); + let generation_with_registry = engine.current_generation(); + + let mut new_proto = proto; + new_proto.network_policies.insert( + "python_api".to_string(), + NetworkPolicyRule { + name: "python_api".to_string(), + endpoints: vec![NetworkEndpoint { + host: "pypi.org".to_string(), + port: 443, + ..Default::default() + }], + binaries: vec![NetworkBinary { + path: "/usr/bin/python3".to_string(), + ..Default::default() + }], + }, + ); + engine + .reload_from_proto_with_pid(&new_proto, 0) + .expect("policy-only reload"); + + assert_eq!(engine.current_generation(), generation_with_registry + 1); + let python_input = NetworkInput { + host: "pypi.org".into(), + port: 443, + binary_path: PathBuf::from("/usr/bin/python3"), + binary_sha256: "unused".into(), + ancestors: vec![], + cmdline_paths: vec![], + }; + assert!(engine.evaluate_network(&python_input).unwrap().allowed); + + let entry = ChainEntry { + name: "regex".into(), + implementation: openshell_supervisor_middleware_builtins::BUILTIN_REGEX.into(), + order: 0, + config: prost_types::Struct::default(), + on_error: openshell_supervisor_middleware::OnError::FailClosed, + }; + let described = engine + .middleware_runner() + .expect("middleware runner") + .describe_chain(&[entry]) + .await + .expect("describe chain"); + assert!(described[0].is_resolved()); + } + + #[tokio::test] + async fn failed_combined_reload_preserves_policy_registry_and_generation() { + let proto = test_proto(); + let engine = OpaEngine::from_proto(&proto).expect("initial load should succeed"); + let builtins = MiddlewareRegistry::connect_services( + openshell_supervisor_middleware_builtins::services(), + Vec::new(), + ) + .await + .expect("built-in registry"); + engine + .reload_policy_and_middleware_from_proto_with_pid(&proto, 0, builtins) + .expect("install last-known-good runtime"); + + let mut invalid = proto; + invalid.network_middlewares.insert( + String::new(), + NetworkMiddlewareConfig { + middleware: openshell_supervisor_middleware_builtins::BUILTIN_REGEX.into(), + ..Default::default() + }, + ); + let empty_registry = MiddlewareRegistry::connect_services(Vec::new(), Vec::new()) + .await + .expect("empty registry"); + + engine + .reload_policy_and_middleware_from_proto_with_pid(&invalid, 0, empty_registry) + .expect_err("invalid policy must reject the combined reload"); + + assert_eq!(engine.current_generation(), 1); + let claude_input = NetworkInput { + host: "api.anthropic.com".into(), + port: 443, + binary_path: PathBuf::from("/usr/local/bin/claude"), + binary_sha256: "unused".into(), + ancestors: vec![], + cmdline_paths: vec![], + }; + assert!(engine.evaluate_network(&claude_input).unwrap().allowed); + + let entry = ChainEntry { + name: "regex".into(), + implementation: openshell_supervisor_middleware_builtins::BUILTIN_REGEX.into(), + order: 0, + config: prost_types::Struct::default(), + on_error: openshell_supervisor_middleware::OnError::FailClosed, + }; + let described = engine + .middleware_runner() + .expect("middleware runner") + .describe_chain(&[entry]) + .await + .expect("describe chain"); + assert!(described[0].is_resolved()); + } + #[test] fn deny_reason_includes_symlink_hint() { // Verify the deny reason includes an actionable symlink hint @@ -6608,6 +7094,7 @@ network_policies: run_as_group: "sandbox".to_string(), }), network_policies, + network_middlewares: std::collections::HashMap::default(), }; // Build engine with our PID (symlink resolution will work via /proc/self/root/) @@ -6685,6 +7172,7 @@ network_policies: run_as_group: "sandbox".to_string(), }), network_policies, + network_middlewares: std::collections::HashMap::default(), }; // Initial load at pid=0 — no symlink expansion @@ -6727,6 +7215,387 @@ network_policies: assert!(eval_l7(&engine, &input)); } + #[test] + fn middleware_chain_uses_configured_order() { + let data = r#" +network_middlewares: + global-redactor: + middleware: openshell/regex + order: 20 + endpoints: + include: ["api.example.com"] + policy-redactor: + middleware: openshell/regex + order: 10 + endpoints: + include: ["api.example.com"] + endpoint-redactor: + middleware: openshell/regex + order: 5 + endpoints: + include: ["api.example.com"] +network_policies: + api: + name: api + endpoints: + - host: api.example.com + port: 443 + protocol: rest + enforcement: enforce + rules: + - allow: { method: POST, path: "/v1/**" } + binaries: + - { path: /usr/bin/curl } +"#; + let engine = OpaEngine::from_strings(TEST_POLICY, data).unwrap(); + let input = NetworkInput { + host: "api.example.com".into(), + port: 443, + binary_path: PathBuf::from("/usr/bin/curl"), + binary_sha256: "unused".into(), + ancestors: vec![], + cmdline_paths: vec![], + }; + let (chain, _) = engine + .query_middleware_chain_with_generation(&input) + .unwrap(); + let names: Vec<_> = chain.iter().map(|entry| entry.name.as_str()).collect(); + assert_eq!( + names, + vec!["endpoint-redactor", "policy-redactor", "global-redactor"] + ); + } + + fn matching_middleware_configs(count: usize) -> Vec { + (0..count) + .map(|index| { + regorus::Value::from(serde_json::json!({ + "name": format!("stage-{index}"), + "middleware": "openshell/regex", + "endpoints": {"include": ["api.example.com"]} + })) + }) + .collect() + } + + #[test] + fn middleware_chain_accepts_maximum_selected_stages() { + let configs = matching_middleware_configs( + openshell_supervisor_middleware::MAX_MIDDLEWARE_CHAIN_STAGES, + ); + + let chain = + global_middleware_entries(&configs, "api.example.com").expect("maximum selected chain"); + assert_eq!( + chain.len(), + openshell_supervisor_middleware::MAX_MIDDLEWARE_CHAIN_STAGES + ); + } + + #[test] + fn middleware_chain_rejects_selected_stages_over_capacity() { + let configs = matching_middleware_configs( + openshell_supervisor_middleware::MAX_MIDDLEWARE_CHAIN_STAGES + 1, + ); + + let error = global_middleware_entries(&configs, "api.example.com") + .expect_err("selected chain over capacity"); + assert!( + error + .to_string() + .contains("selected middleware stage count exceeds platform maximum 10") + ); + } + + #[test] + fn middleware_chain_uses_dns_label_glob_semantics() { + let data = r#" +network_middlewares: + single-label: + middleware: openshell/regex + order: 10 + endpoints: + include: ["*.Example.COM"] + exclude: ["trusted.example.com"] + recursive: + middleware: openshell/regex + order: 20 + endpoints: + include: ["**.example.com"] + intra-label: + middleware: openshell/regex + order: 30 + endpoints: + include: ["*-api.example.com"] +"#; + let engine = OpaEngine::from_strings(TEST_POLICY, data).unwrap(); + let names_for = |host: &str| { + let input = NetworkInput { + host: host.into(), + port: 443, + binary_path: PathBuf::from("/usr/bin/curl"), + binary_sha256: "unused".into(), + ancestors: vec![], + cmdline_paths: vec![], + }; + engine + .query_middleware_chain_with_generation(&input) + .unwrap() + .0 + .into_iter() + .map(|entry| entry.name) + .collect::>() + }; + + assert_eq!( + names_for("api.example.com"), + vec!["single-label", "recursive"] + ); + assert_eq!(names_for("deep.api.example.com"), vec!["recursive"]); + assert_eq!(names_for("trusted.example.com"), vec!["recursive"]); + assert_eq!( + names_for("tenant-api.example.com"), + vec!["single-label", "recursive", "intra-label"] + ); + } + + #[test] + fn host_pattern_matches_rego_endpoint_host_semantics() { + // Middleware selectors and the tls-skip overlap validation promise the + // same host semantics as endpoint admission, which is decided by the + // endpoint_allowed branches in sandbox-policy.rego. Pin parity by + // running one table through openshell_core::host_pattern and through + // regorus with those branches verbatim. + let policy = r#" +package test + +default host_match = false + +host_match if { + not contains(input.pattern, "*") + lower(input.pattern) == lower(input.host) +} + +host_match if { + contains(input.pattern, "*") + glob.match(lower(input.pattern), ["."], lower(input.host)) +} +"#; + let mut engine = regorus::Engine::new(); + engine + .add_policy("test.rego".into(), policy.into()) + .unwrap(); + + let cases = [ + ("api.example.com", "api.example.com"), + ("api.example.com", "API.EXAMPLE.COM"), + ("api.example.com", "api.example.org"), + ("*.example.com", "api.example.com"), + ("*.example.com", "example.com"), + ("*.example.com", "deep.api.example.com"), + ("*-api.example.com", "tenant-api.example.com"), + ("*-api.example.com", "api.example.com"), + ("*.a?i.example.com", "x.abi.example.com"), + ("**.example.com", "example.com"), + ("**.example.com", "api.example.com"), + ("**.example.com", "deep.api.example.com"), + ("api.**.com", "api.com"), + ("api.**.com", "api.x.com"), + ("api.**.com", "api.x.y.com"), + ("api.**", "api"), + ("api.**", "api.com"), + ("*", "com"), + ("*", "example.com"), + ("**", "com"), + ("**", "deep.api.example.com"), + ]; + for (pattern, host) in cases { + let rust = openshell_core::host_pattern::host_matches(pattern, host).unwrap(); + engine + .set_input_json( + &serde_json::json!({ "pattern": pattern, "host": host }).to_string(), + ) + .unwrap(); + let rego = engine.eval_rule("data.test.host_match".into()).unwrap() + == regorus::Value::from(true); + assert_eq!( + rust, rego, + "host pattern parity mismatch: pattern={pattern} host={host} rust={rust} rego={rego}" + ); + } + } + + #[test] + fn middleware_policy_validation_rejects_bad_configs() { + let cases = [ + ( + "invalid on_error", + r#" +network_middlewares: + redactor: + middleware: openshell/regex + on_error: maybe + endpoints: + include: ["api.example.com"] +"#, + "invalid on_error", + ), + ( + "duplicate order", + r#" +network_middlewares: + alpha: + middleware: openshell/regex + order: 10 + endpoints: + include: ["api.example.com"] + beta: + middleware: openshell/regex + order: 10 + endpoints: + include: ["other.example.com"] +"#, + "duplicate order 10", + ), + ( + "missing selector", + r#" +network_middlewares: + redactor: + middleware: openshell/regex +"#, + "endpoint selector is required", + ), + ( + "malformed selector", + r#" +network_middlewares: + redactor: + middleware: openshell/regex + endpoints: + include: ["api[.example.com"] +"#, + "invalid host pattern", + ), + ( + "tls skip selector", + r#" +network_middlewares: + redactor: + middleware: openshell/regex + endpoints: + include: ["api.example.com"] +network_policies: + api: + endpoints: + - host: api.example.com + port: 443 + tls: skip + binaries: + - { path: /usr/bin/curl } +"#, + "tls: skip", + ), + ( + "tls skip wildcard overlap", + r#" +network_middlewares: + redactor: + middleware: openshell/regex + endpoints: + include: ["api.example.com"] +network_policies: + api: + endpoints: + - host: "*.example.com" + port: 443 + tls: skip + binaries: + - { path: /usr/bin/curl } +"#, + "tls: skip", + ), + ]; + + for (name, data, expected) in cases { + let err = match OpaEngine::from_strings(TEST_POLICY, data) { + Ok(_) => panic!("{name}: expected policy validation failure"), + Err(err) => err.to_string(), + }; + assert!( + err.contains(expected), + "{name}: expected {expected:?} in {err:?}" + ); + } + } + + #[test] + fn middleware_catalog_validation_rejects_unknown_or_invalid_builtins() { + let validate = |implementation: &str, config: &prost_types::Struct| { + openshell_supervisor_middleware_builtins::validate_config(implementation, config) + .map_err(|error| error.to_string()) + }; + for (name, data, expected) in [ + ( + "unknown built-in", + r#" +network_middlewares: + unknown: + middleware: openshell/unknown + endpoints: + include: ["api.example.com"] +"#, + "not a registered OpenShell built-in", + ), + ( + "invalid regex config", + r#" +network_middlewares: + redactor: + middleware: openshell/regex + config: + mode: allow + endpoints: + include: ["api.example.com"] +"#, + "supports only mode: redact", + ), + ] { + let error = + OpaEngine::from_strings_with_middleware_config(TEST_POLICY, data, Some(&validate)) + .err() + .unwrap_or_else(|| panic!("{name}: expected catalog validation failure")) + .to_string(); + assert!( + error.contains(expected), + "{name}: expected {expected:?} in {error:?}" + ); + } + } + + #[test] + fn from_proto_revalidates_middleware_policy() { + let mut policy = openshell_policy::restrictive_default_policy(); + policy.network_middlewares.insert( + "redactor".into(), + NetworkMiddlewareConfig { + middleware: "openshell/regex".into(), + endpoints: Some(openshell_core::proto::MiddlewareEndpointSelector { + include: vec!["api[.example.com".into()], + exclude: Vec::new(), + }), + ..Default::default() + }, + ); + + let error = OpaEngine::from_proto(&policy) + .err() + .expect("supervisor must reject invalid effective middleware policy") + .to_string(); + assert!(error.contains("policy validation failed"), "{error}"); + assert!(error.contains("invalid host pattern"), "{error}"); + } + #[test] fn l7_head_denied_when_only_post_allowed() { let engine = OpaEngine::from_strings( diff --git a/crates/openshell-supervisor-network/src/proxy.rs b/crates/openshell-supervisor-network/src/proxy.rs index db6315dd86..ab2313b890 100644 --- a/crates/openshell-supervisor-network/src/proxy.rs +++ b/crates/openshell-supervisor-network/src/proxy.rs @@ -386,25 +386,64 @@ fn could_be_supported_tunnel_protocol_prefix(peek: &[u8]) -> bool { || crate::l7::rest::could_be_http2_prior_knowledge_prefix(peek) } -fn unsupported_l7_tunnel_protocol_detail( - tunnel_protocol: TunnelProtocol, +/// Why tunnel payload inspection is mandatory for a connection, in message +/// precedence order: an L7-configured endpoint owns the wording even when a +/// fail-closed middleware chain also matches. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum InspectionRequirement { + None, + L7Route, + RequiredMiddleware, +} + +fn inspection_requirement( should_inspect_l7: bool, -) -> Option<&'static str> { - if !should_inspect_l7 { - return None; + middleware_gate: crate::l7::middleware::UninspectableTrafficGate, +) -> InspectionRequirement { + if should_inspect_l7 { + InspectionRequirement::L7Route + } else if middleware_gate == crate::l7::middleware::UninspectableTrafficGate::Deny { + InspectionRequirement::RequiredMiddleware + } else { + InspectionRequirement::None } +} - match tunnel_protocol { - TunnelProtocol::H2cPriorKnowledge => { +fn unsupported_l7_tunnel_protocol_detail( + tunnel_protocol: TunnelProtocol, + requirement: InspectionRequirement, +) -> Option<&'static str> { + match (tunnel_protocol, requirement) { + (_, InspectionRequirement::None) | (TunnelProtocol::Tls | TunnelProtocol::Http1, _) => None, + (TunnelProtocol::H2cPriorKnowledge, InspectionRequirement::L7Route) => { Some("HTTP/2 prior-knowledge (h2c) is not supported for L7-inspected endpoints") } - TunnelProtocol::Unsupported => { + (TunnelProtocol::H2cPriorKnowledge, InspectionRequirement::RequiredMiddleware) => { + Some("HTTP/2 prior-knowledge (h2c) cannot be inspected by required middleware") + } + (TunnelProtocol::Unsupported, InspectionRequirement::L7Route) => { Some("Unsupported tunnel protocol for L7-inspected endpoint") } - TunnelProtocol::Tls | TunnelProtocol::Http1 => None, + (TunnelProtocol::Unsupported, InspectionRequirement::RequiredMiddleware) => { + Some("Unsupported tunnel protocol cannot be inspected by required middleware") + } } } +/// Gate for traffic that would bypass L7 inspection entirely: query the +/// middleware chain matching this destination and process identity, and +/// decide whether raw relay is allowed. Uninspectable traffic is denied when +/// any matching entry is `fail_closed`; an all-`fail_open` chain passes it +/// through with a bypass detection finding. +fn middleware_uninspectable_gate( + opa_engine: &OpaEngine, + ctx: &crate::l7::relay::L7EvalContext, +) -> Result { + let input = crate::l7::middleware::middleware_network_input(ctx); + let (chain, _generation) = opa_engine.query_middleware_chain_with_generation(&input)?; + Ok(crate::l7::middleware::uninspectable_traffic_gate(&chain)) +} + async fn peek_tunnel_protocol(client: &TcpStream) -> Result> { let mut peek_buf = [0u8; TUNNEL_PROTOCOL_PEEK_BYTES]; let deadline = tokio::time::Instant::now() + TUNNEL_PROTOCOL_PEEK_TIMEOUT; @@ -456,25 +495,65 @@ fn emit_forward_success_activity(tx: Option<&ActivitySender>, l7_activity_pendin ); } -fn forward_l7_hard_deny_reason( - protocol: crate::l7::L7Protocol, - request_info: &crate::l7::L7RequestInfo, -) -> Option { - request_info - .graphql - .as_ref() - .and_then(|info| info.error.as_deref()) - .map(|error| format!("GraphQL request rejected: {error}")) - .or_else(|| { - request_info.jsonrpc.as_ref().and_then(|info| { - info.error - .as_ref() - .map(crate::l7::jsonrpc::JsonRpcInspectionError::rejection_reason) - .or_else(|| { - crate::l7::relay::jsonrpc_response_frame_hard_deny_reason(protocol, info) - }) - }) - }) +/// Body-aware policy state carried from forward L7 admission to middleware +/// execution. The selected route and its captured policy engine stay paired so +/// middleware cannot be invoked with only half of the re-evaluation context. +struct ForwardL7Reevaluation<'a> { + config: &'a crate::l7::L7EndpointConfig, + engine: &'a crate::opa::TunnelPolicyEngine, + request_info: &'a crate::l7::L7RequestInfo, +} + +/// Executes the middleware portion of the forward HTTP pipeline with an +/// explicit transformed-body policy. +struct ForwardMiddlewarePipeline<'a> { + ctx: &'a crate::l7::relay::L7EvalContext, + scheme: &'a str, + runner: &'a openshell_supervisor_middleware::ChainRunner, + generation_guard: &'a PolicyGenerationGuard, + l7_reevaluation: Option>, +} + +impl ForwardMiddlewarePipeline<'_> { + #[allow( + clippy::option_if_let_else, + reason = "the Some branch must keep a borrowed evaluator alive across the async call" + )] + async fn apply( + &self, + request: crate::l7::provider::L7Request, + client: &mut C, + chain: Vec, + ) -> Result + where + C: TokioAsyncRead + TokioAsyncWrite + Unpin + Send, + { + let validate; + let transformed_body_policy = match &self.l7_reevaluation { + Some(l7) => { + validate = crate::l7::relay::transformed_body_validator( + l7.config, + l7.engine, + self.ctx, + l7.request_info, + ); + openshell_supervisor_middleware::TransformedBodyPolicy::Reevaluate(&validate) + } + None => openshell_supervisor_middleware::TransformedBodyPolicy::NotPolicyRelevant, + }; + + crate::l7::middleware::apply_middleware_chain_for_scheme( + request, + client, + self.ctx, + self.scheme, + chain, + self.runner, + self.generation_guard, + transformed_body_policy, + ) + .await + } } /// Emit a denial event to the aggregator channel (if configured). @@ -583,7 +662,21 @@ async fn handle_tcp_connection( } } - let request = String::from_utf8_lossy(&buf[..used]); + let header_end = buf[..used] + .windows(4) + .position(|window| window == b"\r\n\r\n") + .expect("header terminator was observed") + + 4; + if crate::l7::rest::validate_http_request_header_block(&buf[..header_end]).is_err() { + respond(&mut client, b"HTTP/1.1 400 Bad Request\r\n\r\n").await?; + return Ok(()); + } + let request = + std::str::from_utf8(&buf[..header_end]).expect("validated HTTP request headers are UTF-8"); + if crate::l7::rest::parse_body_length(request).is_err() { + respond(&mut client, b"HTTP/1.1 400 Bad Request\r\n\r\n").await?; + return Ok(()); + } let mut lines = request.split("\r\n"); let request_line = lines.next().unwrap_or(""); let mut parts = request_line.split_whitespace(); @@ -1151,6 +1244,32 @@ async fn handle_tcp_connection( }; if effective_tls_skip { + // Policy validation rejects fail-closed middleware overlapping + // `tls: skip` endpoints; this runtime gate is defense in depth. + match middleware_uninspectable_gate(&opa_engine, &ctx)? { + crate::l7::middleware::UninspectableTrafficGate::Deny => { + crate::l7::middleware::emit_middleware_uninspectable(&ctx, "tls-skip tunnel", true); + respond( + &mut client, + &build_json_error_response( + 403, + "Forbidden", + "middleware_required", + "tls: skip tunnel cannot be inspected by required middleware", + ), + ) + .await?; + return Ok(()); + } + crate::l7::middleware::UninspectableTrafficGate::BypassWithFinding => { + crate::l7::middleware::emit_middleware_uninspectable( + &ctx, + "tls-skip tunnel", + false, + ); + } + crate::l7::middleware::UninspectableTrafficGate::Unrestricted => {} + } // tls: skip — raw tunnel, no termination, no credential injection. debug!( host = %host_lc, @@ -1230,6 +1349,7 @@ async fn handle_tcp_connection( &mut tls_upstream, &ctx, &generation_guard, + Some(&opa_engine), ) .await } @@ -1265,7 +1385,7 @@ async fn handle_tcp_connection( // stream upstream and leak any `openshell:resolve:env:*` // placeholder verbatim). const DETAIL: &str = "TLS termination unavailable after tunnel establishment; \ - closing connection — credential rewrite would be bypassed"; + closing connection - credential rewrite would be bypassed"; let event = NetworkActivityBuilder::new(openshell_ocsf::ctx::ctx()) .activity(ActivityId::Open) .action(ActionId::Denied) @@ -1362,6 +1482,7 @@ async fn handle_tcp_connection( &mut upstream, &ctx, &generation_guard, + Some(&opa_engine), ) .await { @@ -1380,9 +1501,14 @@ async fn handle_tcp_connection( } } } else { + let middleware_gate = middleware_uninspectable_gate(&opa_engine, &ctx)?; + let requirement = inspection_requirement(should_inspect_l7, middleware_gate); if let Some(protocol_detail) = - unsupported_l7_tunnel_protocol_detail(tunnel_protocol, should_inspect_l7) + unsupported_l7_tunnel_protocol_detail(tunnel_protocol, requirement) { + if requirement == InspectionRequirement::RequiredMiddleware { + crate::l7::middleware::emit_middleware_uninspectable(&ctx, protocol_detail, true); + } let event = NetworkActivityBuilder::new(openshell_ocsf::ctx::ctx()) .activity(ActivityId::Open) .action(ActionId::Denied) @@ -1425,6 +1551,9 @@ async fn handle_tcp_connection( return Ok(()); } + if middleware_gate == crate::l7::middleware::UninspectableTrafficGate::BypassWithFinding { + crate::l7::middleware::emit_middleware_uninspectable(&ctx, "non-http tcp", false); + } // Neither TLS nor HTTP — raw binary relay. debug!( host = %host_lc, @@ -3100,6 +3229,68 @@ fn parse_proxy_uri(uri: &str) -> Result<(String, String, u16, String)> { Ok((scheme, host, port, path.to_string())) } +/// Build the HTTP/1.1 `Host` value for a plain-HTTP absolute-form target. +/// +/// Forward proxy requests are restricted to `http`, so port 80 is omitted as +/// the default port. IPv6 literals regain the brackets removed by +/// `parse_proxy_uri` before they are written as an authority. +fn canonical_forward_authority(host: &str, port: u16) -> String { + let host = host.to_ascii_lowercase(); + let host = if host.contains(':') { + format!("[{host}]") + } else { + host + }; + if port == 80 { + host + } else { + format!("{host}:{port}") + } +} + +/// Replace every received `Host` field with the authority selected from the +/// absolute-form request-target, preserving any body bytes already read. +/// +/// RFC 9112 section 3.2.2 requires a proxy to ignore the received `Host` field +/// and generate a new value from the absolute request-target. Doing this before +/// L7 and middleware processing also keeps every buffered representation tied +/// to the same authority used for policy selection. +fn canonicalize_forward_host_header(raw: &[u8], authority: &str) -> Result> { + let header_end = raw + .windows(4) + .position(|window| window == b"\r\n\r\n") + .ok_or_else(|| miette::miette!("HTTP request headers are missing the CRLF terminator"))? + + 4; + crate::l7::rest::validate_http_request_header_block(&raw[..header_end])?; + let header_block = std::str::from_utf8(&raw[..header_end]) + .map_err(|_| miette::miette!("HTTP headers contain invalid UTF-8"))? + .strip_suffix("\r\n\r\n") + .expect("validated header block has terminator"); + let mut lines = header_block.split("\r\n"); + let request_line = lines + .next() + .expect("validated header block contains a request line"); + + let mut output = Vec::with_capacity(raw.len() + authority.len() + 8); + output.extend_from_slice(request_line.as_bytes()); + output.extend_from_slice(b"\r\nHost: "); + output.extend_from_slice(authority.as_bytes()); + output.extend_from_slice(b"\r\n"); + for line in lines { + let (field_name, _) = line + .split_once(':') + .expect("validated header field contains colon"); + if field_name.eq_ignore_ascii_case("host") { + continue; + } + output.extend_from_slice(line.as_bytes()); + output.extend_from_slice(b"\r\n"); + } + output.extend_from_slice(b"\r\n"); + output.extend_from_slice(&raw[header_end..]); + Ok(output) +} + /// Rewrite an absolute-form HTTP proxy request to origin-form for upstream. /// /// Transforms `GET http://host:port/path HTTP/1.1` into `GET /path HTTP/1.1`, @@ -3110,6 +3301,7 @@ fn rewrite_forward_request( raw: &[u8], used: usize, path: &str, + canonical_authority: &str, secret_resolver: Option<&SecretResolver>, request_body_credential_rewrite: bool, ) -> Result, secrets::UnresolvedPlaceholderError> { @@ -3125,10 +3317,18 @@ fn rewrite_forward_request( let header_str = String::from_utf8_lossy(&raw[..header_end]); let lines = header_str.split("\r\n").collect::>(); + let connection_nominated: std::collections::HashSet = lines + .iter() + .skip(1) + .filter_map(|line| line.split_once(':')) + .filter(|(name, _)| name.eq_ignore_ascii_case("connection")) + .flat_map(|(_, value)| value.split(',')) + .map(|token| token.trim().to_ascii_lowercase()) + .filter(|token| !token.is_empty()) + .collect(); // Rebuild headers, stripping hop-by-hop and adding proxy headers let mut output = Vec::with_capacity(header_end + 128); - let mut has_connection = false; let mut has_via = false; for (i, line) in lines.iter().enumerate() { @@ -3152,25 +3352,31 @@ fn rewrite_forward_request( break; } - let lower = line.to_ascii_lowercase(); + let (field_name, _) = line + .split_once(':') + .expect("forward request passed strict ingress header validation"); + let field_name = field_name.to_ascii_lowercase(); + + // RFC 9112 section 3.2.2 requires proxies to replace every received + // Host field with one generated from the absolute request-target. + if field_name == "host" { + continue; + } // Strip proxy hop-by-hop headers - if lower.starts_with("proxy-connection:") - || lower.starts_with("proxy-authorization:") - || lower.starts_with("proxy-authenticate:") - { + if matches!( + field_name.as_str(), + "proxy-connection" | "proxy-authorization" | "proxy-authenticate" + ) { continue; } - // Replace Connection header - if lower.starts_with("connection:") { - has_connection = true; - if websocket_upgrade { - output.extend_from_slice(line.as_bytes()); - output.extend_from_slice(b"\r\n"); - continue; - } - output.extend_from_slice(b"Connection: close\r\n"); + if connection_nominated.contains(&field_name) { + continue; + } + + // Reconstruct hop-by-hop upgrade fields after processing the originals. + if field_name == "connection" || field_name == "upgrade" { continue; } @@ -3182,13 +3388,21 @@ fn rewrite_forward_request( output.extend_from_slice(rewritten_line.as_bytes()); output.extend_from_slice(b"\r\n"); - if lower.starts_with("via:") { + if field_name == "via" { has_via = true; } } + // Generate the only Host field from the absolute request-target authority. + output.extend_from_slice(b"Host: "); + output.extend_from_slice(canonical_authority.as_bytes()); + output.extend_from_slice(b"\r\n"); + // Inject missing headers - if !has_connection && !websocket_upgrade { + if websocket_upgrade { + output.extend_from_slice(b"Connection: Upgrade\r\n"); + output.extend_from_slice(b"Upgrade: websocket\r\n"); + } else { output.extend_from_slice(b"Connection: close\r\n"); } if !has_via { @@ -3385,31 +3599,45 @@ async fn handle_forward_proxy( return Ok(()); } - // 2. Reject HTTPS — must use CONNECT for TLS - if scheme == "https" { - { - let event = HttpActivityBuilder::new(openshell_ocsf::ctx::ctx()) - .activity(ActivityId::Refuse) - .action(ActionId::Denied) - .disposition(DispositionId::Rejected) - .severity(SeverityId::Informational) - .status(StatusId::Failure) - .dst_endpoint(Endpoint::from_domain(&host_lc, port)) - .message(format!( - "FORWARD rejected: HTTPS requires CONNECT for {host_lc}:{port}" - )) - .build(); - ocsf_emit!(event); + if scheme != "http" { + let event = HttpActivityBuilder::new(openshell_ocsf::ctx::ctx()) + .activity(ActivityId::Refuse) + .action(ActionId::Denied) + .disposition(DispositionId::Rejected) + .severity(SeverityId::Informational) + .status(StatusId::Failure) + .dst_endpoint(Endpoint::from_domain(&host_lc, port)) + .message(format!( + "FORWARD rejected: unsupported scheme {scheme} for {host_lc}:{port}" + )) + .build(); + ocsf_emit!(event); + if scheme == "https" { + respond( + client, + b"HTTP/1.1 400 Bad Request\r\nContent-Length: 27\r\n\r\nUse CONNECT for HTTPS URLs", + ) + .await?; + } else { + respond( + client, + &build_json_error_response( + 400, + "Bad Request", + "unsupported_proxy_scheme", + "Forward proxy requests must use http", + ), + ) + .await?; } - respond( - client, - b"HTTP/1.1 400 Bad Request\r\nContent-Length: 27\r\n\r\nUse CONNECT for HTTPS URLs", - ) - .await?; return Ok(()); } - // 3. Evaluate OPA policy (same identity binding as CONNECT) + let canonical_authority = canonical_forward_authority(&host_lc, port); + let mut forward_request_bytes = + canonicalize_forward_host_header(&buf[..used], &canonical_authority)?; + + // 2. Evaluate OPA policy (same identity binding as CONNECT) let peer_addr = client.peer_addr().into_diagnostic()?; let _local_addr = client.local_addr().into_diagnostic()?; @@ -3547,10 +3775,14 @@ async fn handle_forward_proxy( return Ok(()); } }; - let mut forward_request_bytes = buf[..used].to_vec(); let mut upstream_target = path.clone(); let mut websocket_extensions = crate::l7::rest::WebSocketExtensionMode::Preserve; let mut forward_tunnel_engine: Option = None; + // L7 endpoint config and evaluated request info, carried past the L7 + // block so a middleware-transformed body can be re-evaluated against the + // same policy inputs before it is forwarded. + let mut forward_l7_reeval: Option<(crate::l7::L7EndpointConfig, crate::l7::L7RequestInfo)> = + None; let mut forward_upgrade_config: Option = None; let mut forward_upgrade_target = String::new(); let mut forward_upgrade_query_params = std::collections::HashMap::new(); @@ -3892,10 +4124,10 @@ async fn handle_forward_proxy( jsonrpc, }; - let parse_error_reason = - forward_l7_hard_deny_reason(l7_config.config.protocol, &request_info); - let force_deny = parse_error_reason.is_some(); - let (allowed, reason) = parse_error_reason.map_or_else( + let hard_deny_reason = + crate::l7::relay::l7_request_hard_deny_reason(l7_config.config.protocol, &request_info); + let force_deny = hard_deny_reason.is_some(); + let (allowed, reason) = hard_deny_reason.map_or_else( || { crate::l7::relay::evaluate_l7_request(&tunnel_engine, &l7_ctx, &request_info) .unwrap_or_else(|e| { @@ -4013,6 +4245,7 @@ async fn handle_forward_proxy( } l7_activity_pending = true; forward_tunnel_engine = Some(tunnel_engine); + forward_l7_reeval = Some((l7_config.config.clone(), request_info)); } // 5. DNS resolution + SSRF defence (mirrors the CONNECT path logic). @@ -4373,30 +4606,75 @@ async fn handle_forward_proxy( } }; - // Log success - { - let event = HttpActivityBuilder::new(openshell_ocsf::ctx::ctx()) - .activity(ActivityId::Other) - .action(ActionId::Allowed) - .disposition(DispositionId::Allowed) - .severity(SeverityId::Informational) - .status(StatusId::Success) - .http_request(HttpRequest::new( - method, - OcsfUrl::new("http", &host_lc, &path, port), - )) - .dst_endpoint(Endpoint::from_domain(&host_lc, port)) - .src_endpoint(Endpoint::from_ip(peer_addr.ip(), peer_addr.port())) - .actor_process( - Process::from_bypass(&binary_str, &pid_str, &ancestors_str) - .with_cmd_line(&cmdline_str), - ) - .firewall_rule(policy_str, "opa") - .message(format!("FORWARD allowed {method} {host_lc}:{port}{path}")) - .build(); - ocsf_emit!(event); + let middleware_path = path.split_once('?').map_or(path.as_str(), |(path, _)| path); + let middleware_input = crate::opa::NetworkInput { + host: host_lc.clone(), + port, + binary_path: decision.binary.clone().unwrap_or_default(), + binary_sha256: String::new(), + ancestors: decision.ancestors.clone(), + cmdline_paths: decision.cmdline_paths.clone(), + }; + let (chain, generation) = + opa_engine.query_middleware_chain_with_generation(&middleware_input)?; + if generation != forward_generation_guard.captured_generation() { + emit_l7_tunnel_close_after_policy_change( + &host_lc, + port, + miette::miette!( + "policy changed before forward middleware evaluation [expected_generation:{} current_generation:{}]", + forward_generation_guard.captured_generation(), + generation, + ), + ); + respond( + client, + &build_json_error_response( + 403, + "Forbidden", + "policy_denied", + &format!("{method} {host_lc}:{port}{path} not permitted by policy"), + ), + ) + .await?; + return Ok(()); + } + if !chain.is_empty() { + let middleware_runner = opa_engine.middleware_runner()?; + let request = crate::l7::rest::request_from_buffered_http( + method, + middleware_path, + &upstream_target, + forward_request_bytes, + )?; + let l7_reevaluation = match (forward_l7_reeval.as_ref(), forward_tunnel_engine.as_ref()) { + (Some((config, request_info)), Some(engine)) => Some(ForwardL7Reevaluation { + config, + engine, + request_info, + }), + _ => None, + }; + let pipeline = ForwardMiddlewarePipeline { + ctx: &l7_ctx, + scheme: &scheme, + runner: &middleware_runner, + generation_guard: &forward_generation_guard, + l7_reevaluation, + }; + forward_request_bytes = match pipeline.apply(request, client, chain).await? { + crate::l7::middleware::MiddlewareApplyResult::Allowed(request) => request.raw_header, + crate::l7::middleware::MiddlewareApplyResult::Denied { denial, .. } => { + emit_activity_simple(activity_tx, true, "middleware"); + let response = denial.as_ref().map_or_else( + || build_middleware_failure_response(&l7_ctx.policy_name), + |denial| build_middleware_deny_response(&l7_ctx.policy_name, denial), + ); + respond(client, &response).await?; + return Ok(()); + } + }; } - emit_forward_success_activity(activity_tx, l7_activity_pending); forward_request_bytes = match inject_token_grant_for_forward_request( method, @@ -4433,6 +4711,7 @@ async fn handle_forward_proxy( &forward_request_bytes, forward_request_bytes.len(), &upstream_target, + &canonical_authority, secret_resolver.as_deref(), request_body_credential_rewrite, ) { @@ -4494,6 +4773,34 @@ async fn handle_forward_proxy( }, ) .await?; + + // The request has now survived middleware, token grant, credential + // rewriting, generation checks, and the HTTP relay. Only now record the + // final allowed outcome. + { + let event = HttpActivityBuilder::new(openshell_ocsf::ctx::ctx()) + .activity(ActivityId::Other) + .action(ActionId::Allowed) + .disposition(DispositionId::Allowed) + .severity(SeverityId::Informational) + .status(StatusId::Success) + .http_request(HttpRequest::new( + method, + OcsfUrl::new("http", &host_lc, &path, port), + )) + .dst_endpoint(Endpoint::from_domain(&host_lc, port)) + .src_endpoint(Endpoint::from_ip(peer_addr.ip(), peer_addr.port())) + .actor_process( + Process::from_bypass(&binary_str, &pid_str, &ancestors_str) + .with_cmd_line(&cmdline_str), + ) + .firewall_rule(policy_str, "opa") + .message(format!("FORWARD allowed {method} {host_lc}:{port}{path}")) + .build(); + ocsf_emit!(event); + } + emit_forward_success_activity(activity_tx, l7_activity_pending); + if let crate::l7::provider::RelayOutcome::Upgraded { overflow, websocket_permessage_deflate, @@ -4571,6 +4878,58 @@ fn build_json_error_response(status: u16, status_text: &str, error: &str, detail .into_bytes() } +fn build_middleware_deny_response( + policy_name: &str, + denial: &openshell_supervisor_middleware::MiddlewareDenial, +) -> Vec { + let mut body = serde_json::Map::new(); + body.insert("error".to_string(), serde_json::json!("middleware_denied")); + body.insert( + "detail".to_string(), + serde_json::json!("Request rejected by configured middleware"), + ); + body.insert("policy".to_string(), serde_json::json!(policy_name)); + body.insert( + "middleware".to_string(), + serde_json::json!(denial.config_name), + ); + if let Some(reason_code) = &denial.reason_code { + body.insert("reason_code".to_string(), serde_json::json!(reason_code)); + } + let body_str = serde_json::Value::Object(body).to_string(); + format!( + "HTTP/1.1 403 Forbidden\r\n\ + Content-Type: application/json\r\n\ + Content-Length: {}\r\n\ + Connection: close\r\n\ + \r\n\ + {}", + body_str.len(), + body_str, + ) + .into_bytes() +} + +fn build_middleware_failure_response(policy_name: &str) -> Vec { + let body = serde_json::json!({ + "error": "middleware_failed", + "detail": "Request could not be processed by configured middleware", + "policy": policy_name, + }); + let body_str = body.to_string(); + format!( + "HTTP/1.1 403 Forbidden\r\n\ + Content-Type: application/json\r\n\ + Content-Length: {}\r\n\ + Connection: close\r\n\ + \r\n\ + {}", + body_str.len(), + body_str, + ) + .into_bytes() +} + /// Detail shared by the fail-closed 503 body, the OCSF denial event, and the /// denial notification when a terminating CONNECT route has no TLS termination /// state available. @@ -4647,6 +5006,127 @@ mod tests { use tokio::io::{AsyncRead, AsyncReadExt, AsyncWriteExt}; use tokio::net::{TcpListener, TcpStream}; + async fn drive_raw_request_through_handler(raw: Vec) -> Vec { + let policy = include_str!("../data/sandbox-policy.rego"); + let data = r#" +network_middlewares: + guard: + middleware: openshell/regex + endpoints: + include: ["api.example.com"] +network_policies: {} +"#; + let engine = Arc::new(OpaEngine::from_strings(policy, data).expect("load policy")); + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let client = tokio::spawn(async move { + let mut socket = TcpStream::connect(address).await.unwrap(); + socket.write_all(&raw).await.unwrap(); + let mut response = Vec::new(); + socket.read_to_end(&mut response).await.unwrap(); + response + }); + let (server, _) = listener.accept().await.unwrap(); + + Box::pin(handle_tcp_connection( + server, + engine, + Arc::new(BinaryIdentityCache::new()), + Arc::new(AtomicU32::new(std::process::id())), + None, + None, + None, + Arc::new(None), + None, + None, + None, + None, + )) + .await + .expect("malformed request should be handled"); + client.await.unwrap() + } + + #[tokio::test] + async fn malformed_forward_headers_are_rejected_before_route_or_middleware_dispatch() { + for host in ["api.example.com", "unmatched.example.com"] { + let raw = format!( + "GET http://{host}/ HTTP/1.1\r\nHost: {host}\r\nX-Guard: before\0after\r\n\r\n" + ) + .into_bytes(); + let response = Box::pin(drive_raw_request_through_handler(raw)).await; + assert!( + response.starts_with(b"HTTP/1.1 400 Bad Request"), + "malformed request for {host} must fail at ingress" + ); + } + } + + #[tokio::test] + async fn malformed_request_lines_are_rejected_before_connect_or_forward_dispatch() { + for host in ["api.example.com", "unmatched.example.com"] { + for request_line in [ + format!("GET http://{host}/ HTTP/1.1 extra"), + format!("CONNECT {host}:443 HTTP/1.1 extra"), + ] { + let raw = format!("{request_line}\r\nHost: {host}\r\n\r\n").into_bytes(); + let response = Box::pin(drive_raw_request_through_handler(raw)).await; + assert!( + response.starts_with(b"HTTP/1.1 400 Bad Request"), + "malformed request for {host} must fail before dispatch" + ); + } + } + } + + #[tokio::test] + async fn unsupported_forward_scheme_is_rejected_before_policy_or_middleware_dispatch() { + let raw = b"GET ftp://api.example.com/resource HTTP/1.1\r\nHost: api.example.com\r\n\r\n" + .to_vec(); + let response = Box::pin(drive_raw_request_through_handler(raw)).await; + assert!(response.starts_with(b"HTTP/1.1 400 Bad Request")); + assert!( + response + .windows(b"unsupported_proxy_scheme".len()) + .any(|window| window == b"unsupported_proxy_scheme") + ); + } + + #[tokio::test] + async fn policy_local_preserves_specific_non_http_scheme_error() { + for scheme in ["https", "ftp"] { + let raw = format!( + "GET {scheme}://policy.local/resource HTTP/1.1\r\nHost: policy.local\r\n\r\n" + ) + .into_bytes(); + let response = Box::pin(drive_raw_request_through_handler(raw)).await; + assert!(response.starts_with(b"HTTP/1.1 400 Bad Request")); + assert!( + response + .windows(b"invalid_policy_local_scheme".len()) + .any(|window| window == b"invalid_policy_local_scheme") + ); + } + } + + #[test] + fn middleware_failure_response_uses_platform_text_without_policy_guidance() { + let response = build_middleware_failure_response("api-policy"); + let response = String::from_utf8(response).expect("UTF-8 error response"); + let (_, body) = response.split_once("\r\n\r\n").expect("HTTP response"); + let body: serde_json::Value = serde_json::from_str(body).expect("JSON response"); + + assert_eq!(body["error"], "middleware_failed"); + assert_eq!( + body["detail"], + "Request could not be processed by configured middleware" + ); + assert_eq!(body["policy"], "api-policy"); + assert!(body.get("rule_missing").is_none()); + assert!(body.get("next_steps").is_none()); + assert!(body.get("agent_guidance").is_none()); + } + #[test] fn endpoint_only_opa_allows_declared_endpoint_without_process_identity() { let policy = include_str!("../data/sandbox-policy.rego"); @@ -4739,6 +5219,8 @@ network_policies: #[tokio::test] async fn h2c_prior_knowledge_is_blocked_for_l7_tunnel() { + use crate::l7::middleware::UninspectableTrafficGate; + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); let addr = listener.local_addr().unwrap(); let mut client = TcpStream::connect(addr).await.unwrap(); @@ -4755,10 +5237,44 @@ network_policies: .expect("client sent bytes"); assert_eq!(protocol, TunnelProtocol::H2cPriorKnowledge); assert_eq!( - unsupported_l7_tunnel_protocol_detail(protocol, true), + unsupported_l7_tunnel_protocol_detail(protocol, InspectionRequirement::L7Route), Some("HTTP/2 prior-knowledge (h2c) is not supported for L7-inspected endpoints") ); - assert_eq!(unsupported_l7_tunnel_protocol_detail(protocol, false), None); + // A fail-closed middleware chain makes inspection mandatory even for + // an L4-only endpoint. + assert_eq!( + unsupported_l7_tunnel_protocol_detail( + protocol, + InspectionRequirement::RequiredMiddleware + ), + Some("HTTP/2 prior-knowledge (h2c) cannot be inspected by required middleware") + ); + assert_eq!( + unsupported_l7_tunnel_protocol_detail( + TunnelProtocol::Unsupported, + InspectionRequirement::RequiredMiddleware + ), + Some("Unsupported tunnel protocol cannot be inspected by required middleware") + ); + assert_eq!( + unsupported_l7_tunnel_protocol_detail(protocol, InspectionRequirement::None), + None + ); + + // The L7 route owns the wording even when middleware also requires + // inspection; the middleware requirement applies only without a route. + assert_eq!( + inspection_requirement(true, UninspectableTrafficGate::Deny), + InspectionRequirement::L7Route + ); + assert_eq!( + inspection_requirement(false, UninspectableTrafficGate::Deny), + InspectionRequirement::RequiredMiddleware + ); + assert_eq!( + inspection_requirement(false, UninspectableTrafficGate::BypassWithFinding), + InspectionRequirement::None + ); } #[tokio::test] @@ -4861,7 +5377,7 @@ network_policies: } #[test] - fn forward_l7_hard_deny_reason_includes_jsonrpc_errors() { + fn l7_hard_deny_reason_includes_jsonrpc_errors() { let cases: &[(&[u8], &str)] = &[ (b"{", "JSON-RPC request rejected: invalid JSON"), ( @@ -4882,15 +5398,18 @@ network_policies: )), }; - let reason = forward_l7_hard_deny_reason(crate::l7::L7Protocol::JsonRpc, &request_info) - .expect("JSON-RPC parse error"); + let reason = crate::l7::relay::l7_request_hard_deny_reason( + crate::l7::L7Protocol::JsonRpc, + &request_info, + ) + .expect("JSON-RPC parse error"); assert_eq!(reason, expected_reason); } } #[test] - fn forward_l7_hard_deny_reason_includes_jsonrpc_response_frames() { + fn l7_hard_deny_reason_includes_jsonrpc_response_frames() { let request_info = crate::l7::L7RequestInfo { action: "POST".to_string(), target: "/rpc".to_string(), @@ -4905,16 +5424,129 @@ network_policies: }), }; - let reason = forward_l7_hard_deny_reason(crate::l7::L7Protocol::JsonRpc, &request_info) - .expect("JSON-RPC response hard deny"); + let reason = crate::l7::relay::l7_request_hard_deny_reason( + crate::l7::L7Protocol::JsonRpc, + &request_info, + ) + .expect("JSON-RPC response hard deny"); assert_eq!(reason, crate::l7::relay::JSONRPC_RESPONSE_FRAME_DENY_REASON); assert!( - forward_l7_hard_deny_reason(crate::l7::L7Protocol::Mcp, &request_info).is_none(), + crate::l7::relay::l7_request_hard_deny_reason( + crate::l7::L7Protocol::Mcp, + &request_info, + ) + .is_none(), "MCP response frames are evaluated by policy instead of hard-denied" ); } + #[tokio::test] + async fn forward_middleware_pipeline_denies_policy_invalid_transformation() { + const TEST_POLICY: &str = include_str!("../data/sandbox-policy.rego"); + let data = r#" +network_policies: + jsonrpc_api: + name: jsonrpc_api + endpoints: + - host: api.example.test + port: 80 + path: /rpc + protocol: json-rpc + enforcement: enforce + rules: + - allow: + method: sk-ABCDEFGHIJKLMNOP + binaries: + - { path: /usr/bin/node } +"#; + let engine = OpaEngine::from_strings(TEST_POLICY, data).unwrap(); + let input = crate::opa::NetworkInput { + host: "api.example.test".into(), + port: 80, + binary_path: PathBuf::from("/usr/bin/node"), + binary_sha256: "unused".into(), + ancestors: vec![], + cmdline_paths: vec![], + }; + let (endpoint, generation) = engine + .query_endpoint_config_with_generation(&input) + .expect("endpoint config"); + let config = crate::l7::parse_l7_config(&endpoint.expect("JSON-RPC endpoint")) + .expect("parse JSON-RPC config"); + let tunnel_engine = engine.clone_engine_for_tunnel(generation).unwrap(); + let body = br#"{"jsonrpc":"2.0","id":1,"method":"sk-ABCDEFGHIJKLMNOP"}"#; + let request_info = crate::l7::L7RequestInfo { + action: "POST".into(), + target: "/rpc".into(), + query_params: std::collections::HashMap::new(), + graphql: None, + jsonrpc: Some(crate::l7::jsonrpc::parse_jsonrpc_body_with_options( + body, + crate::l7::jsonrpc::JsonRpcInspectionOptions::for_config(&config), + )), + }; + let raw = format!( + "POST /rpc HTTP/1.1\r\nHost: api.example.test\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", + body.len(), + std::str::from_utf8(body).unwrap() + ) + .into_bytes(); + let request = + crate::l7::rest::request_from_buffered_http("POST", "/rpc", "/rpc", raw).unwrap(); + let ctx = crate::l7::relay::L7EvalContext { + host: "api.example.test".into(), + port: 80, + policy_name: "jsonrpc_api".into(), + binary_path: "/usr/bin/node".into(), + ancestors: vec![], + cmdline_paths: vec![], + secret_resolver: None, + activity_tx: None, + dynamic_credentials: None, + token_grant_resolver: None, + }; + let runner = openshell_supervisor_middleware::ChainRunner::new( + openshell_supervisor_middleware_builtins::services() + .into_iter() + .next() + .expect("built-in middleware service"), + ); + let pipeline = ForwardMiddlewarePipeline { + ctx: &ctx, + scheme: "http", + runner: &runner, + generation_guard: tunnel_engine.generation_guard(), + l7_reevaluation: Some(ForwardL7Reevaluation { + config: &config, + engine: &tunnel_engine, + request_info: &request_info, + }), + }; + let chain = vec![openshell_supervisor_middleware::ChainEntry { + name: "redactor".into(), + implementation: openshell_supervisor_middleware_builtins::BUILTIN_REGEX.into(), + order: 0, + config: prost_types::Struct::default(), + on_error: openshell_supervisor_middleware::OnError::FailClosed, + }]; + let (_app, mut client) = tokio::io::duplex(8192); + + let outcome = pipeline + .apply(request, &mut client, chain) + .await + .expect("forward middleware pipeline"); + + match outcome { + crate::l7::middleware::MiddlewareApplyResult::Denied { denial } => { + assert!(denial.is_none()); + } + crate::l7::middleware::MiddlewareApplyResult::Allowed(_) => { + panic!("policy-invalid transformed request must be denied") + } + } + } + #[test] fn forward_l7_allowed_activity_is_deferred_until_after_ssrf() { let (tx, mut rx) = mpsc::channel(4); @@ -4945,6 +5577,23 @@ network_policies: assert_eq!(event.deny_group, "l7_policy"); } + #[test] + fn forward_middleware_denial_does_not_emit_success_activity() { + let (tx, mut rx) = mpsc::channel(4); + let activity_tx = Some(tx); + + emit_activity_simple(activity_tx.as_ref(), true, "middleware"); + let event = rx + .try_recv() + .expect("middleware denial should emit the request activity"); + assert!(event.denied); + assert_eq!(event.deny_group, "middleware"); + assert!( + rx.try_recv().is_err(), + "middleware-denied forward request must not emit success activity" + ); + } + #[test] fn forward_success_activity_uses_unknown_without_l7() { let (tx, mut rx) = mpsc::channel(4); @@ -4975,10 +5624,19 @@ network_policies: request_body_credential_rewrite: bool, ) -> Result { let guard = forward_test_guard(); + let target_uri = std::str::from_utf8(raw) + .expect("forward test request is UTF-8") + .lines() + .next() + .and_then(|line| line.split(' ').nth(1)) + .expect("forward test request has an absolute target"); + let (_, host, port, _) = parse_proxy_uri(target_uri)?; + let authority = canonical_forward_authority(&host, port); let rewritten = rewrite_forward_request( raw, raw.len(), path, + &authority, resolver, request_body_credential_rewrite, ) @@ -5190,8 +5848,15 @@ network_policies: Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n\ Sec-WebSocket-Version: 13\r\n\r\n" ); - let rewritten = rewrite_forward_request(raw.as_bytes(), raw.len(), path, None, false) - .expect("forward websocket request should rewrite to origin form"); + let rewritten = rewrite_forward_request( + raw.as_bytes(), + raw.len(), + path, + &canonical_forward_authority(&host, port), + None, + false, + ) + .expect("forward websocket request should rewrite to origin form"); let websocket_extensions = crate::l7::relay::websocket_extension_mode(&config); let target = path.to_string(); let query_params = std::collections::HashMap::new(); @@ -7621,9 +8286,15 @@ network_policies: let with_token = inject_token_grant_for_forward_request("GET", "/v1/projects", raw, &ctx) .await .expect("forward token grant should inject"); - let rewritten = - rewrite_forward_request(&with_token, with_token.len(), "/v1/projects", None, false) - .expect("forward request should rewrite"); + let rewritten = rewrite_forward_request( + &with_token, + with_token.len(), + "/v1/projects", + "api.example.test:8080", + None, + false, + ) + .expect("forward request should rewrite"); let rewritten = String::from_utf8_lossy(&rewritten); assert!(rewritten.starts_with("GET /v1/projects HTTP/1.1\r\n")); @@ -7651,8 +8322,8 @@ network_policies: fn test_rewrite_get_request() { let raw = b"GET http://10.0.0.1:8000/api HTTP/1.1\r\nHost: 10.0.0.1:8000\r\nAccept: */*\r\n\r\n"; - let result = - rewrite_forward_request(raw, raw.len(), "/api", None, false).expect("should succeed"); + let result = rewrite_forward_request(raw, raw.len(), "/api", "10.0.0.1:8000", None, false) + .expect("should succeed"); let result_str = String::from_utf8_lossy(&result); assert!(result_str.starts_with("GET /api HTTP/1.1\r\n")); assert!(result_str.contains("Host: 10.0.0.1:8000")); @@ -7660,11 +8331,153 @@ network_policies: assert!(result_str.contains("Via: 1.1 openshell-sandbox")); } + #[test] + fn canonical_forward_authority_formats_ports_and_ipv6() { + for (uri, expected) in [ + ("http://API.EXAMPLE.TEST/path", "api.example.test"), + ("http://api.example.test:8080/path", "api.example.test:8080"), + ("http://[2001:DB8::1]/path", "[2001:db8::1]"), + ("http://[2001:DB8::1]:8080/path", "[2001:db8::1]:8080"), + ] { + let (_, host, port, _) = parse_proxy_uri(uri).expect("parse absolute target"); + assert_eq!(canonical_forward_authority(&host, port), expected); + } + } + + #[test] + fn forward_host_header_is_replaced_from_absolute_target() { + let raw = b"POST http://allowed.example.test:8080/api HTTP/1.1\r\n\ + Host: disallowed.example.test\r\n\ + hOsT: second.example.test\r\n\ + Content-Length: 4\r\n\r\nbody"; + let authority = "allowed.example.test:8080"; + + let canonical = canonicalize_forward_host_header(raw, authority) + .expect("canonicalize received Host fields"); + let canonical = String::from_utf8(canonical).expect("canonical request is UTF-8"); + let host_fields: Vec<_> = canonical + .split("\r\n") + .skip(1) + .take_while(|line| !line.is_empty()) + .filter(|line| { + line.split_once(':') + .is_some_and(|(name, _)| name.eq_ignore_ascii_case("host")) + }) + .collect(); + assert_eq!(host_fields, ["Host: allowed.example.test:8080"]); + assert!(!canonical.contains("disallowed.example.test")); + assert!(!canonical.contains("second.example.test")); + assert!(canonical.ends_with("\r\n\r\nbody")); + + let rewritten = rewrite_forward_request(raw, raw.len(), "/api", authority, None, false) + .expect("final rewrite enforces canonical Host"); + let rewritten = String::from_utf8(rewritten).expect("rewritten request is UTF-8"); + assert_eq!( + rewritten + .split("\r\n") + .filter(|line| { + line.split_once(':') + .is_some_and(|(name, _)| name.eq_ignore_ascii_case("host")) + }) + .collect::>(), + ["Host: allowed.example.test:8080"] + ); + assert!(!rewritten.contains("disallowed.example.test")); + assert!(!rewritten.contains("second.example.test")); + } + + #[test] + fn forward_host_header_is_generated_when_missing() { + let raw = b"GET http://allowed.example.test/api HTTP/1.1\r\nAccept: */*\r\n\r\n"; + let canonical = canonicalize_forward_host_header(raw, "allowed.example.test") + .expect("generate missing Host field"); + let canonical = String::from_utf8(canonical).expect("canonical request is UTF-8"); + assert!(canonical.starts_with( + "GET http://allowed.example.test/api HTTP/1.1\r\nHost: allowed.example.test\r\n" + )); + } + + #[tokio::test] + async fn middleware_selected_forward_keeps_canonical_host_on_the_wire() { + let authority = "allowed.example.test"; + let raw = b"GET http://allowed.example.test/api HTTP/1.1\r\n\ + Host: disallowed.example.test\r\n\ + HOST: second.example.test\r\n\r\n"; + let raw = canonicalize_forward_host_header(raw, authority) + .expect("canonicalize Host before middleware"); + let request = crate::l7::rest::request_from_buffered_http("GET", "/api", "/api", raw) + .expect("build middleware request"); + let ctx = crate::l7::relay::L7EvalContext { + host: authority.into(), + port: 80, + policy_name: "test".into(), + binary_path: "/usr/bin/node".into(), + ancestors: vec![], + cmdline_paths: vec![], + secret_resolver: None, + activity_tx: None, + dynamic_credentials: None, + token_grant_resolver: None, + }; + let runner = openshell_supervisor_middleware::ChainRunner::new( + openshell_supervisor_middleware_builtins::services() + .into_iter() + .next() + .expect("built-in middleware service"), + ); + let guard = forward_test_guard(); + let pipeline = ForwardMiddlewarePipeline { + ctx: &ctx, + scheme: "http", + runner: &runner, + generation_guard: &guard, + l7_reevaluation: None, + }; + let chain = vec![openshell_supervisor_middleware::ChainEntry { + name: "redactor".into(), + implementation: openshell_supervisor_middleware_builtins::BUILTIN_REGEX.into(), + order: 0, + config: prost_types::Struct::default(), + on_error: openshell_supervisor_middleware::OnError::FailClosed, + }]; + let (_app, mut client) = tokio::io::duplex(8192); + + let allowed = pipeline + .apply(request, &mut client, chain) + .await + .expect("middleware pipeline"); + let crate::l7::middleware::MiddlewareApplyResult::Allowed(request) = allowed else { + panic!("middleware-selected request should be allowed"); + }; + let rewritten = rewrite_forward_request( + &request.raw_header, + request.raw_header.len(), + "/api", + authority, + None, + false, + ) + .expect("rewrite middleware-selected request"); + let rewritten = String::from_utf8(rewritten).expect("rewritten request is UTF-8"); + assert_eq!( + rewritten + .split("\r\n") + .filter(|line| { + line.split_once(':') + .is_some_and(|(name, _)| name.eq_ignore_ascii_case("host")) + }) + .collect::>(), + ["Host: allowed.example.test"] + ); + assert!(!rewritten.contains("disallowed.example.test")); + assert!(!rewritten.contains("second.example.test")); + } + #[test] fn test_rewrite_strips_proxy_headers() { let raw = b"GET http://host/p HTTP/1.1\r\nHost: host\r\nProxy-Authorization: Basic abc\r\nProxy-Connection: keep-alive\r\nAccept: */*\r\n\r\n"; - let result = - rewrite_forward_request(raw, raw.len(), "/p", None, false).expect("should succeed"); + let result = rewrite_forward_request(raw, raw.len(), "/p", "host", None, false) + .expect("should succeed"); let result_str = String::from_utf8_lossy(&result); assert!( !result_str @@ -7678,18 +8491,32 @@ network_policies: #[test] fn test_rewrite_replaces_connection_header() { let raw = b"GET http://host/p HTTP/1.1\r\nHost: host\r\nConnection: keep-alive\r\n\r\n"; - let result = - rewrite_forward_request(raw, raw.len(), "/p", None, false).expect("should succeed"); + let result = rewrite_forward_request(raw, raw.len(), "/p", "host", None, false) + .expect("should succeed"); let result_str = String::from_utf8_lossy(&result); assert!(result_str.contains("Connection: close")); assert!(!result_str.contains("keep-alive")); } + #[test] + fn test_rewrite_strips_connection_nominated_headers() { + let raw = b"GET http://host/p HTTP/1.1\r\nHost: host\r\nX-Guard: hidden\r\nConnection: keep-alive, x-guard\r\nKeep-Alive: timeout=5\r\nX-Visible: yes\r\n\r\n"; + let result = rewrite_forward_request(raw, raw.len(), "/p", "host", None, false) + .expect("should succeed"); + let result_str = String::from_utf8_lossy(&result); + let lower = result_str.to_ascii_lowercase(); + + assert!(!lower.contains("x-guard:")); + assert!(!lower.contains("keep-alive:")); + assert!(result_str.contains("Connection: close\r\n")); + assert!(result_str.contains("X-Visible: yes\r\n")); + } + #[test] fn test_rewrite_preserves_body_overflow() { let raw = b"POST http://host/api HTTP/1.1\r\nHost: host\r\nContent-Length: 13\r\n\r\n{\"key\":\"val\"}"; - let result = - rewrite_forward_request(raw, raw.len(), "/api", None, false).expect("should succeed"); + let result = rewrite_forward_request(raw, raw.len(), "/api", "host", None, false) + .expect("should succeed"); let result_str = String::from_utf8_lossy(&result); assert!(result_str.contains("{\"key\":\"val\"}")); assert!(result_str.contains("POST /api HTTP/1.1")); @@ -7698,8 +8525,8 @@ network_policies: #[test] fn test_rewrite_preserves_existing_via() { let raw = b"GET http://host/p HTTP/1.1\r\nHost: host\r\nVia: 1.0 upstream\r\n\r\n"; - let result = - rewrite_forward_request(raw, raw.len(), "/p", None, false).expect("should succeed"); + let result = rewrite_forward_request(raw, raw.len(), "/p", "host", None, false) + .expect("should succeed"); let result_str = String::from_utf8_lossy(&result); assert!(result_str.contains("Via: 1.0 upstream")); // Should not add a second Via header @@ -7722,7 +8549,7 @@ network_policies: .expect("canonicalization should succeed for the attack payload"); assert_eq!(canon.path, "/secret"); - let rewritten = rewrite_forward_request(raw, raw.len(), &canon.path, None, false) + let rewritten = rewrite_forward_request(raw, raw.len(), &canon.path, "host", None, false) .expect("rewrite_forward_request should succeed"); let rewritten_str = String::from_utf8_lossy(&rewritten); assert!( @@ -7748,8 +8575,9 @@ network_policies: _ => canon.path, }; - let rewritten = rewrite_forward_request(raw, raw.len(), &upstream_target, None, false) - .expect("rewrite_forward_request should succeed"); + let rewritten = + rewrite_forward_request(raw, raw.len(), &upstream_target, "host", None, false) + .expect("rewrite_forward_request should succeed"); let rewritten_str = String::from_utf8_lossy(&rewritten); assert!( rewritten_str.starts_with( @@ -7767,8 +8595,9 @@ network_policies: .collect(), ); let raw = b"GET http://host/p HTTP/1.1\r\nHost: host\r\nAuthorization: Bearer openshell:resolve:env:ANTHROPIC_API_KEY\r\n\r\n"; - let result = rewrite_forward_request(raw, raw.len(), "/p", resolver.as_ref(), false) - .expect("should succeed"); + let result = + rewrite_forward_request(raw, raw.len(), "/p", "host", resolver.as_ref(), false) + .expect("should succeed"); let result_str = String::from_utf8_lossy(&result); assert!(result_str.contains("Authorization: Bearer sk-test")); assert!(!result_str.contains("openshell:resolve:env:ANTHROPIC_API_KEY")); @@ -7874,6 +8703,7 @@ network_policies: raw.as_bytes(), raw.len(), "/api/messages", + "api.example.com", Some(&resolver), true, ) @@ -7912,18 +8742,33 @@ network_policies: fn test_forward_rewrite_preserves_websocket_upgrade_connection_header() { let raw = "GET http://gateway.example.test/ws HTTP/1.1\r\n\ Host: gateway.example.test\r\n\ - Upgrade: websocket\r\n\ + Upgrade: h2c\r\n\ + Upgrade: h2c, websocket\r\n\ Connection: keep-alive, Upgrade\r\n\ + Keep-Alive: timeout=5\r\n\ + X-Guard: hidden\r\n\ + Connection: x-guard\r\n\ Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n\ Sec-WebSocket-Extensions: permessage-deflate; client_no_context_takeover\r\n\ Sec-WebSocket-Version: 13\r\n\r\n"; - let result = rewrite_forward_request(raw.as_bytes(), raw.len(), "/ws", None, false) - .expect("websocket forward rewrite should succeed"); + let result = rewrite_forward_request( + raw.as_bytes(), + raw.len(), + "/ws", + "gateway.example.test", + None, + false, + ) + .expect("websocket forward rewrite should succeed"); let result_str = String::from_utf8_lossy(&result); assert!(result_str.starts_with("GET /ws HTTP/1.1\r\n")); - assert!(result_str.contains("Connection: keep-alive, Upgrade\r\n")); + assert_eq!(result_str.matches("Connection: Upgrade\r\n").count(), 1); + assert_eq!(result_str.matches("Upgrade: websocket\r\n").count(), 1); + assert!(!result_str.to_ascii_lowercase().contains("upgrade: h2c")); + assert!(!result_str.contains("keep-alive")); + assert!(!result_str.to_ascii_lowercase().contains("x-guard:")); assert!( !result_str.contains("Connection: close\r\n"), "websocket forward proxy must not strip the upgrade token" @@ -7941,7 +8786,7 @@ network_policies: engine.reload(policy, policy_data).unwrap(); let raw = b"GET http://host/api HTTP/1.1\r\nHost: host\r\n\r\n"; - let rewritten = rewrite_forward_request(raw, raw.len(), "/api", None, false) + let rewritten = rewrite_forward_request(raw, raw.len(), "/api", "host", None, false) .expect("rewrite should succeed"); let (mut proxy_to_upstream, mut upstream_side) = tokio::io::duplex(8192); let (mut _app_side, mut proxy_to_client) = tokio::io::duplex(8192); @@ -7984,7 +8829,7 @@ network_policies: .unwrap(); let raw = b"POST http://host/api HTTP/1.1\r\nHost: host\r\nContent-Length: 4\r\nTransfer-Encoding: chunked\r\n\r\n0\r\n\r\n"; - let rewritten = rewrite_forward_request(raw, raw.len(), "/api", None, false) + let rewritten = rewrite_forward_request(raw, raw.len(), "/api", "host", None, false) .expect("rewrite should succeed"); let (mut proxy_to_upstream, mut upstream_side) = tokio::io::duplex(8192); let (mut _app_side, mut proxy_to_client) = tokio::io::duplex(8192); @@ -8287,6 +9132,28 @@ network_policies: assert_eq!(body["detail"], "connection to api.example.com:443 failed"); } + #[test] + fn middleware_deny_response_uses_policy_config_identity() { + let resp = build_middleware_deny_response( + "api-policy", + &openshell_supervisor_middleware::MiddlewareDenial { + config_name: "prototype-content-guard".into(), + reason_code: Some("content_match".into()), + }, + ); + let resp_str = String::from_utf8(resp).unwrap(); + let body_start = resp_str.find("\r\n\r\n").unwrap() + 4; + let body: serde_json::Value = serde_json::from_str(&resp_str[body_start..]).unwrap(); + + assert_eq!(body["error"], "middleware_denied"); + assert_eq!(body["detail"], "Request rejected by configured middleware"); + assert_eq!(body["middleware"], "prototype-content-guard"); + assert_eq!(body["reason_code"], "content_match"); + assert_eq!(body["policy"], "api-policy"); + assert!(body.get("rule_missing").is_none()); + assert!(body.get("next_steps").is_none()); + } + /// Locks the fail-closed response the CONNECT handler sends when TLS is /// detected but no termination state exists (ephemeral CA setup failed). /// The proxy must refuse the connection with a 503 instead of raw-tunneling diff --git a/docs/extensibility/supervisor-middleware.mdx b/docs/extensibility/supervisor-middleware.mdx new file mode 100644 index 0000000000..f3bdcac9bb --- /dev/null +++ b/docs/extensibility/supervisor-middleware.mdx @@ -0,0 +1,179 @@ +--- +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +title: "Supervisor Middleware" +sidebar-title: "Supervisor Middleware" +description: "Configure and operate built-in and operator-run middleware for sandbox HTTP requests." +keywords: "Generative AI, Cybersecurity, AI Agents, Supervisor Middleware, Extensibility, Request Filtering" +--- + +Supervisor middleware adds ordered request-processing stages to allowed HTTP egress. Middleware runs after network and L7 policy admit a request and before OpenShell injects provider credentials. A stage can allow or deny the request, replace its body, add approved headers, and report audit-safe findings. + +Middleware selection is independent of the network policy rule that admitted the request. OpenShell matches middleware by destination host, so the same middleware applies consistently across broad, specific, user-authored, and provider-derived network policies. + +## Request Flow + +For each inspected HTTP request, the supervisor: + +1. Evaluates network and L7 policy. +2. Selects middleware whose host selectors match the admitted destination. +3. Buffers the request body using the largest body limit in the selected chain. +4. Runs matching middleware by ascending `order`. Policy validation rejects duplicate order values. +5. Re-checks body-aware protocol policy (GraphQL, JSON-RPC, MCP) after each stage that replaces the body. Every middleware receives a payload the policy admits, and a transformation cannot smuggle a denied or unparseable operation to a later stage or the upstream. +6. Applies allowed transformations, injects provider credentials, and forwards the request. + +Because each transformed body is re-checked before the next stage runs, a middleware hook always receives a request that satisfies the sandbox policy. A stage whose output the policy rejects stops the chain; under `enforcement: audit` the rejection is logged and the request proceeds. + +If post-transformation policy evaluation itself fails, OpenShell denies the request and emits a high-severity detection finding. This failure is separate from middleware `on_error` because the middleware completed successfully; the sandbox policy could not validate its output. + +Middleware receives the request before credential injection. Operator-run services cannot inspect OpenShell-managed credentials. Middleware-visible request headers are delivered in wire order and repeated header names are preserved as separate entries. OpenShell filters credential, routing, framing, and hop-by-hop headers before invoking middleware. It rejects malformed request headers and unsupported transfer-coding sequences before middleware or policy dispatch. Headers named by a request's `Connection` field are omitted from middleware input and removed before forwarding, except for the validated WebSocket upgrade pair. + +## Choose a Middleware Type + +| Type | Registration | Body limit | Deployment | +| --- | --- | --- | --- | +| Built-in | None | Defined by OpenShell | Runs inside the supervisor | +| Operator-run service | Required in gateway TOML | Set by the operator, up to the service capability | Runs as a separate service reachable by the gateway and supervisors | + +`openshell/regex` is an example built-in middleware. It replaces only simple, self-contained token patterns in UTF-8 request bodies; the initial pattern recognizes `sk-` tokens. It does not infer values from keyword assignments such as JSON `password` fields. This best-effort text transformation is not parser-aware and does not guarantee that it will detect or fully remove sensitive values. Its `config` accepts one field, `mode: redact`, which is also the default when the field is omitted. Unknown config fields and non-string values are rejected at policy validation. Custom expressions are not configurable yet. + +Operator-run services expose bindings for supported operation and phase pairs. A binding is identified by its operation and phase; V1 supports only `HttpRequest/pre_credentials`. Policies attach the complete middleware by its operator-owned gateway registration name. + +## Register a Middleware Service + +Start an operator-run service before starting the gateway, then add a registration to the local gateway TOML: + +```toml +[[openshell.supervisor.middleware]] +name = "local-content-guard" +grpc_endpoint = "http://host.openshell.internal:50051" +max_body_bytes = 262144 +timeout = "500ms" +``` + +| Field | Description | +| --- | --- | +| `name` | Operator-owned registration name used by policy attachments and diagnostics. Names must be unique, and `openshell/` is reserved for built-ins. | +| `grpc_endpoint` | Service address reachable from both the gateway and sandbox supervisors. Supports plaintext `http://` and TLS `https://` with platform trust roots. | +| `max_body_bytes` | Operator limit applied to every binding exposed by the service, up to the 4 MiB platform maximum. | +| `timeout` | Optional service-wide RPC timeout using an integer with an `ms` or `s` suffix. Defaults to `500ms`; valid values range from `10ms` through `30s`. | + +Each binding returned by `Describe` may advertise a shorter `timeout` using the same syntax and bounds. The operator-configured service timeout is a ceiling: OpenShell uses the smaller of the binding and service values. An omitted binding timeout inherits the service setting, and an omitted service setting uses the 500 ms platform default. OpenShell rejects an invalid timeout before accepting the manifest. The service timeout applies to `Describe`, while the effective binding timeout applies to `ValidateConfig` and `EvaluateHttpRequest`. + +The gateway connects to every registered service and verifies its capabilities before accepting traffic. Gateway startup fails when a service is unavailable, reports an invalid capability, or exposes more than one binding for the same operation and phase. The manifest `name` is diagnostic metadata and does not need to match the operator registration name. Operator-run registration names cannot claim the reserved `openshell/` namespace. + +Registration is static. Restart the gateway after adding, removing, or changing a service. See [Gateway Configuration](/reference/gateway-config#supervisor-middleware-services) for the complete gateway TOML context. + +## Apply Middleware with Policy + +Add middleware configs to the top-level `network_middlewares` map. Each key is the policy-local config name: + +```yaml +network_middlewares: + regex-redactor: + name: Redact API tokens + middleware: openshell/regex + order: 10 + config: + mode: redact + on_error: fail_closed + endpoints: + include: ["*.example.com"] + exclude: ["trusted.example.com"] +``` + +Each config has a stable policy-local identity from its map key, an optional human-readable `name` that defaults to that key, a built-in or operator-owned registration name in `middleware`, an integer `order`, implementation-owned `config`, failure behavior, and host selectors. The optional name does not replace the map key for attachment or future keyed updates. A policy accepts at most 10 middleware configs. + +`include` selects destination hosts. `exclude` takes precedence and removes hosts from that selection. Each config accepts at most 32 combined include and exclude patterns. Matching is case-insensitive and uses the same exact-host and DNS glob behavior as network policy endpoints: `*` matches exactly one DNS label, `**` matches one or more labels, and intra-label patterns like `*-api.example.com` work. Brace alternates such as `{prod,staging}` are rejected at validation; list each host pattern separately. + +Matching configs run once each by ascending `order`; lower values run first. Order values must be unique across the complete policy, even when endpoint selectors do not overlap. The default order is `0`, so policies with multiple configs normally set explicit values. Different map keys may attach the same middleware and run as separate stages. Map keys are structurally unique. Runtime selection defensively rejects chains with more than 10 stages. + +See [Policy Schema](/reference/policy-schema#network-middleware) for the complete field reference. + +## Configure Failure Behavior + +`on_error` controls what happens when middleware is unavailable, rejects its configuration, returns an invalid result, or exceeds a body limit. + +| Value | Behavior | +| --- | --- | +| `fail_closed` | Denies the request when the middleware stage fails. This is the default. | +| `fail_open` | Skips the failed stage and continues the request through the remaining chain. | + +Use `fail_open` only when bypassing the middleware preserves the intended security policy. OpenShell emits a detection finding when a failed stage is bypassed. + +An explicit deny decision always stops the chain and denies the request, regardless of `on_error`. The HTTP response uses `error: middleware_denied`, identifies the policy-local middleware config, and omits policy-advisor remediation because the network and L7 allow rules already matched. OpenShell never copies the free-form middleware `reason` into the response or security logs. A service can instead return an optional stable `reason_code`: 1–64 bytes, starting with a lowercase ASCII letter and containing only lowercase ASCII letters, digits, and underscores. Invalid codes make the result a middleware failure governed by `on_error`. + +```json +{ + "error": "middleware_denied", + "detail": "Request rejected by configured middleware", + "policy": "api-policy", + "middleware": "prototype-content-guard", + "reason_code": "content_match" +} +``` + +A failed `fail_closed` stage uses `error: middleware_failed` and a platform-owned `detail`. It also omits `rule_missing`, `next_steps`, and `agent_guidance`: the failure did not result from a missing network or L7 policy rule, and changing policy cannot repair it. Runtime diagnostic text is available only through sanitized operator telemetry. + +Middleware decisions are enforced regardless of the endpoint's `enforcement` mode. `enforcement: audit` applies to an endpoint's network and L7 policy rules and does not bypass middleware: a middleware deny, or a failed `fail_closed` stage, blocks the request even on an audit endpoint. A middleware service that needs to observe traffic without blocking should return an allow decision with findings, which OpenShell emits as detection findings. + +## Set Body Limits + +Every middleware binding declares the largest request or replacement body it supports. + +- Built-in middleware uses its OpenShell-defined limit. +- Each operator-run registration sets `max_body_bytes` no higher than the service capability. +- A selected chain buffers using its largest stage limit, so every stage that can process the body receives it. +- The same per-stage limit applies to request bodies and replacement bodies. + +The gateway rejects a registration whose operator limit exceeds the service capability or the 4 MiB platform maximum instead of silently clamping it. OpenShell also bounds the non-body protobuf components: 64 KiB for service config, 4 KiB for request context, 32 KiB for the target, and 128 request header lines totaling at most 64 KiB encoded. Results allow a 4 KiB discarded free-form reason, a 64-byte validated reason code, 64 header mutations totaling at most 64 KiB encoded, 32 findings of at most 4 KiB encoded each, and 64 metadata entries totaling at most 32 KiB. Middleware gRPC servers should configure request and response message limits to at least 4 MiB plus 293 KiB so every platform-valid envelope fits. + +At request time, exceeding a selected stage's limit is a middleware failure for that stage alone and follows that config's `on_error` behavior; other stages in the chain still run against their own limits. OpenShell can apply `fail_open` to an oversized `Content-Length` before consuming body bytes. A chunked body can cross the limit only after bytes have been consumed, so OpenShell denies that request because it cannot safely resume the original stream. + +## Mutate Request Headers + +A middleware result can return ordered header mutations before OpenShell injects credentials. A `write` mutation adds a value when the case-insensitive header name is absent and selects one behavior when it is already present: + +- `append` adds another field value. +- `overwrite` removes every existing value before adding the new value. +- `skip` leaves existing values unchanged. + +A `remove` mutation removes every value for a case-insensitive header name. OpenShell applies each successful stage's mutations before invoking the next middleware, so later stages observe the accumulated header state. + +Header writes must use the `x-openshell-middleware-` prefix. Removes may target other middleware-visible request headers. Protected credential, routing, framing, and hop-by-hop headers are always rejected. Header values must not contain control characters. + +OpenShell validates and applies each stage's mutations atomically. An invalid operation discards every mutation from that stage and follows its `on_error` behavior. Built-in failures can name the offending header. Operator-run failures use a platform-owned error code so request-derived header text cannot reach logs or denied responses. + +## Operate Middleware Services + +Plan startup and updates around these boundaries: + +- Start registered services before the gateway. The gateway validates every registration during startup. +- Keep service endpoints reachable from both the gateway and sandbox supervisors. The supervisors call operator-run services directly on the request path. +- Restart the gateway after changing registrations. +- Keep required services available before creating or updating policies. The gateway validates implementation-owned config before persisting a policy. +- Treat `fail_open` as an explicit availability-over-enforcement decision. + +When the effective sandbox configuration changes, a running supervisor validates the new service registry before installing it. If the reload fails, the supervisor keeps its last-known-good registry and emits a configuration failure event. + +## Observe Middleware + +Middleware activity is emitted through OpenShell's OCSF logging: + +- Each invocation records its policy-local config name, attached middleware name, decision, transformation state, and failure state. +- A denied invocation records a platform-owned reason derived from the policy-local config name and optional validated reason code. OpenShell does not record service-provided free-form reason text. +- A bypass under `fail_open` emits a detection finding. +- A required stage that fails closed emits a high-severity detection finding. +- Built-in findings include their type, label, and aggregate count. Operator-run findings use the operator-owned registration name and a platform label plus the aggregate count; OpenShell does not log service-provided finding text or diagnostic metadata. A stage can return at most 32 findings. Exceeding the per-stage cap is an invalid response handled through `on_error`. A maximum 10-stage chain retains and emits up to 320 findings without silently dropping findings from later stages. +- Registry reload success and failure are emitted as configuration state changes. + +See [Logging](/observability/logging) for log access and [OCSF JSON Export](/observability/ocsf-json-export) for structured export. + +## Current Limitations + +- Middleware applies only to HTTP requests parsed by the supervisor. Traffic the supervisor cannot inspect, such as HTTP/2 prior knowledge or non-HTTP TCP protocols, is denied on hosts matched by a fail-closed middleware, and relayed with a detection finding when every matching middleware is `fail_open`. +- The typed operation and phase are `HTTP_REQUEST/PRE_CREDENTIALS`. +- Selection uses destination host include and exclude patterns. +- A fail-closed middleware cannot cover `tls: skip` endpoints because OpenShell cannot inspect that traffic. An all-`fail_open` match may cover the endpoint; OpenShell bypasses the middleware and emits a detection finding. +- Operator-run services support plaintext `http://` and TLS `https://` endpoints. HTTPS certificates must chain to a CA in the platform trust store. +- Custom trust roots, client authentication, health checks, and runtime registration are not available. diff --git a/docs/index.yml b/docs/index.yml index b2443e4afd..45db451a78 100644 --- a/docs/index.yml +++ b/docs/index.yml @@ -19,6 +19,8 @@ navigation: title: "Manage OpenShell" - folder: providers title: "Providers" +- folder: extensibility + title: "Extensibility" - folder: observability title: "Observability" - folder: kubernetes diff --git a/docs/observability/logging.mdx b/docs/observability/logging.mdx index dcfe9f19d4..7a13ffea0b 100644 --- a/docs/observability/logging.mdx +++ b/docs/observability/logging.mdx @@ -94,9 +94,9 @@ CLASS:ACTIVITY [SEVERITY] ACTION DETAILS [CONTEXT] - SSH: peer address and authentication type - Process: `name(pid)` with exit code or command line - Config: description of what changed -- Finding: quoted title with confidence level +- Finding: quoted title with the stable finding type, optional confidence, and source-specific context attributes when available -**Context** in brackets at the end provides the policy rule and enforcement engine that produced the decision. +**Context** in brackets provides structured fields such as policy provenance, source-specific attributes, and denial reasons. ### Examples @@ -130,6 +130,13 @@ An HTTP request to a non-default port. HTTP log URLs include the port whenever i OCSF HTTP:GET [INFO] ALLOWED GET http://api.internal.corp:8080/v1/status [policy:internal_api engine:opa] ``` +A supervisor middleware HTTP event records whether it transformed the request. If the middleware also emits a finding, that remains a separate event: + +```text +OCSF HTTP:POST [INFO] ALLOWED POST http://httpbin.org:443/anything [policy:httpbin engine:middleware] [failed:false transformed:true] +OCSF FINDING:CREATE [MED] "configured content matched" [type:content_guard.match count:1 middleware:prototype-content-guard] +``` + Proxy and SSH servers ready: ```text @@ -160,6 +167,8 @@ OCSF CONFIG:LOADED [INFO] Policy reloaded successfully [policy_hash:0cc0c2b52557 Denied `NET:` and `HTTP:` events carry a `[reason:...]` suffix that surfaces the decision detail from the event's `status_detail` field. The reason helps distinguish between policy misses, SSRF hardening, and L7 enforcement without inspecting the full OCSF JSONL record. +For supervisor middleware denials, `status_detail` contains a platform-owned reason derived from the policy-local middleware config name and optional validated reason code. Middleware failure details also use platform-owned error codes. OpenShell does not copy per-request service text into logs. + Common reason phrases emitted by the sandbox include: | Reason | Meaning | @@ -196,9 +205,9 @@ An upstream that the proxy cannot reach returns `502 Bad Gateway`: } ``` -The `error` field is a short machine-readable code (`policy_denied`, `ssrf_denied`, `upstream_unreachable`). The `detail` field is a human-readable explanation suitable for display in an agent transcript. +The `error` field is a short machine-readable code (`policy_denied`, `middleware_denied`, `middleware_failed`, `ssrf_denied`, `upstream_unreachable`). The `detail` field is a human-readable explanation suitable for display in an agent transcript. -For L7 REST denials, the body also includes structured policy fields such as `method`, `path`, `rule_missing`, and `next_steps`. When policy advisor is enabled, it also includes `agent_guidance`, a short plain-language instruction telling the agent to read `/etc/openshell/skills/policy_advisor.md`, propose the narrowest rule through `http://policy.local/v1/proposals`, wait for `policy_reloaded: true`, and retry. +For L7 REST policy denials, the body also includes structured policy fields such as `method`, `path`, `rule_missing`, and `next_steps`. When policy advisor is enabled, it also includes `agent_guidance`, a short plain-language instruction telling the agent to read `/etc/openshell/skills/policy_advisor.md`, propose the narrowest rule through `http://policy.local/v1/proposals`, wait for `policy_reloaded: true`, and retry. A middleware denial instead identifies the policy-local config in `middleware` and can include a validated `reason_code`. A fail-closed runtime failure uses `middleware_failed` with platform-owned text. Both middleware responses omit `rule_missing`, `next_steps`, and `agent_guidance` because no policy rule is missing. ## Filesystem Sandbox Logs diff --git a/docs/reference/gateway-config.mdx b/docs/reference/gateway-config.mdx index b0efa87e40..3dde7643d5 100644 --- a/docs/reference/gateway-config.mdx +++ b/docs/reference/gateway-config.mdx @@ -111,6 +111,14 @@ provider_profile_sources = [ { type = "user" }, ] +# Operator-run supervisor middleware. The gRPC endpoint must be reachable from +# both the gateway and sandbox supervisors. +[[openshell.supervisor.middleware]] +name = "local-content-guard" +grpc_endpoint = "http://host.openshell.internal:50051" +max_body_bytes = 262144 +timeout = "500ms" + # Gateway listener TLS (distinct from the per-driver guest_tls_*). [openshell.gateway.tls] cert_path = "/etc/openshell/certs/gateway.pem" @@ -167,6 +175,32 @@ Local Docker, Podman, and VM gateways can also set `[openshell.gateway.mtls_auth `[openshell.gateway.auth] allow_unauthenticated_users = true` is an unsafe local-development and trusted-proxy escape hatch. It accepts user-facing CLI/API calls without OIDC or mTLS credentials while sandbox supervisors still authenticate with gateway-minted sandbox JWTs. Leave it false for shared and production gateways. +## Supervisor Middleware Services + +Register operator-run supervisor middleware services with one or more `[[openshell.supervisor.middleware]]` entries. Registration is static and operator-owned; changing it requires restarting the gateway. + +```toml +[[openshell.supervisor.middleware]] +name = "local-content-guard" +grpc_endpoint = "http://host.openshell.internal:50051" +max_body_bytes = 262144 +timeout = "500ms" +``` + +Each service implements the supervisor middleware gRPC contract and exposes bindings through `Describe`. Policies reference the operator-owned registration `name`, attaching the complete middleware and all of its bindings. Bindings are identified by operation and phase. A manifest may expose at most one binding for each operation and phase pair; V1 supports only `HttpRequest/pre_credentials`, so a service currently exposes one binding. Registration names must be unique, and operator-run registrations cannot claim the reserved `openshell/` namespace. The service-reported manifest name is diagnostic metadata and does not need to match the registration name. + +The gateway connects to every registered service and validates `Describe` before it starts. The service must therefore be running before the gateway. Policy creation and full policy updates call `ValidateConfig`; an unavailable service or invalid middleware configuration rejects the policy before persistence. + +`max_body_bytes` is the operator limit for every binding exposed by the service. It must be greater than zero, no larger than each binding's advertised limit, and no larger than the 4 MiB platform maximum. OpenShell rejects an oversized value instead of silently clamping it. Middleware gRPC servers should allow messages of at least 4 MiB plus 293 KiB so a maximum-size body and its protobuf envelope fit on the transport. + +`timeout` is the operator-configured service-wide RPC timeout. It accepts the same compact duration syntax as gateway interceptors: an integer followed by `ms` or `s`, such as `500ms` or `2s`. Values must be between `10ms` and `30s`, inclusive. Omit the field to use the 500 ms platform default. A binding may advertise a shorter `timeout` in the `Describe` manifest, but it cannot extend the operator-configured deadline; OpenShell uses the smaller value. OpenShell validates both levels before accepting the service. The effective timeout covers `ValidateConfig` and `EvaluateHttpRequest`; `Describe` uses the service timeout because binding metadata is not available yet. + +The service `grpc_endpoint` currently supports plaintext `http://` and TLS `https://` using the platform trust store. Custom trust roots, client authentication, health checks, and runtime registration are not currently supported. The endpoint must be reachable from both the gateway and sandbox supervisors; use `host.openshell.internal` or another shared address that can be resolved in both places. + +See [Supervisor Middleware](/extensibility/supervisor-middleware) for selection, failure, body-limit, and operational guidance. + +## Gateway Interceptors + `[[openshell.gateway.interceptors]]` configures gateway-side interceptor services. The gateway calls each service's `Describe` RPC at startup, validates its declared OpenShell RPC bindings against the compiled service descriptor, and applies matching phases from a central gRPC middleware path. Interceptors can target only methods in the gateway's built-in allowlist of unary mutation RPCs. New RPCs are non-interceptable until they are deliberately added to that allowlist; adding one does not require handler-specific interceptor code. Request bodies are exposed as protobuf JSON objects. Fields marked secret in the protobuf schema are recursively omitted from requests and post-commit responses. Interceptors cannot patch an omitted field or a containing object. `binding_policy` controls how the manifest and operator binding configuration combine: diff --git a/docs/reference/policy-schema.mdx b/docs/reference/policy-schema.mdx index 049ad47979..721f16109d 100644 --- a/docs/reference/policy-schema.mdx +++ b/docs/reference/policy-schema.mdx @@ -20,6 +20,7 @@ filesystem_policy: { ... } landlock: { ... } process: { ... } network_policies: { ... } +network_middlewares: { ... } ``` | Field | Type | Required | Category | Description | @@ -29,6 +30,7 @@ network_policies: { ... } | `landlock` | object | No | Static | Configures Landlock LSM enforcement behavior. | | `process` | object | No | Static | Sets the user and group the agent process runs as. | | `network_policies` | map | No | Dynamic | Declares which binaries can reach which network endpoints. | +| `network_middlewares` | map | No | Dynamic | Selects ordered HTTP request middleware by destination host. | Static fields are set at sandbox creation time. Changing them requires destroying and recreating the sandbox. Dynamic fields can be updated on a running sandbox with `openshell policy update` for incremental merges or `openshell policy set` for full replacement, and take effect without restarting. @@ -164,7 +166,7 @@ Each endpoint defines a reachable destination and optional inspection rules. | `allowed_ips` | list of string | No | CIDR or IP allowlist for SSRF override. Exact user-declared hostname endpoints may resolve to RFC 1918 private addresses without this field, but wildcard, hostless, and policy-advisor-proposed endpoints still require `allowed_ips` for private resolved IPs. Entries overlapping loopback (`127.0.0.0/8`), link-local (`169.254.0.0/16`), or unspecified (`0.0.0.0`) are rejected at load time. | | `allow_encoded_slash` | bool | No | When `true`, L7 request parsing preserves `%2F` inside path segments instead of rejecting it. Use this for registries and APIs such as npm scoped packages (`/@scope%2Fname`). Defaults to `false`. | | `websocket_credential_rewrite` | bool | No | When `true` on a `protocol: rest` or `protocol: websocket` endpoint, OpenShell rewrites credential placeholders in client-to-server WebSocket text messages after an allowed HTTP `101` upgrade. Binary frames are relayed but not rewritten. Defaults to `false`. | -| `request_body_credential_rewrite` | bool | No | When `true` on a `protocol: rest` endpoint, OpenShell rewrites credential placeholders in UTF-8 `application/json`, `application/x-www-form-urlencoded`, and `text/*` request bodies before forwarding upstream. The proxy buffers at most 256 KiB and updates `Content-Length` after rewriting. Defaults to `false`. Mutually exclusive with `credential_signing`. | +| `request_body_credential_rewrite` | bool | No | When `true` on a `protocol: rest` endpoint, OpenShell rewrites credential placeholders in UTF-8 `application/json`, `application/x-www-form-urlencoded`, and `text/*` request bodies before forwarding upstream. The proxy buffers at most 256 KiB and updates `Content-Length` after rewriting. For chunked requests, the limit counts framing, extensions, and trailers. Defaults to `false`. Mutually exclusive with `credential_signing`. | | `credential_signing` | string | No | Proxy-side credential signing mode. When set, the proxy strips the sandbox client's `Authorization` header and re-signs with real provider credentials. Values: `sigv4` (auto-detect payload mode from client headers), `sigv4:body` (buffer and hash body, max 10 MiB), `sigv4:no_body` (unsigned payload, stream body). Mutually exclusive with `request_body_credential_rewrite`. See [AWS SigV4](/providers/aws-sigv4). | | `signing_service` | string | No | AWS service name for SigV4 signing (e.g. `bedrock`, `s3`, `sts`). Required when `credential_signing` is set. | | `signing_region` | string | No | AWS region override for SigV4 signing (e.g. `us-east-1`). When omitted, the region is extracted from the endpoint hostname. Required for non-standard AWS endpoints where the region cannot be inferred. | @@ -472,7 +474,40 @@ Identifies an executable that is permitted to use the associated endpoints. |---|---|---|---| | `path` | string | Yes | Filesystem path to the executable. Supports glob patterns with `*` and `**`. For example, `/sandbox/.vscode-server/**` matches any executable under that directory tree. | -### Full Example +## Network Middleware + +**Category:** Dynamic + +A map of up to 10 middleware configs selected after network and L7 policy admit an HTTP request. Each map key is the stable policy-local config identity. Middleware selection is independent of the network policy entry that admitted the request. Every matching config runs once by ascending `order` before provider credential injection. Order values must be unique across the policy, and runtime selection also enforces the 10-stage maximum. + +```yaml showLineNumbers={false} +network_middlewares: + regex-redactor: + name: Redact API tokens + middleware: openshell/regex + order: 10 + config: + mode: redact + on_error: fail_closed + endpoints: + include: ["*.example.com"] + exclude: ["trusted.example.com"] +``` + +| Field | Type | Required | Description | +|---|---|---|---| +| `name` | string | No | Human-readable name for the middleware config. Defaults to the map key, which remains its stable identity. | +| `middleware` | string | Yes | Built-in middleware name or operator-owned registration name. `openshell/` is reserved for built-ins. | +| `order` | integer | No | Execution priority. Lower values run first, and values must be unique across the policy. Defaults to `0`; therefore, policies with multiple configs normally specify it explicitly. | +| `config` | object | No | Implementation-owned configuration validated by the selected middleware. | +| `on_error` | string | No | `fail_closed` denies the request when the stage fails; `fail_open` skips the failed stage. Defaults to `fail_closed`. | +| `endpoints` | object | Yes | Host selector with required non-empty `include` and optional `exclude` lists, limited to 32 combined patterns. Exclusions take precedence. | + +Host selectors use the same case-insensitive exact and DNS glob semantics as network endpoints: `*` matches exactly one DNS label and `**` matches one or more labels, so `**.example.com` covers subdomains but not `example.com` itself. Brace alternates are rejected at validation. Middleware runs only on HTTP requests the supervisor parses. A fail-closed selector that can cover a `tls: skip` endpoint is rejected because OpenShell cannot inspect that traffic. An all-`fail_open` match may cover the endpoint; the supervisor bypasses the middleware and emits a detection finding. + +See [Supervisor Middleware](/extensibility/supervisor-middleware) for registration, failure behavior, body limits, and operational guidance. + +## Full Example The following policy grants read-only GitHub API access and npm registry access: diff --git a/docs/sandboxes/policies.mdx b/docs/sandboxes/policies.mdx index 212ba76fce..990f260cea 100644 --- a/docs/sandboxes/policies.mdx +++ b/docs/sandboxes/policies.mdx @@ -12,7 +12,7 @@ Use this page to apply and iterate policy changes on running sandboxes. For a fu ## Policy Structure -A policy has static sections `filesystem_policy`, `landlock`, and `process` that are locked at sandbox creation, and a dynamic section `network_policies` that is hot-reloadable on a running sandbox. +A policy has static sections `filesystem_policy`, `landlock`, and `process` that are locked at sandbox creation, and dynamic `network_policies` and `network_middlewares` sections that are hot-reloadable on a running sandbox. ```yaml wordWrap showLineNumbers={false} version: 1 @@ -44,6 +44,19 @@ network_policies: binaries: - path: /usr/bin/curl +# Dynamic: ordered middleware selected independently by admitted host. +network_middlewares: + regex-redactor: + name: Redact API tokens + middleware: openshell/regex + order: 10 + config: + mode: redact + on_error: fail_closed + endpoints: + include: ["api.example.com"] + exclude: [] + ``` Static sections are locked at sandbox creation. Changing them requires destroying and recreating the sandbox. @@ -57,6 +70,33 @@ Raw streams are connection-scoped and outside L7 live-reload guarantees. This in | `landlock` | Static | Configures Landlock LSM enforcement behavior. Set `compatibility` to `best_effort` (skip individual inaccessible paths while applying remaining rules) or `hard_requirement` (fail if any path is inaccessible or the required kernel ABI is unavailable). Refer to the [Policy Schema Reference](/reference/policy-schema#landlock) for the full behavior table. | | `process` | Static | Sets the OS-level identity for the agent process. `run_as_user` and `run_as_group` default to `sandbox`. Root (`root` or `0`) is rejected. The agent also runs with seccomp filters that block dangerous system calls. | | `network_policies` | Dynamic | Controls network access for ordinary outbound traffic from the sandbox. Each block has a name, a list of endpoints (host, port, protocol, and optional rules), and a list of binaries allowed to use those endpoints.
Every outbound connection except `https://inference.local` goes through the proxy, which queries the [policy engine](/about/how-it-works#core-components) with the destination and calling binary. A connection is allowed only when both match an entry in the same policy block.
For endpoints with `protocol: rest`, the proxy auto-detects TLS and terminates it so each HTTP request can be checked against that endpoint's `rules` (method and path). For endpoints with `protocol: websocket`, the proxy validates the RFC 6455 upgrade and evaluates `GET` rules for the handshake plus either `WEBSOCKET_TEXT` rules for raw client text messages or GraphQL operation rules for GraphQL-over-WebSocket messages. Set `websocket_credential_rewrite: true` only when a WebSocket or REST compatibility endpoint must keep placeholder credentials in sandbox-owned text frames and resolve them at the OpenShell relay boundary.
Endpoints without `protocol` allow the TCP stream through without inspecting payloads.
If no endpoint matches, the connection is denied. Configure managed inference separately through [Inference Routing](/sandboxes/inference-routing). | +| `network_middlewares` | Dynamic | Declares keyed HTTP request middleware configs. After network and L7 policy admit a request, OpenShell matches each config's host selectors independently and runs matching entries by their unique ascending `order` before credential injection. | + +## Supervisor Middleware + +Supervisor middleware can inspect, deny, or replace admitted HTTP request bodies before provider credentials are injected. Middleware selection is independent of the `network_policies` rule that admitted the request: each keyed `network_middlewares` entry matches the destination host through `endpoints.include` and `endpoints.exclude`. + +```yaml +network_middlewares: + regex-redactor: + name: Redact API tokens + middleware: openshell/regex + order: 10 + config: + mode: redact + on_error: fail_closed + endpoints: + include: ["*.example.com"] + exclude: ["trusted.example.com"] +``` + +Matching entries run once each by ascending `order`; lower values run first, and duplicate order values are rejected. The default order is `0`, so policies with multiple entries normally set it explicitly. Map keys are structurally unique. An optional `name` provides a human-readable label, defaults to the map key, and does not change the key used as the config identity. Different keys may use the same implementation and run as distinct stages. `exclude` takes precedence over `include`. + +`openshell/regex` is an example built into the supervisor. It applies fixed regular expressions as a best-effort UTF-8 text transformation, without guarantees that sensitive values will be detected or fully removed. Custom expressions are not configurable yet. Operator-run middleware must be registered by name before a policy can reference it. The gateway validates implementation-owned config before accepting the policy. + +`on_error` defaults to `fail_closed`. Use `fail_open` only when skipping a failed middleware is acceptable. Middleware applies only to HTTP traffic the supervisor can parse and inspect. Policy validation rejects a fail-closed selector that can cover a `tls: skip` endpoint. An all-`fail_open` match may cover the endpoint; the supervisor bypasses the middleware and emits a detection finding. + +See [Supervisor Middleware](/extensibility/supervisor-middleware) for registration, chain ordering, body limits, failure behavior, and operations. ## Baseline Filesystem Paths @@ -247,7 +287,7 @@ If you set `protocol: rest` or `protocol: websocket`, you also need an allow sha Use the `websocket-credential-rewrite` endpoint option with `protocol: websocket` when the sandbox should send credential placeholders in client text frames and have OpenShell resolve them after the allowed upgrade. The option can also be used with `protocol: rest` compatibility endpoints that perform a WebSocket upgrade. It is rejected for plain L4 or `protocol: sql` endpoints. -Use the `request-body-credential-rewrite` endpoint option with `protocol: rest` when an API expects OpenShell-managed credentials in UTF-8 JSON, form, or text request bodies. OpenShell buffers up to 256 KiB, rewrites recognized credential placeholders, updates `Content-Length`, and rejects unresolved placeholders instead of forwarding them. The option is rejected for WebSocket, GraphQL, SQL, and plain L4 endpoints. +Use the `request-body-credential-rewrite` endpoint option with `protocol: rest` when an API expects OpenShell-managed credentials in UTF-8 JSON, form, or text request bodies. OpenShell buffers up to 256 KiB, rewrites recognized credential placeholders, updates `Content-Length`, and rejects unresolved placeholders instead of forwarding them. For chunked requests, the 256 KiB limit counts the complete wire representation, including framing, extensions, and trailers. The option is rejected for WebSocket, GraphQL, SQL, and plain L4 endpoints. Credential rewrite recognizes the canonical `openshell:resolve:env:KEY` placeholder form and whole-token provider-shaped aliases such as `provider-OPENSHELL-RESOLVE-ENV-API_TOKEN` when the referenced environment key exists in the configured provider credentials. diff --git a/proto/sandbox.proto b/proto/sandbox.proto index 8a5a593334..9e32b2d306 100644 --- a/proto/sandbox.proto +++ b/proto/sandbox.proto @@ -5,6 +5,8 @@ syntax = "proto3"; package openshell.sandbox.v1; +import "google/protobuf/struct.proto"; + // Sandbox-supervisor configuration and policy messages. // // Conventions: @@ -25,6 +27,10 @@ message SandboxPolicy { ProcessPolicy process = 4; // Network access policies keyed by name (e.g. "claude_code", "gitlab"). map network_policies = 5; + // Reusable supervisor middleware configs for network egress, keyed by their + // policy-local names. At most 10 configs are accepted, and at most 10 stages + // can be selected per request. + map network_middlewares = 6; } // Filesystem access policy. @@ -61,6 +67,32 @@ message NetworkPolicyRule { repeated NetworkBinary binaries = 3; } +// A reusable middleware config selected for admitted egress by host. +message NetworkMiddlewareConfig { + // Human-readable name for this middleware config. + string name = 1; + // Built-in middleware name or operator-owned registration name. + string middleware = 2; + // Service-specific configuration. + google.protobuf.Struct config = 3; + // Failure behavior: "fail_closed" (default) or "fail_open". + string on_error = 4; + // Host selector controlling which admitted destinations use this config. + MiddlewareEndpointSelector endpoints = 5; + // Execution order. Values must be unique within a policy; lower values run first. + int32 order = 6; +} + +// Host selector controlling which admitted destinations use a middleware config. +message MiddlewareEndpointSelector { + // Exact host or DNS glob patterns included in the selection. Include and + // exclude accept at most 32 combined patterns. + repeated string include = 1; + // Exact host or DNS glob patterns removed from the selection. + // Exclusions take precedence over inclusions. + repeated string exclude = 2; +} + // A network endpoint (host + port) with optional L7 inspection config. message NetworkEndpoint { // Hostname or host glob pattern. Exact match is case-insensitive. @@ -329,4 +361,22 @@ message GetSandboxConfigResponse { // Fingerprint for provider credential inputs attached to this sandbox. // Changes when attached provider names or attached provider records change. uint64 provider_env_revision = 8; + // Operator-registered supervisor middleware services required by the + // effective policy. Built-in middleware is not included. + repeated SupervisorMiddlewareService supervisor_middleware_services = 9; +} + +// Connection details for one operator-registered supervisor middleware service. +// V1 supports plaintext and server-authenticated TLS gRPC. +message SupervisorMiddlewareService { + // Operator-owned registration name used by policy attachments and diagnostics. + string name = 1; + // gRPC endpoint reachable from the sandbox supervisor. + string grpc_endpoint = 2; + // Operator-owned body limit applied to every binding exposed by the service. + uint64 max_body_bytes = 3; + // Default RPC timeout for this service. Empty uses the platform default of + // 500ms. Values use an integer with an `ms` or `s` suffix and must be + // between 10ms and 30s. + string timeout = 4; } diff --git a/proto/supervisor_middleware.proto b/proto/supervisor_middleware.proto new file mode 100644 index 0000000000..dbde411c9f --- /dev/null +++ b/proto/supervisor_middleware.proto @@ -0,0 +1,242 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +syntax = "proto3"; + +package openshell.middleware.v1; + +import "google/protobuf/empty.proto"; +import "google/protobuf/struct.proto"; + +// SupervisorMiddleware lets an operator-run service inspect and transform +// sandbox HTTP egress before OpenShell injects credentials. +service SupervisorMiddleware { + // Describe returns the service manifest and declared bindings. + rpc Describe(google.protobuf.Empty) returns (MiddlewareManifest); + + // ValidateConfig checks service-specific configuration for one binding. + rpc ValidateConfig(ValidateConfigRequest) returns (ValidateConfigResponse); + + // EvaluateHttpRequest returns an allow, deny, or mutation decision for one + // buffered HTTP request. + rpc EvaluateHttpRequest(HttpRequestEvaluation) returns (HttpRequestResult); +} + +// MiddlewareManifest describes one middleware service and the bindings it +// exposes. The service is the operator-run gRPC server implementing +// SupervisorMiddleware. +message MiddlewareManifest { + // Human-readable middleware service name used only for diagnostics. This is + // not required to match an operator-owned registration name. + string name = 1; + // Release version of the middleware service implementation, used for + // diagnostics. + string service_version = 2; + // Bindings exposed by this middleware service. + repeated MiddlewareBinding bindings = 3; +} + +// MiddlewareBinding declares one operation and phase supported by a service. +message MiddlewareBinding { + // Supported operation. V1 supports HTTP_REQUEST. + SupervisorMiddlewareOperation operation = 1; + // Supported evaluation phase. V1 supports PRE_CREDENTIALS. + SupervisorMiddlewarePhase phase = 2; + // Maximum request or replacement body this binding can process. + uint64 max_body_bytes = 3; + // Optional binding-specific RPC timeout. Empty uses the operator-configured + // service timeout, or the 500ms platform default when that is also omitted. + // A non-empty value may shorten but cannot extend the operator timeout. + // Values use an integer with an `ms` or `s` suffix and must be between + // 10ms and 30s. + string timeout = 4; +} + +// ValidateConfigRequest contains one policy configuration to validate. +message ValidateConfigRequest { + // Service-specific policy configuration. + google.protobuf.Struct config = 1; + // Built-in middleware name or operator-owned registration name. + string middleware_name = 2; +} + +// ValidateConfigResponse reports whether a policy configuration is accepted. +message ValidateConfigResponse { + // True when the service accepts the configuration. + bool valid = 1; + // Human-readable validation failure reason. Empty when valid is true. + string reason = 2; +} + +// HttpRequestEvaluation contains one buffered HTTP request to evaluate. +message HttpRequestEvaluation { + // Evaluation phase selected for this request. + SupervisorMiddlewarePhase phase = 1; + // Sandbox and request identity available to the supervisor. + // The encoded context is limited to 4 KiB. + RequestContext context = 2; + // Validated service-specific policy configuration. + // The encoded configuration is limited to 64 KiB. + google.protobuf.Struct config = 3; + // Destination and HTTP request target. + // The encoded target is limited to 32 KiB. + HttpRequestTarget target = 4; + // HTTP request headers before OpenShell injects credentials, in wire + // order. Repeated header names are preserved as separate entries. Protected + // credential, routing, framing, and hop-by-hop headers are omitted. + // At most 128 lines and 64 KiB of encoded headers are included. + repeated HttpHeader headers = 5; + // Buffered request body, limited to 4 MiB. Empty for a bodyless request. + bytes body = 6; + // Built-in middleware name or operator-owned registration name. + string middleware_name = 7; +} + +// HttpHeader is one request header line. +message HttpHeader { + // Lowercased header name. + string name = 1; + // Header value with surrounding whitespace trimmed. + string value = 2; +} + +// Supervisor operation selected for middleware evaluation. +enum SupervisorMiddlewareOperation { + SUPERVISOR_MIDDLEWARE_OPERATION_UNSPECIFIED = 0; + SUPERVISOR_MIDDLEWARE_OPERATION_HTTP_REQUEST = 1; +} + +// Ordered phase within a supervisor operation. +enum SupervisorMiddlewarePhase { + SUPERVISOR_MIDDLEWARE_PHASE_UNSPECIFIED = 0; + SUPERVISOR_MIDDLEWARE_PHASE_PRE_CREDENTIALS = 1; +} + +// RequestContext identifies the sandbox request being evaluated. +message RequestContext { + // Request id used to correlate middleware and supervisor logs. + string request_id = 1; + // Sandbox id that originated the request. + string sandbox_id = 2; + // Workload process that originated the request, when available. + Process originating_process = 3; +} + +// HttpRequestTarget describes the admitted HTTP destination and request target. +message HttpRequestTarget { + // Request scheme, such as "http" or "https". + string scheme = 1; + // Destination hostname selected by network policy. + string host = 2; + // Destination TCP port. + uint32 port = 3; + // HTTP request method. + string method = 4; + // Request path without the query string. + string path = 5; + // Raw request query string without the leading question mark. + string query = 6; +} + +// Process identifies a workload process and its executable ancestry. +message Process { + // Executable path for the originating process. + string binary = 1; + // Process id within the sandbox. + uint32 pid = 2; + // Executable paths for ancestor processes, nearest parent first. + repeated string ancestors = 3; +} + +// Decision controls whether OpenShell continues processing the request. +enum Decision { + // Invalid response value handled according to the policy failure mode. + DECISION_UNSPECIFIED = 0; + // Continue processing the request and apply any returned mutations. + DECISION_ALLOW = 1; + // Deny the request before credentials are injected or data is sent upstream. + DECISION_DENY = 2; +} + +// Finding is an audit-safe observation produced during evaluation. +message Finding { + // Stable, service-defined finding type. + string type = 1; + // Human-readable finding label that does not contain request content. + string label = 2; + // Number of matching observations represented by this finding. + uint32 count = 3; + // Service-defined confidence level. + string confidence = 4; + // Service-defined severity level. + string severity = 5; +} + +// ExistingHeaderAction controls how a header write behaves when the +// case-insensitive header name is already present. Every action writes the +// value when the header is absent. +enum ExistingHeaderAction { + EXISTING_HEADER_ACTION_UNSPECIFIED = 0; + // Add another field value without changing existing values. + EXISTING_HEADER_ACTION_APPEND = 1; + // Remove every existing value, then add the new value. + EXISTING_HEADER_ACTION_OVERWRITE = 2; + // Leave the existing values unchanged. + EXISTING_HEADER_ACTION_SKIP = 3; +} + +// WriteHeader proposes one header value and defines collision behavior. +message WriteHeader { + string name = 1; + string value = 2; + ExistingHeaderAction on_existing = 3; +} + +// RemoveHeader removes every value for a case-insensitive header name. +message RemoveHeader { + string name = 1; +} + +// HeaderMutation is one ordered request-header operation. +message HeaderMutation { + oneof operation { + WriteHeader write = 1; + RemoveHeader remove = 2; + } +} + +// HttpRequestResult contains the decision and optional request mutations. +message HttpRequestResult { + // Allow or deny decision for this request. + Decision decision = 1; + // Free-form service diagnostic. OpenShell does not relay this text into + // denied responses or security logs. Limited to 4 KiB before discarding. + string reason = 2; + // Replacement request body when has_body is true. Limited to 4 MiB. + bytes body = 3; + // True when body should replace the request body, including with an empty body. + bool has_body = 4; + // Ordered request-header mutations applied before the next middleware and + // before forwarding. Header writes are restricted to the + // "x-openshell-middleware-" namespace. Removes may target other visible + // request headers, but credential, routing, framing, and hop-by-hop headers + // are always protected. A violating result is a middleware failure handled + // according to the policy failure mode. At most 64 operations, 32 KiB of + // validated name/value data, and 64 KiB encoded are accepted. + repeated HeaderMutation header_mutations = 5; + // Audit-safe findings produced during evaluation. For operator-run services, + // OpenShell logs platform-owned fields derived from the operator-owned + // registration name rather than service-provided type, label, confidence, + // or metadata text. + // At most 32 findings of at most 4 KiB encoded each are accepted per stage. + // A policy selects at most 10 stages, so one chain retains at most 320. + repeated Finding findings = 6; + // Non-secret service-defined metadata included in diagnostics. At most 64 + // entries and 32 KiB of combined key/value data are accepted. + map metadata = 7; + // Optional stable machine-readable code for a deny decision. Codes must + // start with a lowercase ASCII letter and contain only lowercase ASCII + // letters, digits, and underscores, with a maximum length of 64 bytes. + // OpenShell may return this code to the requester, unlike free-form reason. + string reason_code = 8; +}