From c230a0e6464f8e5e0733ad5c409a78bdc29bb34d Mon Sep 17 00:00:00 2001 From: Mrunal Patel Date: Wed, 2 Dec 2026 16:28:45 +0000 Subject: [PATCH 1/6] feat(policy): add per-endpoint credential binding placement Let a sandbox policy endpoint's credential_binding set its own request placement, so one stored provider credential can be presented as a Bearer token at one endpoint and as a raw named header at another. Each endpoint accepts the credential only at its own placement; endpoints without one keep the provider profile placement. - Add NetworkCredentialPlacement to NetworkCredentialBinding and carry it on StaticCredentialEndpointBinding to the supervisor. - Select the placement per request from the matching endpoint bindings and resolve nothing when matching bindings disagree. - Validate placements strictly and reject overlapping bindings of one provider with different placements, or placement with credential_signing. - Include placement in the provider environment revision and stable workload handle without changing values for existing bindings. - Gate delivery on a new supervisor policy capability and a polling request flag; withhold affected credentials from older supervisors. Closes #5963 Signed-off-by: Mrunal Patel --- .../openshell-core/src/extension_protocol.rs | 12 + crates/openshell-core/src/grpc_client.rs | 2 + .../src/provider_credentials.rs | 407 ++++++++++++++++-- crates/openshell-core/src/secrets_body.rs | 1 + crates/openshell-policy-schema/src/lib.rs | 37 +- crates/openshell-policy/src/ambiguity.rs | 92 +++- crates/openshell-policy/src/lib.rs | 142 +++++- crates/openshell-providers/src/profiles.rs | 1 + crates/openshell-server/src/grpc/policy.rs | 289 ++++++++++++- .../grpc/policy/token_grant_owners_tests.rs | 15 +- crates/openshell-server/src/grpc/provider.rs | 38 +- crates/openshell-server/src/grpc/sandbox.rs | 1 + crates/openshell-server/src/storage_proto.rs | 12 +- .../src/google_cloud_metadata.rs | 1 + .../src/l7/relay.rs | 7 + .../src/l7/rest.rs | 2 + .../src/l7/websocket.rs | 2 + .../openshell-supervisor-network/src/proxy.rs | 8 + .../src/proxy/relay.rs | 1 + .../src/config_runtime.rs | 1 + crates/openshell-supervisor/src/lib.rs | 7 +- crates/openshell-supervisor/src/main.rs | 7 +- docs/how-it-works/policies/schema.mdx | 1 + docs/how-it-works/providers/profiles.mdx | 38 ++ .../kubernetes_shared_supervisor_spiffe.rs | 1 + proto/openshell.proto | 8 + proto/sandbox.proto | 18 + skills/generate-sandbox-policy/SKILL.md | 5 + tests/testkit/testkit/src/policy.rs | 1 + 29 files changed, 1074 insertions(+), 83 deletions(-) diff --git a/crates/openshell-core/src/extension_protocol.rs b/crates/openshell-core/src/extension_protocol.rs index 1d6d57960b..b7cd0259da 100644 --- a/crates/openshell-core/src/extension_protocol.rs +++ b/crates/openshell-core/src/extension_protocol.rs @@ -15,6 +15,18 @@ pub const PROTOCOL_MINOR: u32 = 0; /// Policy format implemented by a peer's registered Cedar backend. pub const POLICY_CEDAR_V1: &str = "openshell.policy.cedar.v1"; +/// Peer enforces `credential_binding.placement` on policy endpoints. +pub const POLICY_CREDENTIAL_BINDING_PLACEMENT_V1: &str = + "openshell.policy.credential-binding-placement.v1"; + +/// Versioned policy capabilities a supervisor reports in its hello. +#[must_use] +pub fn supervisor_policy_capabilities(cedar: bool) -> Vec { + let mut capabilities = vec![POLICY_CREDENTIAL_BINDING_PLACEMENT_V1.to_string()]; + capabilities.extend(capabilities_if(POLICY_CEDAR_V1, cedar)); + capabilities +} + /// Whether a peer advertises the required versioned capability. #[must_use] pub fn has_capability(capabilities: &[String], required: &str) -> bool { diff --git a/crates/openshell-core/src/grpc_client.rs b/crates/openshell-core/src/grpc_client.rs index 2429f255cc..4839ff4dd2 100644 --- a/crates/openshell-core/src/grpc_client.rs +++ b/crates/openshell-core/src/grpc_client.rs @@ -1487,6 +1487,7 @@ pub async fn fetch_provider_environment_with_stable_placeholders( sandbox_id: sandbox_id.to_string(), supports_static_credential_bindings: true, supports_stable_placeholder_environment_keys: true, + supports_static_credential_endpoint_placements: true, }) .await .map_err(grpc_status_error)?; @@ -1553,6 +1554,7 @@ mod provider_environment_tests { host: "api.example.com".to_string(), port: 443, path: "/v1/**".to_string(), + placement: None, }], credential_identity: "provider:TOKEN".to_string(), ..Default::default() diff --git a/crates/openshell-core/src/provider_credentials.rs b/crates/openshell-core/src/provider_credentials.rs index 9f81a00590..e82affae25 100644 --- a/crates/openshell-core/src/provider_credentials.rs +++ b/crates/openshell-core/src/provider_credentials.rs @@ -232,6 +232,8 @@ struct CompiledStaticCredentialEndpointBinding { host: HostPattern, port: u16, path: EndpointPathPattern, + /// Replaces the credential's profile placement at this endpoint. + placement: Option, } #[derive(Debug, Clone)] @@ -706,16 +708,21 @@ impl ProviderCredentialState { // safely, so expose no endpoint-scoped resolver. return (None, None, revision); }; - let allowed: HashSet = inner - .static_credential_bindings - .iter() - .filter(|(_, binding)| { - binding.endpoints.iter().any(|endpoint| { - static_credential_endpoint_matches(endpoint, &host_labels, port, &request_path) - }) - }) - .map(|(key, _)| key.clone()) - .collect(); + let mut allowed = HashSet::new(); + let mut placements = HashMap::new(); + for (key, binding) in &inner.static_credential_bindings { + match endpoint_placement(binding, &host_labels, port, &request_path) { + EndpointPlacement::Authorized(placement) => { + allowed.insert(key.clone()); + placements.insert(key.clone(), placement.clone()); + } + // Bindings that disagree on placement for one request select + // no location, so the credential is not resolved. + EndpointPlacement::Conflicting | EndpointPlacement::Unbound => { + placements.insert(key.clone(), binding.placement.clone()); + } + } + } let classifier = inner.body_inventory_available.then(|| { Arc::new(crate::secrets::body::BodyCredentialClassifier::new( inner.combined_resolver.as_deref(), @@ -754,13 +761,7 @@ impl ProviderCredentialState { let scoped = resolver .as_ref() .clone() - .with_placements( - inner - .static_credential_bindings - .iter() - .map(|(key, binding)| (key.clone(), binding.placement.clone())) - .collect(), - ) + .with_placements(placements) .scoped_to_env_keys( &inner.known_static_credential_keys, &allowed, @@ -1456,51 +1457,114 @@ fn compile_static_credential_bindings( fn compile_credential_placement( metadata: &crate::proto::ProviderProfileCredential, ) -> Result { - let style = metadata.auth_style.trim().to_ascii_lowercase(); // Authored profiles may retain fields for other auth styles. Only the // selected style grants a location; unused fields grant no authority. + placement_from_fields( + &metadata.auth_style, + &metadata.header_name, + &metadata.query_param, + &metadata.path_template, + ) + .ok_or_else(|| { + binding_error("static credential placement metadata has an invalid request location") + }) +} + +/// Compile the request location an endpoint credential binding authorizes. +/// +/// Unlike provider profile metadata, a binding placement must not carry +/// fields that its `auth_style` does not use, so an authored binding cannot +/// appear to authorize a location that it does not. +/// +/// # Errors +/// +/// Returns a diagnostic naming the invalid field. +pub fn endpoint_credential_placement( + placement: &crate::proto::NetworkCredentialPlacement, +) -> Result { + let style = placement.auth_style.trim().to_ascii_lowercase(); + let (required, diagnostic) = match style.as_str() { + "basic" => (None, ""), + "bearer" | "header" => ( + Some("header_name"), + "header_name must be a non-empty HTTP header name", + ), + "query" => ( + Some("query_param"), + "query_param must be non-empty and must not contain control characters or &=#?", + ), + "path" | "path_subtree" => ( + Some("path_template"), + "path_template must start with '/', contain {credential} exactly once, and must not contain control characters, '?' or '#'", + ), + "" => return Err("auth_style is required".to_string()), + _ => { + return Err(format!( + "unsupported auth_style '{}'; use basic, bearer, header, query, path, or path_subtree", + placement.auth_style + )); + } + }; + for (field, value) in [ + ("header_name", &placement.header_name), + ("query_param", &placement.query_param), + ("path_template", &placement.path_template), + ] { + if required != Some(field) && !value.is_empty() { + return Err(format!("{field} is not used by auth_style {style}")); + } + } + placement_from_fields( + &placement.auth_style, + &placement.header_name, + &placement.query_param, + &placement.path_template, + ) + .ok_or_else(|| diagnostic.to_string()) +} + +fn placement_from_fields( + auth_style: &str, + header_name: &str, + query_param: &str, + path_template: &str, +) -> Option { + let style = auth_style.trim().to_ascii_lowercase(); let placement = match style.as_str() { "basic" => CredentialPlacement::Header("authorization".into()), "header" | "bearer" - if !metadata.header_name.trim().is_empty() - && metadata - .header_name + if !header_name.trim().is_empty() + && header_name .trim() .bytes() .all(|b| b.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&b)) => { - CredentialPlacement::Header(metadata.header_name.trim().to_ascii_lowercase()) + CredentialPlacement::Header(header_name.trim().to_ascii_lowercase()) } "query" - if !metadata.query_param.trim().is_empty() - && !metadata - .query_param + if !query_param.trim().is_empty() + && !query_param .chars() .any(|c| c.is_control() || "&=#?".contains(c)) => { - CredentialPlacement::QueryParam(metadata.query_param.trim().to_string()) + CredentialPlacement::QueryParam(query_param.trim().to_string()) } "path" | "path_subtree" - if metadata.path_template.starts_with('/') - && metadata.path_template.matches(CREDENTIAL_PATH_SLOT).count() == 1 - && !metadata - .path_template + if path_template.starts_with('/') + && path_template.matches(CREDENTIAL_PATH_SLOT).count() == 1 + && !path_template .chars() .any(|c| c.is_control() || "?#".contains(c)) => { if style == "path_subtree" { - CredentialPlacement::PathSubtree(metadata.path_template.clone()) + CredentialPlacement::PathSubtree(path_template.to_string()) } else { - CredentialPlacement::PathTemplate(metadata.path_template.clone()) + CredentialPlacement::PathTemplate(path_template.to_string()) } } - _ => { - return Err(binding_error( - "static credential placement metadata has an invalid request location", - )); - } + _ => return None, }; - Ok(placement) + Some(placement) } fn compile_static_credential_endpoint( @@ -1508,11 +1572,21 @@ fn compile_static_credential_endpoint( ) -> Result { let host = HostPattern::new(&endpoint.host) .map_err(|_| binding_error("static credential binding contains an invalid endpoint"))?; + let placement = endpoint + .placement + .as_ref() + .map(|placement| { + endpoint_credential_placement(placement).map_err(|_| { + binding_error("static credential binding contains an invalid endpoint placement") + }) + }) + .transpose()?; Ok(CompiledStaticCredentialEndpointBinding { host, port: u16::try_from(endpoint.port) .map_err(|_| binding_error("static credential binding contains an invalid endpoint"))?, path: EndpointPathPattern::new(&endpoint.path), + placement, }) } @@ -1583,6 +1657,35 @@ fn binding_error(message: &str) -> StaticCredentialBindingError { } } +enum EndpointPlacement<'a> { + Authorized(&'a CredentialPlacement), + Conflicting, + Unbound, +} + +/// Select the placement every endpoint of `binding` matching this request +/// authorizes. An endpoint without its own placement uses the profile one. +fn endpoint_placement<'a>( + binding: &'a CompiledStaticCredentialBinding, + host_labels: &[&str], + port: u16, + path: &str, +) -> EndpointPlacement<'a> { + let mut selected = None; + for endpoint in &binding.endpoints { + if !static_credential_endpoint_matches(endpoint, host_labels, port, path) { + continue; + } + let placement = endpoint.placement.as_ref().unwrap_or(&binding.placement); + match selected { + None => selected = Some(placement), + Some(previous) if previous == placement => {} + Some(_) => return EndpointPlacement::Conflicting, + } + } + selected.map_or(EndpointPlacement::Unbound, EndpointPlacement::Authorized) +} + fn static_credential_endpoint_matches( endpoint: &CompiledStaticCredentialEndpointBinding, host_labels: &[&str], @@ -1786,6 +1889,7 @@ mod tests { host: host.to_string(), port, path: path.to_string(), + placement: None, }], credential_identity: "provider-a:API_KEY".to_string(), workload_credential_handle: String::new(), @@ -1886,6 +1990,233 @@ mod tests { } } + fn endpoint( + host: &str, + path: &str, + placement: Option<(&str, &str)>, + ) -> StaticCredentialEndpointBinding { + StaticCredentialEndpointBinding { + host: host.to_string(), + port: 443, + path: path.to_string(), + placement: placement.map(|(auth_style, header_name)| { + crate::proto::NetworkCredentialPlacement { + auth_style: auth_style.to_string(), + header_name: header_name.to_string(), + ..Default::default() + } + }), + } + } + + fn multi_endpoint_state( + endpoints: Vec, + metadata: HashMap, + ) -> ProviderCredentialState { + let mut bound = binding("unused.example.com", 443, "/**"); + bound.endpoints = endpoints; + ProviderCredentialState::from_bound_environment( + 7, + HashMap::from([("API_KEY".into(), "synthetic".into())]), + HashMap::new(), + metadata, + HashMap::from([("API_KEY".into(), bound)]), + vec![], + ) + .unwrap() + } + + #[test] + fn endpoint_placements_bind_one_credential_to_independent_locations() { + let state = multi_endpoint_state( + vec![ + endpoint( + "bearer.example.com", + "/**", + Some(("bearer", "Authorization")), + ), + endpoint("raw.example.com", "/**", Some(("header", "x-api-key"))), + endpoint("profile.example.com", "/**", None), + ], + placement_metadata("query"), + ); + let reference = state.snapshot().child_env["API_KEY"].clone(); + let bearer = format!("Bearer {reference}"); + let at = |host: &str| state.resolver_for_endpoint(host, 443, "/v1").unwrap(); + + assert_eq!( + at("bearer.example.com") + .rewrite_header_value_for_name("Authorization", &bearer) + .unwrap(), + Some("Bearer synthetic".into()) + ); + assert!( + at("bearer.example.com") + .rewrite_header_value_for_name("x-api-key", &reference) + .unwrap_err() + .is_placement_mismatch() + ); + assert_eq!( + at("raw.example.com") + .rewrite_header_value_for_name("X-Api-Key", &reference) + .unwrap(), + Some("synthetic".into()) + ); + assert!( + at("raw.example.com") + .rewrite_header_value_for_name("Authorization", &bearer) + .unwrap_err() + .is_placement_mismatch() + ); + // An endpoint without its own placement keeps the profile placement. + assert!( + at("profile.example.com") + .rewrite_header_value_for_name("Authorization", &bearer) + .unwrap_err() + .is_placement_mismatch() + ); + assert_eq!( + at("profile.example.com") + .with_request_location(crate::secrets::RequestCredentialLocation::QueryParam( + "api_key".into() + )) + .resolve_placeholder(&reference), + Some("synthetic") + ); + // A binding's placement cannot follow the credential to a destination + // that no binding authorizes. + assert!( + at("other.example.com") + .rewrite_header_value_for_name("X-Api-Key", &reference) + .unwrap_err() + .is_endpoint_mismatch() + ); + } + + #[test] + fn endpoint_placement_replacement_rebinds_without_a_second_value() { + let state = multi_endpoint_state( + vec![ + endpoint( + "bearer.example.com", + "/**", + Some(("bearer", "Authorization")), + ), + endpoint("raw.example.com", "/**", Some(("header", "x-api-key"))), + ], + HashMap::new(), + ); + let mut bound = binding("unused.example.com", 443, "/**"); + bound.endpoints = vec![ + endpoint( + "bearer.example.com", + "/**", + Some(("bearer", "Authorization")), + ), + endpoint("raw.example.com", "/**", Some(("header", "x-api-key"))), + ]; + state + .install_bound_environment( + 8, + HashMap::from([("API_KEY".into(), "rotated".into())]), + HashMap::new(), + HashMap::new(), + HashMap::from([("API_KEY".into(), bound)]), + vec![], + ) + .unwrap(); + let reference = state.snapshot().child_env["API_KEY"].clone(); + for (host, header, value) in [ + ( + "bearer.example.com", + "Authorization", + format!("Bearer {reference}"), + ), + ("raw.example.com", "x-api-key", reference.clone()), + ] { + let resolved = state + .resolver_for_endpoint(host, 443, "/") + .unwrap() + .rewrite_header_value_for_name(header, &value) + .unwrap() + .unwrap(); + assert!(resolved.ends_with("rotated"), "{host}"); + } + state + .install_bound_environment( + 9, + HashMap::new(), + HashMap::new(), + HashMap::new(), + HashMap::new(), + vec![], + ) + .unwrap(); + for host in ["bearer.example.com", "raw.example.com"] { + assert!( + state + .resolver_for_endpoint(host, 443, "/") + .is_none_or(|resolver| resolver + .rewrite_header_value_for_name("x-api-key", &reference) + .is_err()) + ); + } + } + + #[test] + fn overlapping_endpoints_with_different_placements_resolve_nothing() { + let state = multi_endpoint_state( + vec![ + endpoint("api.example.com", "/**", Some(("bearer", "Authorization"))), + endpoint( + "api.example.com", + "/admin/**", + Some(("header", "x-api-key")), + ), + ], + HashMap::new(), + ); + let reference = state.snapshot().child_env["API_KEY"].clone(); + let admin = state + .resolver_for_endpoint("api.example.com", 443, "/admin/users") + .unwrap(); + for (header, value) in [ + ("Authorization", format!("Bearer {reference}")), + ("x-api-key", reference.clone()), + ] { + assert!(admin.rewrite_header_value_for_name(header, &value).is_err()); + } + assert_eq!( + state + .resolver_for_endpoint("api.example.com", 443, "/public") + .unwrap() + .rewrite_header_value_for_name("Authorization", &format!("Bearer {reference}")) + .unwrap(), + Some("Bearer synthetic".into()) + ); + } + + #[test] + fn invalid_endpoint_placement_rejects_the_binding() { + for (auth_style, header_name) in [("bearer", ""), ("query", "x-api-key"), ("cookie", "")] { + let mut bound = binding("api.example.com", 443, "/**"); + bound.endpoints[0] = + endpoint("api.example.com", "/**", Some((auth_style, header_name))); + assert!( + ProviderCredentialState::from_bound_environment( + 7, + HashMap::from([("API_KEY".into(), "synthetic".into())]), + HashMap::new(), + HashMap::new(), + HashMap::from([("API_KEY".into(), bound)]), + vec![], + ) + .is_err(), + "{auth_style}/{header_name}" + ); + } + } + #[test] fn explicit_custom_header_overrides_authorization_default() { let mut metadata = placement_metadata("header"); diff --git a/crates/openshell-core/src/secrets_body.rs b/crates/openshell-core/src/secrets_body.rs index c9464f8e50..08cc5d0fb3 100644 --- a/crates/openshell-core/src/secrets_body.rs +++ b/crates/openshell-core/src/secrets_body.rs @@ -358,6 +358,7 @@ mod tests { host: "api.example.com".into(), port: 443, path: "/**".into(), + placement: None, }], }, )]), diff --git a/crates/openshell-policy-schema/src/lib.rs b/crates/openshell-policy-schema/src/lib.rs index 89290be888..9a1f020de7 100644 --- a/crates/openshell-policy-schema/src/lib.rs +++ b/crates/openshell-policy-schema/src/lib.rs @@ -340,6 +340,27 @@ pub struct NetworkEndpoint { #[serde(deny_unknown_fields)] pub struct NetworkCredentialBinding { pub provider: String, + #[serde( + default, + deserialize_with = "deserialize_non_null_optional_field", + skip_serializing_if = "Option::is_none" + )] + pub placement: Option, +} + +/// Request location an endpoint's credential binding authorizes. Field names +/// match provider profile credential placement metadata. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct NetworkCredentialPlacement { + #[serde(default, skip_serializing_if = "String::is_empty")] + pub auth_style: String, + #[serde(default, skip_serializing_if = "String::is_empty")] + pub header_name: String, + #[serde(default, skip_serializing_if = "String::is_empty")] + pub query_param: String, + #[serde(default, skip_serializing_if = "String::is_empty")] + pub path_template: String, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] @@ -616,6 +637,7 @@ pub fn parse_policy_with_limits(source: &str, limits: ParseLimits) -> Result InspectionResult { else { return Ok(()); }; + let binding = endpoint.get("credential_binding"); inspect_named( - endpoint.get("credential_binding"), + binding, &join(path, "credential_binding"), - &["provider"], + &["provider", "placement"], + )?; + inspect_named( + binding.and_then(|binding| binding.get("placement")), + &join(&join(path, "credential_binding"), "placement"), + &["auth_style", "header_name", "query_param", "path_template"], )?; inspect_named( endpoint.get("json_rpc"), @@ -1287,6 +1315,7 @@ mod tests { format!("graphql_persisted_queries: {spelling}"), format!("graphql_persisted_queries: {{op: {spelling}}}"), format!("credential_binding: {spelling}"), + format!("credential_binding: {{provider: p, placement: {spelling}}}"), format!("json_rpc: {spelling}"), format!("mcp: {spelling}"), ] { @@ -1354,6 +1383,10 @@ mod tests { "version: 1\nnetwork_policies: { api: { endpoints: [{ host: example.com, port: 443, credential_binding: { provider: p, future: true } }] } }\n", "network_policies.api.endpoints[0].credential_binding.future", ), + ( + "version: 1\nnetwork_policies: { api: { endpoints: [{ host: example.com, port: 443, credential_binding: { provider: p, placement: { auth_style: header, future: true } } }] } }\n", + "network_policies.api.endpoints[0].credential_binding.placement.future", + ), ( "version: 1\nnetwork_policies: { api: { endpoints: [{ host: example.com, port: 443, json_rpc: { future: true } }] } }\n", "network_policies.api.endpoints[0].json_rpc.future", diff --git a/crates/openshell-policy/src/ambiguity.rs b/crates/openshell-policy/src/ambiguity.rs index efb846a9a1..dacc74e730 100644 --- a/crates/openshell-policy/src/ambiguity.rs +++ b/crates/openshell-policy/src/ambiguity.rs @@ -4,7 +4,8 @@ //! Validation for endpoint selectors whose policy-derived behavior conflicts. use openshell_core::proto::{ - NetworkEndpoint, NetworkEnforcementMode, NetworkTlsMode, SandboxPolicy, + NetworkCredentialPlacement, NetworkEndpoint, NetworkEnforcementMode, NetworkTlsMode, + SandboxPolicy, }; use std::collections::{BTreeSet, HashSet, VecDeque}; use std::fmt; @@ -99,6 +100,22 @@ pub fn find_endpoint_ambiguities(policy: &SandboxPolicy) -> Vec Vec) -> String { + placement.map_or_else( + || "".to_string(), + |placement| { + format!( + "{{auth_style: {}, header_name: {}, query_param: {}, path_template: {}}}", + placement.auth_style.trim().to_ascii_lowercase(), + placement.header_name.trim().to_ascii_lowercase(), + placement.query_param, + placement.path_template, + ) + }, + ) +} + fn endpoint_selector(endpoint: &NetworkEndpoint) -> String { let host = if endpoint.host.is_empty() { "" @@ -945,10 +977,12 @@ mod tests { let mut left = endpoint("api.example.com", 443); left.credential_binding = Some(openshell_core::proto::NetworkCredentialBinding { provider: "provider-a".to_string(), + placement: None, }); let mut right = endpoint("api.example.com", 443); right.credential_binding = Some(openshell_core::proto::NetworkCredentialBinding { provider: "provider-b".to_string(), + placement: None, }); let ambiguities = find_endpoint_ambiguities(&policy_with(left, right)); @@ -961,6 +995,62 @@ mod tests { ); } + #[test] + fn overlapping_credential_bindings_must_agree_on_placement() { + let bound = |host: &str, path: &str, header_name: Option<&str>| { + let mut endpoint = endpoint(host, 443); + endpoint.path = path.to_string(); + endpoint.credential_binding = Some(openshell_core::proto::NetworkCredentialBinding { + provider: "shared-api".to_string(), + placement: header_name.map(|header_name| NetworkCredentialPlacement { + auth_style: "header".to_string(), + header_name: header_name.to_string(), + ..Default::default() + }), + }); + endpoint + }; + + // Different specificity still conflicts: every matching binding + // contributes to a request's credential placement. + for (left, right) in [ + ( + bound("api.example.com", "/**", None), + bound("api.example.com", "/admin/**", Some("x-api-key")), + ), + ( + bound("*.example.com", "", Some("x-token")), + bound("api.example.com", "", Some("x-api-key")), + ), + ] { + let ambiguities = find_endpoint_ambiguities(&policy_with(left, right)); + assert_eq!(ambiguities.len(), 1); + assert!( + ambiguities[0] + .conflicts + .iter() + .any(|field| field.contains("credential_binding.placement")) + ); + } + + for (left, right) in [ + ( + bound("bearer.example.com", "", None), + bound("raw.example.com", "", Some("x-api-key")), + ), + ( + bound("api.example.com", "/v1/**", Some("X-Api-Key")), + bound("api.example.com", "/v1/**", Some("x-api-key")), + ), + ( + bound("api.example.com", "/v1/**", None), + bound("api.example.com", "/v2/**", Some("x-api-key")), + ), + ] { + assert!(find_endpoint_ambiguities(&policy_with(left, right)).is_empty()); + } + } + #[test] fn json_rpc_body_limit_is_compared_only_within_the_same_protocol() { let mut json_rpc = endpoint("api.example.com", 443); diff --git a/crates/openshell-policy/src/lib.rs b/crates/openshell-policy/src/lib.rs index ff6cdd8d5a..d0b36e148a 100644 --- a/crates/openshell-policy/src/lib.rs +++ b/crates/openshell-policy/src/lib.rs @@ -71,9 +71,11 @@ use openshell_policy_schema::{ L7Allow as L7AllowDef, L7DenyRule as L7DenyRuleDef, L7Rule as L7RuleDef, LandlockCompatibility as LandlockCompatibilityDef, LandlockPolicy as LandlockDef, MCP_VERSION_REMEDIATION, McpConfig as McpConfigDef, NetworkBinary as NetworkBinaryDef, - NetworkCredentialBinding as NetworkCredentialBindingDef, NetworkEndpoint as NetworkEndpointDef, - NetworkPolicyRule as NetworkPolicyRuleDef, ParameterMatcher as ParamMatcherDef, - PolicyDocument as PolicyFile, ProcessPolicy as ProcessDef, QueryMatcher as QueryMatcherDef, + NetworkCredentialBinding as NetworkCredentialBindingDef, + NetworkCredentialPlacement as NetworkCredentialPlacementDef, + NetworkEndpoint as NetworkEndpointDef, NetworkPolicyRule as NetworkPolicyRuleDef, + ParameterMatcher as ParamMatcherDef, PolicyDocument as PolicyFile, ProcessPolicy as ProcessDef, + QueryMatcher as QueryMatcherDef, }; fn json_rpc_config_from_proto(max_body_bytes: u32) -> Option { @@ -552,6 +554,14 @@ fn endpoint_def_to_proto(e: NetworkEndpointDef) -> NetworkEndpoint { credential_binding: e.credential_binding.map(|binding| { openshell_core::proto::NetworkCredentialBinding { provider: binding.provider, + placement: binding.placement.map(|placement| { + openshell_core::proto::NetworkCredentialPlacement { + auth_style: placement.auth_style, + header_name: placement.header_name, + query_param: placement.query_param, + path_template: placement.path_template, + } + }), } }), json_rpc_max_body_bytes: json_rpc_max_body_bytes(&e.json_rpc, &e.mcp), @@ -806,6 +816,14 @@ fn endpoint_proto_to_def(e: &NetworkEndpoint) -> Result { credential_binding: e.credential_binding.as_ref().map(|binding| { NetworkCredentialBindingDef { provider: binding.provider.clone(), + placement: binding.placement.as_ref().map(|placement| { + NetworkCredentialPlacementDef { + auth_style: placement.auth_style.clone(), + header_name: placement.header_name.clone(), + query_param: placement.query_param.clone(), + path_template: placement.path_template.clone(), + } + }), } }), json_rpc, @@ -2726,6 +2744,22 @@ pub fn validate_credential_bindings( if invalid_port { violations.push(format!("credential-bound endpoint '{}' for provider '{provider}' must define ports in range 1..=65535", endpoint.host)); } + if let Some(placement) = &binding.placement { + if let Err(error) = + openshell_core::provider_credentials::endpoint_credential_placement(placement) + { + violations.push(format!( + "credential_binding.placement for endpoint '{}': {error}", + endpoint.host + )); + } + if !endpoint.credential_signing.is_empty() { + violations.push(format!( + "credential_binding.placement for endpoint '{}' cannot be combined with credential_signing", + endpoint.host + )); + } + } } } if violations.is_empty() { @@ -6067,6 +6101,108 @@ network_policies: assert!(yaml_out.contains("provider: work-gcp")); } + #[test] + fn round_trip_preserves_credential_binding_placement() { + let yaml = r" +version: 1 +network_policies: + shared_api: + endpoints: + - host: bearer.example.com + port: 443 + protocol: rest + access: full + credential_binding: + provider: shared-api + placement: + auth_style: bearer + header_name: Authorization + - host: raw.example.com + port: 443 + protocol: rest + access: full + credential_binding: + provider: shared-api + placement: + auth_style: header + header_name: x-api-key +"; + + let proto1 = parse_sandbox_policy(yaml).expect("parse failed"); + let endpoints = &proto1.network_policies["shared_api"].endpoints; + let placement = endpoints[1] + .credential_binding + .as_ref() + .and_then(|binding| binding.placement.as_ref()) + .expect("placement"); + assert_eq!(placement.auth_style, "header"); + assert_eq!(placement.header_name, "x-api-key"); + assert!(validate_credential_bindings(&proto1).is_ok()); + + let yaml_out = serialize_sandbox_policy(&proto1).expect("serialize failed"); + let proto2 = parse_sandbox_policy(&yaml_out).expect("re-parse failed"); + assert_eq!(proto1, proto2); + assert!(yaml_out.contains("header_name: x-api-key")); + } + + #[test] + fn credential_binding_placement_is_validated() { + for (placement, signing, expected) in [ + ("{}", "", "auth_style is required"), + ("{auth_style: cookie}", "", "unsupported auth_style"), + ("{auth_style: bearer}", "", "header_name must be"), + ( + "{auth_style: header, header_name: 'x api key'}", + "", + "header_name must be", + ), + ( + "{auth_style: query, header_name: x-api-key, query_param: key}", + "", + "header_name is not used by auth_style query", + ), + ( + "{auth_style: query, query_param: 'a&b'}", + "", + "query_param must be", + ), + ( + "{auth_style: path, path_template: /v1/static}", + "", + "path_template must", + ), + ( + "{auth_style: header, header_name: x-api-key}", + "credential_signing: sigv4, signing_service: s3, signing_region: us-east-1,", + "cannot be combined with credential_signing", + ), + ] { + let yaml = format!( + "version: 1\nnetwork_policies:\n api:\n endpoints:\n - {{host: api.example.com, port: 443, protocol: rest, access: full, {signing} credential_binding: {{provider: p, placement: {placement}}}}}\n" + ); + let policy = parse_sandbox_policy(&yaml).expect("parse failed"); + let violations = validate_credential_bindings(&policy).expect_err(&yaml); + assert!( + violations + .iter() + .any(|violation| violation.contains(expected)), + "{yaml}: {violations:?}" + ); + } + for placement in [ + "{auth_style: basic}", + "{auth_style: Bearer, header_name: Authorization}", + "{auth_style: query, query_param: api_key}", + "{auth_style: path_subtree, path_template: '/bot{credential}'}", + ] { + let yaml = format!( + "version: 1\nnetwork_policies:\n api:\n endpoints:\n - {{host: api.example.com, port: 443, credential_binding: {{provider: p, placement: {placement}}}}}\n" + ); + let policy = parse_sandbox_policy(&yaml).expect("parse failed"); + assert!(validate_credential_bindings(&policy).is_ok(), "{yaml}"); + } + } + #[test] fn round_trip_preserves_multi_port() { let yaml = r" diff --git a/crates/openshell-providers/src/profiles.rs b/crates/openshell-providers/src/profiles.rs index 84e982c372..8fe370256f 100644 --- a/crates/openshell-providers/src/profiles.rs +++ b/crates/openshell-providers/src/profiles.rs @@ -4027,6 +4027,7 @@ credentials: host: endpoint.host.clone(), port: endpoint.port, path: endpoint.path.clone(), + placement: None, }) .collect(), }; diff --git a/crates/openshell-server/src/grpc/policy.rs b/crates/openshell-server/src/grpc/policy.rs index b9d5fa8fff..3950e99424 100644 --- a/crates/openshell-server/src/grpc/policy.rs +++ b/crates/openshell-server/src/grpc/policy.rs @@ -2174,6 +2174,7 @@ fn policy_static_credential_endpoint_bindings( host: endpoint.host.clone(), port, path: endpoint.path.clone(), + placement: binding.placement.clone(), }; if !provider_bindings.contains(&candidate) { provider_bindings.push(candidate); @@ -2183,13 +2184,33 @@ fn policy_static_credential_endpoint_bindings( } for endpoints in bindings.values_mut() { - endpoints.sort_by(|left, right| { - (&left.host, left.port, &left.path).cmp(&(&right.host, right.port, &right.path)) - }); + endpoints.sort_by(compare_static_credential_endpoints); } Ok(bindings) } +fn compare_static_credential_endpoints( + left: &StaticCredentialEndpointBinding, + right: &StaticCredentialEndpointBinding, +) -> std::cmp::Ordering { + let placement = |endpoint: &StaticCredentialEndpointBinding| { + endpoint.placement.as_ref().map(|placement| { + ( + placement.auth_style.clone(), + placement.header_name.clone(), + placement.query_param.clone(), + placement.path_template.clone(), + ) + }) + }; + (&left.host, left.port, &left.path, placement(left)).cmp(&( + &right.host, + right.port, + &right.path, + placement(right), + )) +} + pub(super) fn policy_has_credential_binding_for_provider( policy: &ProtoSandboxPolicy, provider_name: &str, @@ -2919,9 +2940,33 @@ pub fn require_policy_capabilities( { return Err(Status::unimplemented(CEDAR_SUPPORT_REQUIRED)); } + if !openshell_core::extension_protocol::has_capability( + &supported_capabilities, + openshell_core::extension_protocol::POLICY_CREDENTIAL_BINDING_PLACEMENT_V1, + ) && policy.is_some_and(policy_has_credential_binding_placement) + { + return Err(Status::unimplemented( + CREDENTIAL_BINDING_PLACEMENT_SUPPORT_REQUIRED, + )); + } Ok(()) } +const CREDENTIAL_BINDING_PLACEMENT_SUPPORT_REQUIRED: &str = "credential_binding.placement requires a supervisor that enforces endpoint credential placement"; + +fn policy_has_credential_binding_placement(policy: &ProtoSandboxPolicy) -> bool { + policy + .network_policies + .values() + .flat_map(|rule| &rule.endpoints) + .any(|endpoint| { + endpoint + .credential_binding + .as_ref() + .is_some_and(|binding| binding.placement.is_some()) + }) +} + /// Resolve the same effective configuration for authenticated RPCs and trusted /// readiness snapshots. Callers must authorize external access before entering. pub(super) async fn load_sandbox_config( @@ -3526,13 +3571,24 @@ fn hash_policy_credential_bindings( for provider_name in provider_names { hasher.update(provider_name.as_bytes()); let mut endpoints = bindings[provider_name].clone(); - endpoints.sort_by(|left, right| { - (&left.host, left.port, &left.path).cmp(&(&right.host, right.port, &right.path)) - }); + endpoints.sort_by(compare_static_credential_endpoints); for endpoint in endpoints { hasher.update(endpoint.host.as_bytes()); hasher.update(endpoint.port.to_le_bytes()); hasher.update(endpoint.path.as_bytes()); + // Absent placement keeps the established revision input. + if let Some(placement) = &endpoint.placement { + hasher.update(b"placement"); + for field in [ + &placement.auth_style, + &placement.header_name, + &placement.query_param, + &placement.path_template, + ] { + hasher.update(field.len().to_le_bytes()); + hasher.update(field.as_bytes()); + } + } } } } @@ -3896,6 +3952,9 @@ pub(super) async fn handle_get_sandbox_provider_environment( let supports_stable_placeholder_environment_keys = request .get_ref() .supports_stable_placeholder_environment_keys; + let supports_static_credential_endpoint_placements = request + .get_ref() + .supports_static_credential_endpoint_placements; let principal = crate::auth::guard::enforce_sandbox_scope(&request, &sandbox_id)?; drop(request); @@ -3906,11 +3965,57 @@ pub(super) async fn handle_get_sandbox_provider_environment( &sandbox, supports_static_credential_bindings, supports_stable_placeholder_environment_keys, + supports_static_credential_endpoint_placements, ) .await?; Ok(Response::new(environment)) } +/// Remove static credentials whose binding sets an endpoint placement. A +/// supervisor that ignores the placement would apply the profile placement +/// at that endpoint instead, so these credentials are withheld rather than +/// delivered with a weaker binding. +fn withhold_static_credential_endpoint_placements( + sandbox_id: &str, + snapshot: &mut ProviderEnvironmentSnapshot, +) { + use openshell_core::provider_credentials::STATIC_CREDENTIAL_METADATA_PREFIX; + let withheld = snapshot + .values + .iter() + .filter(|value| { + value + .static_credential_binding + .as_ref() + .is_some_and(|binding| { + binding + .endpoints + .iter() + .any(|endpoint| endpoint.placement.is_some()) + }) + }) + .map(|value| value.name.clone()) + .collect::>(); + if withheld.is_empty() { + return; + } + for key in &withheld { + warn!( + sandbox_id = %sandbox_id, + key = %key, + "withholding endpoint-placement credential from incompatible supervisor" + ); + } + snapshot + .values + .retain(|value| !withheld.contains(&value.name)); + snapshot.dynamic_credentials.retain(|key, _| { + key.strip_prefix(STATIC_CREDENTIAL_METADATA_PREFIX) + .is_none_or(|key| !withheld.contains(key)) + }); + snapshot.readiness_reason = ProviderReadinessReason::UnsupportedSupervisor.into(); +} + /// Materialize a privileged provider snapshot after the caller has authorized /// access. Omission reasons remain separate from a legitimately empty snapshot. pub(super) async fn load_sandbox_provider_environment( @@ -3918,16 +4023,19 @@ pub(super) async fn load_sandbox_provider_environment( sandbox: &Sandbox, supports_static_credential_bindings: bool, supports_stable_placeholder_environment_keys: bool, + supports_static_credential_endpoint_placements: bool, ) -> Result { - Ok(provider_environment_response( - build_provider_environment_snapshot( - state, - sandbox, - supports_static_credential_bindings, - supports_stable_placeholder_environment_keys, - ) - .await?, - )) + let mut snapshot = build_provider_environment_snapshot( + state, + sandbox, + supports_static_credential_bindings, + supports_stable_placeholder_environment_keys, + ) + .await?; + if !supports_static_credential_endpoint_placements { + withhold_static_credential_endpoint_placements(sandbox.object_id(), &mut snapshot); + } + Ok(provider_environment_response(snapshot)) } /// Build the complete provider environment for one persisted sandbox. @@ -10880,11 +10988,13 @@ mod tests { host: "API.Bound.Example".to_string(), port: 8443, path: "/v1".to_string(), + placement: None, }, StaticCredentialEndpointBinding { host: "api.bound.example".to_string(), port: 8443, path: "/v2".to_string(), + placement: None, }, ], ), @@ -10894,6 +11004,7 @@ mod tests { host: "profile-bound.example".to_string(), port: 443, path: String::new(), + placement: None, }], ), ( @@ -10902,6 +11013,7 @@ mod tests { host: "unattached.example".to_string(), port: 443, path: String::new(), + placement: None, }], ), ]); @@ -12666,6 +12778,7 @@ mod tests { .endpoints[0] .credential_binding = Some(openshell_core::proto::NetworkCredentialBinding { provider: provider.to_string(), + placement: None, }); policy } @@ -12680,6 +12793,7 @@ mod tests { endpoint.credential_binding = provider.map(|provider| openshell_core::proto::NetworkCredentialBinding { provider: provider.to_string(), + placement: None, }); policy } @@ -12907,6 +13021,7 @@ mod tests { sandbox_id: "sb-snapshot-consistency".to_string(), supports_static_credential_bindings: true, supports_stable_placeholder_environment_keys: true, + supports_static_credential_endpoint_placements: true, })), ) .await @@ -14988,6 +15103,7 @@ mod tests { sandbox_id: "sb-provider-env".to_string(), supports_static_credential_bindings: true, supports_stable_placeholder_environment_keys: true, + supports_static_credential_endpoint_placements: true, })), ) .await @@ -15001,6 +15117,7 @@ mod tests { sandbox_id: "sb-provider-env".to_string(), supports_static_credential_bindings: true, supports_stable_placeholder_environment_keys: true, + supports_static_credential_endpoint_placements: true, })), ) .await @@ -15074,6 +15191,7 @@ mod tests { sandbox_id: "sb-files-and-credentials".to_string(), supports_static_credential_bindings: true, supports_stable_placeholder_environment_keys: false, + supports_static_credential_endpoint_placements: true, })), ) .await @@ -15134,6 +15252,7 @@ mod tests { sandbox_id: "sb-cedar-env".to_string(), supports_static_credential_bindings: true, supports_stable_placeholder_environment_keys: true, + supports_static_credential_endpoint_placements: true, })), ) .await @@ -15182,6 +15301,7 @@ mod tests { sandbox_id: "sb-static-ready".to_string(), supports_static_credential_bindings: true, supports_stable_placeholder_environment_keys: false, + supports_static_credential_endpoint_placements: true, })), ) .await @@ -15241,6 +15361,7 @@ mod tests { sandbox_id: "sb-legacy-provider-env".to_string(), supports_static_credential_bindings: false, supports_stable_placeholder_environment_keys: false, + supports_static_credential_endpoint_placements: false, })), ) .await @@ -15286,6 +15407,7 @@ mod tests { sandbox_id: "sb-unbound-provider-env".to_string(), supports_static_credential_bindings: true, supports_stable_placeholder_environment_keys: true, + supports_static_credential_endpoint_placements: true, })), ) .await @@ -15314,6 +15436,124 @@ mod tests { ); } + #[tokio::test] + async fn provider_environment_delivers_endpoint_placements_to_capable_supervisors() { + use openshell_core::proto::{ + GetSandboxProviderEnvironmentRequest, NetworkCredentialBinding, + NetworkCredentialPlacement, ProviderProfile, ProviderProfileCategory, + }; + + let state = test_server_state().await; + state + .store + .put_message(&StoredProviderProfile { + metadata: Some(openshell_core::proto::datamodel::v1::ObjectMeta { + id: "profile-shared-api".to_string(), + name: "shared-api".to_string(), + workspace: "default".to_string(), + ..Default::default() + }), + profile: Some(ProviderProfile { + id: "shared-api".to_string(), + display_name: "Shared API".to_string(), + category: ProviderProfileCategory::Other as i32, + credentials: vec![openshell_core::proto::ProviderProfileCredential { + name: "api_key".to_string(), + env_vars: vec!["API_KEY".to_string()], + ..Default::default() + }], + endpoints: Vec::new(), + ..Default::default() + }), + }) + .await + .unwrap(); + let mut provider = test_provider("work-api", "shared-api"); + provider.credentials = HashMap::from([("API_KEY".to_string(), "api-secret".to_string())]); + state.store.put_message(&provider).await.unwrap(); + + let placement = |auth_style: &str, header_name: &str| NetworkCredentialPlacement { + auth_style: auth_style.to_string(), + header_name: header_name.to_string(), + ..Default::default() + }; + let mut policy = test_policy_with_rule("shared_api", "bearer.example.com"); + let rule = policy.network_policies.get_mut("shared_api").unwrap(); + rule.endpoints[0].protocol = "rest".to_string(); + rule.endpoints[0].access = openshell_core::proto::NetworkAccessPreset::Full as i32; + let mut raw = rule.endpoints[0].clone(); + raw.host = "raw.example.com".to_string(); + rule.endpoints[0].credential_binding = Some(NetworkCredentialBinding { + provider: "work-api".to_string(), + placement: Some(placement("bearer", "Authorization")), + }); + raw.credential_binding = Some(NetworkCredentialBinding { + provider: "work-api".to_string(), + placement: Some(placement("header", "x-api-key")), + }); + rule.endpoints.push(raw); + openshell_policy::ensure_sandbox_process_identity(&mut policy); + + assert!(require_policy_capabilities(Vec::new(), Some(&policy)).is_err()); + assert!( + require_policy_capabilities( + openshell_core::extension_protocol::supervisor_policy_capabilities(false), + Some(&policy), + ) + .is_ok() + ); + + state + .store + .put_message(&test_sandbox( + "sb-endpoint-placement", + "endpoint-placement", + policy, + vec!["work-api".to_string()], + )) + .await + .unwrap(); + let fetch = |supports_placements| { + handle_get_sandbox_provider_environment( + &state, + with_user(Request::new(GetSandboxProviderEnvironmentRequest { + sandbox_id: "sb-endpoint-placement".to_string(), + supports_static_credential_bindings: true, + supports_stable_placeholder_environment_keys: true, + supports_static_credential_endpoint_placements: supports_placements, + })), + ) + }; + + let environment = fetch(true).await.unwrap().into_inner(); + assert_eq!( + environment.environment.get("API_KEY"), + Some(&"api-secret".to_string()) + ); + let endpoints = &environment.static_credential_bindings["API_KEY"].endpoints; + assert_eq!( + endpoints + .iter() + .map(|endpoint| (endpoint.host.as_str(), endpoint.placement.clone())) + .collect::>(), + vec![ + ( + "bearer.example.com", + Some(placement("bearer", "Authorization")) + ), + ("raw.example.com", Some(placement("header", "x-api-key"))), + ] + ); + + let legacy = fetch(false).await.unwrap().into_inner(); + assert!(!legacy.environment.contains_key("API_KEY")); + assert!(!legacy.static_credential_bindings.contains_key("API_KEY")); + assert_eq!( + legacy.readiness_reason, + ProviderReadinessReason::UnsupportedSupervisor as i32 + ); + } + #[tokio::test] async fn provider_environment_uses_policy_binding_and_negotiates_stable_placeholders() { use openshell_core::proto::{ @@ -15360,6 +15600,7 @@ mod tests { .endpoints[0] .credential_binding = Some(NetworkCredentialBinding { provider: "work-cloud".to_string(), + placement: None, }); let bound_endpoint = &mut policy .network_policies @@ -15402,6 +15643,7 @@ mod tests { sandbox_id: "sb-policy-binding".to_string(), supports_static_credential_bindings: supports_bindings, supports_stable_placeholder_environment_keys: supports_stable, + supports_static_credential_endpoint_placements: false, })), ) .await @@ -15446,6 +15688,7 @@ mod tests { sandbox_id: "sb-policy-binding".to_string(), supports_static_credential_bindings: true, supports_stable_placeholder_environment_keys: true, + supports_static_credential_endpoint_placements: true, })), ) .await @@ -15472,6 +15715,7 @@ mod tests { host: "api.cloud.example".to_string(), port: 443, path: String::new(), + placement: None, }] ); assert_eq!( @@ -15525,6 +15769,7 @@ mod tests { sandbox_id: "sb-policy-binding".to_string(), supports_static_credential_bindings: true, supports_stable_placeholder_environment_keys: true, + supports_static_credential_endpoint_placements: true, })), ) .await @@ -15592,6 +15837,7 @@ mod tests { sandbox_id: "sb-policy-binding".to_string(), supports_static_credential_bindings: true, supports_stable_placeholder_environment_keys: true, + supports_static_credential_endpoint_placements: true, })), ) .await @@ -15689,6 +15935,7 @@ mod tests { sandbox_id: "sb-mixed-provider-env".to_string(), supports_static_credential_bindings: true, supports_stable_placeholder_environment_keys: true, + supports_static_credential_endpoint_placements: true, })), ) .await @@ -15798,6 +16045,7 @@ mod tests { sandbox_id: "sb-token-exchange-subject".to_string(), supports_static_credential_bindings: true, supports_stable_placeholder_environment_keys: true, + supports_static_credential_endpoint_placements: true, })), ) .await @@ -15866,6 +16114,7 @@ mod tests { sandbox_id: "sb-provider-revision".to_string(), supports_static_credential_bindings: true, supports_stable_placeholder_environment_keys: true, + supports_static_credential_endpoint_placements: true, })), ) .await @@ -15906,6 +16155,7 @@ mod tests { sandbox_id: "sb-provider-revision".to_string(), supports_static_credential_bindings: true, supports_stable_placeholder_environment_keys: true, + supports_static_credential_endpoint_placements: true, })), ) .await @@ -15952,7 +16202,7 @@ mod tests { let mut revisions = HashSet::new(); for _ in 0..16 { let config = load_sandbox_config(&state, &sandbox).await.unwrap(); - let environment = load_sandbox_provider_environment(&state, &sandbox, true, true) + let environment = load_sandbox_provider_environment(&state, &sandbox, true, true, true) .await .unwrap(); assert_eq!( @@ -16570,6 +16820,7 @@ mod tests { sandbox_id: "sb-attach-lifecycle".to_string(), supports_static_credential_bindings: true, supports_stable_placeholder_environment_keys: true, + supports_static_credential_endpoint_placements: true, })), ) .await @@ -16604,6 +16855,7 @@ mod tests { sandbox_id: "sb-attach-lifecycle".to_string(), supports_static_credential_bindings: true, supports_stable_placeholder_environment_keys: true, + supports_static_credential_endpoint_placements: true, })), ) .await @@ -16646,6 +16898,7 @@ mod tests { sandbox_id: "sb-attach-lifecycle".to_string(), supports_static_credential_bindings: true, supports_stable_placeholder_environment_keys: true, + supports_static_credential_endpoint_placements: true, })), ) .await @@ -16751,6 +17004,7 @@ mod tests { sandbox_id: "sb-attach-lifecycle".to_string(), supports_static_credential_bindings: true, supports_stable_placeholder_environment_keys: true, + supports_static_credential_endpoint_placements: true, })), ) .await @@ -16788,6 +17042,7 @@ mod tests { sandbox_id: "sb-attach-lifecycle".to_string(), supports_static_credential_bindings: true, supports_stable_placeholder_environment_keys: true, + supports_static_credential_endpoint_placements: true, })), ) .await @@ -16829,6 +17084,7 @@ mod tests { sandbox_id: "sb-attach-lifecycle".to_string(), supports_static_credential_bindings: true, supports_stable_placeholder_environment_keys: true, + supports_static_credential_endpoint_placements: true, })), ) .await @@ -26850,6 +27106,7 @@ mod tests { sandbox_id: "sandbox-other".into(), supports_static_credential_bindings: true, supports_stable_placeholder_environment_keys: true, + supports_static_credential_endpoint_placements: true, }), ) .await diff --git a/crates/openshell-server/src/grpc/policy/token_grant_owners_tests.rs b/crates/openshell-server/src/grpc/policy/token_grant_owners_tests.rs index b3608bd942..abe6d1c148 100644 --- a/crates/openshell-server/src/grpc/policy/token_grant_owners_tests.rs +++ b/crates/openshell-server/src/grpc/policy/token_grant_owners_tests.rs @@ -92,7 +92,7 @@ async fn composed_owners_survive_name_collisions_and_audience_overrides() { let policy = config.policy.unwrap(); assert!(policy.network_policies.contains_key("_provider_team_a")); assert!(policy.network_policies.contains_key("_provider_team_a_2")); - let environment = load_sandbox_provider_environment(&state, &sandbox, true, true) + let environment = load_sandbox_provider_environment(&state, &sandbox, true, true, true) .await .unwrap(); assert_eq!(environment.policy_hash, deterministic_policy_hash(&policy)); @@ -153,7 +153,7 @@ async fn refreshed_profile_owners_do_not_match_the_previous_policy() { let mut replacement = profile("owner-a", "/alpha/**"); replacement.binaries[0].path = "/usr/bin/replacement-client".into(); store_profile(&state, replacement).await; - let environment = load_sandbox_provider_environment(&state, &sandbox, true, true) + let environment = load_sandbox_provider_environment(&state, &sandbox, true, true, true) .await .unwrap(); let replacement_policy = load_sandbox_config(&state, &sandbox) @@ -184,7 +184,7 @@ async fn refreshed_profile_owners_do_not_match_the_previous_policy() { async fn global_policy_replaces_grant_authorities_and_preserves_profile_destinations() { let state = test_server_state().await; let sandbox = provider_sandbox(&state).await; - let before = load_sandbox_provider_environment(&state, &sandbox, true, true) + let before = load_sandbox_provider_environment(&state, &sandbox, true, true, true) .await .unwrap(); let mut global = ProtoSandboxPolicy { @@ -228,7 +228,7 @@ async fn global_policy_replaces_grant_authorities_and_preserves_profile_destinat assert_eq!(global.network_policies.len(), 1); let global_owner = &global.network_policies["global_api"].endpoints[0].token_grant_owner; assert_ne!(global_owner, "forged-global-owner"); - let after = load_sandbox_provider_environment(&state, &sandbox, true, true) + let after = load_sandbox_provider_environment(&state, &sandbox, true, true, true) .await .unwrap(); assert_ne!(before.provider_env_revision, after.provider_env_revision); @@ -270,9 +270,10 @@ async fn global_policy_replaces_grant_authorities_and_preserves_profile_destinat .await .unwrap(); let replacement_config = load_sandbox_config(&state, &sandbox).await.unwrap(); - let replacement_environment = load_sandbox_provider_environment(&state, &sandbox, true, true) - .await - .unwrap(); + let replacement_environment = + load_sandbox_provider_environment(&state, &sandbox, true, true, true) + .await + .unwrap(); assert_ne!( after.provider_env_revision, replacement_environment.provider_env_revision diff --git a/crates/openshell-server/src/grpc/provider.rs b/crates/openshell-server/src/grpc/provider.rs index e14424bc9c..597c576e48 100644 --- a/crates/openshell-server/src/grpc/provider.rs +++ b/crates/openshell-server/src/grpc/provider.rs @@ -1382,6 +1382,7 @@ pub(super) async fn resolve_provider_environment_from_records_with_policy_bindin host: endpoint.host.clone(), port, path: endpoint.path.clone(), + placement: None, }) }) .collect::>() @@ -1832,7 +1833,15 @@ fn derive_workload_credential_handle( "" | "**" | "/**" => "/**".to_string(), path => path.to_string(), }; - (host, endpoint.port, path) + let placement = endpoint.placement.as_ref().map(|placement| { + [ + placement.auth_style.trim().to_ascii_lowercase(), + placement.header_name.trim().to_ascii_lowercase(), + placement.query_param.clone(), + placement.path_template.clone(), + ] + }); + (host, endpoint.port, path, placement) }) .collect::>(); endpoints.sort(); @@ -1844,11 +1853,27 @@ fn derive_workload_credential_handle( hash_handle_component(&mut hasher, provider_id.as_bytes()); hash_handle_component(&mut hasher, credential_key.as_bytes()); hash_handle_component(&mut hasher, authorization_epoch.as_bytes()); - for (host, port, path) in endpoints { + for (host, port, path, _) in &endpoints { hash_handle_component(&mut hasher, host.as_bytes()); hash_handle_component(&mut hasher, &port.to_le_bytes()); hash_handle_component(&mut hasher, path.as_bytes()); } + // Bindings without endpoint placements keep their existing handles. A + // placement change revokes the handle like any other endpoint + // authorization change. Presence components are one byte, so this + // section cannot be read as another endpoint's four-byte port. + if endpoints + .iter() + .any(|(_, _, _, placement)| placement.is_some()) + { + hash_handle_component(&mut hasher, b"openshell-endpoint-placements-v1"); + for (_, _, _, placement) in &endpoints { + hash_handle_component(&mut hasher, &[u8::from(placement.is_some())]); + for field in placement.iter().flatten() { + hash_handle_component(&mut hasher, field.as_bytes()); + } + } + } hex::encode(hasher.finalize()) } @@ -14159,6 +14184,7 @@ pub(super) mod tests { host: "api.example.com".into(), port: 443, path: "/**".into(), + placement: None, }]; let baseline = static_credential_binding( Some("sandbox"), @@ -14266,6 +14292,7 @@ pub(super) mod tests { host: "api.example.com".to_string(), port: 443, path: "/v1/**".to_string(), + placement: None, }]; let external_binding = |sandbox, record: &ProviderEnvironmentRecord, key, endpoints: &[_]| { @@ -14291,6 +14318,7 @@ pub(super) mod tests { host: host.to_string(), port, path: path.to_string(), + placement: None, }]; assert!( initial.workload_credential_handle @@ -14320,11 +14348,13 @@ pub(super) mod tests { host: "API.EXAMPLE.COM.".to_string(), port: 443, path: "**".to_string(), + placement: None, }, StaticCredentialEndpointBinding { host: "files.example.com".to_string(), port: 8443, path: "/v1/**".to_string(), + placement: None, }, ]; let mut reordered = endpoints.clone(); @@ -14384,6 +14414,7 @@ pub(super) mod tests { host: "api.example.com".to_string(), port: 443, path: "/v2/**".to_string(), + placement: None, }], ), ] { @@ -14983,6 +15014,7 @@ pub(super) mod tests { host: "storage.googleapis.com".to_string(), port: 443, path: "/**".to_string(), + placement: None, }], )]); @@ -15052,6 +15084,7 @@ pub(super) mod tests { host: "tools.example.com".to_string(), port: 443, path: "/mcp/**".to_string(), + placement: None, }], )]); let credentials = crate::credentials::CredentialRuntime::from_config( @@ -15162,6 +15195,7 @@ pub(super) mod tests { host: "storage.googleapis.com".to_string(), port: 443, path: "/**".to_string(), + placement: None, }], )]); let bound = resolve_provider_environment_from_records_with_policy_bindings_and_credentials( diff --git a/crates/openshell-server/src/grpc/sandbox.rs b/crates/openshell-server/src/grpc/sandbox.rs index 8e5762a33b..d607d0abac 100644 --- a/crates/openshell-server/src/grpc/sandbox.rs +++ b/crates/openshell-server/src/grpc/sandbox.rs @@ -7191,6 +7191,7 @@ mod tests { port: 443, credential_binding: Some(openshell_core::proto::NetworkCredentialBinding { provider: "work-gcp".to_string(), + placement: None, }), ..Default::default() }], diff --git a/crates/openshell-server/src/storage_proto.rs b/crates/openshell-server/src/storage_proto.rs index 4c452c7cf3..ed5b2468fd 100644 --- a/crates/openshell-server/src/storage_proto.rs +++ b/crates/openshell-server/src/storage_proto.rs @@ -252,13 +252,13 @@ mod tests { // The service backend HTTP version is part of both schemas. Legacy // endpoint records omit it and continue to use HTTP/1.1. const PUBLIC_RPC_SCHEMA_SHA256: &str = - "edfc80ad192e77e1a9d1e1d6e3342280e4438f8bf7cb49969f580060df9a056a"; + "14ebaf33fdc17b0fdcf1226e611b3fb3641360cc66090fbef13aa006c27b670e"; // The storage.v2 refresh root adds retired handles and the first mint's // provider revision. All fields from the prior root retain their wire tags. const DURABLE_SCHEMA_SHA256: &str = - "ca31950286327bc385fae933bbb9e34d3c9191214f9b549c558bba40957fcc65"; + "acaa7cf6b0c38969642cc89b10cef71eb11df8aeea91c64a2efe88b56410b747"; const PUBLIC_DURABLE_OVERLAP_SHA256: &str = - "d0eead2cd403f6f52ecd9b7df73ca7db15e84dd847e11bc9d50469970204e589"; + "1c77da747567c3bf5bd50b442f958915baa6fcb94540eb8ab68aa813b15f8c48"; // Encoded with the schema that omitted stable_placeholder. Keep these // bytes fixed so the current encoder cannot hide a compatibility change. const LEGACY_STATIC_PROFILE: &str = "0a240a116c65676163792d70726f66696c652d6964120d6c65676163792d737461746963280712510a0d6c65676163792d73746174696312184c6567616379207374617469632063726564656e7469616c2a260a076170695f6b65791a1153594e5448455449435f4150495f4b455920012a06626561726572"; @@ -817,9 +817,9 @@ mod tests { overlap_hash.as_str(), ), ( - (369, 32), - (104, 23), - (88, 23), + (370, 32), + (105, 23), + (89, 23), PUBLIC_RPC_SCHEMA_SHA256, DURABLE_SCHEMA_SHA256, PUBLIC_DURABLE_OVERLAP_SHA256 diff --git a/crates/openshell-supervisor-network/src/google_cloud_metadata.rs b/crates/openshell-supervisor-network/src/google_cloud_metadata.rs index ea5d0c16bd..935c85a185 100644 --- a/crates/openshell-supervisor-network/src/google_cloud_metadata.rs +++ b/crates/openshell-supervisor-network/src/google_cloud_metadata.rs @@ -380,6 +380,7 @@ mod tests { host: "storage.googleapis.com".into(), port: 443, path: "/**".into(), + placement: None, }], credential_identity: "test-google:token".into(), workload_credential_handle: String::new(), diff --git a/crates/openshell-supervisor-network/src/l7/relay.rs b/crates/openshell-supervisor-network/src/l7/relay.rs index 7f0fad468d..e4408098aa 100644 --- a/crates/openshell-supervisor-network/src/l7/relay.rs +++ b/crates/openshell-supervisor-network/src/l7/relay.rs @@ -5154,6 +5154,7 @@ mod tests { host: "allowed.example.test".to_string(), port: 443, path: "/allowed/**".to_string(), + placement: None, }], credential_identity: identity.to_string(), workload_credential_handle: String::new(), @@ -7873,6 +7874,7 @@ network_policies: host: "api.example.test".to_string(), port: 8080, path: "/v1/**".to_string(), + placement: None, }], credential_identity: "provider-a:API_TOKEN".to_string(), workload_credential_handle: String::new(), @@ -7977,6 +7979,7 @@ network_policies: host: "api.example.test".to_string(), port: u32::from(port), path: "/v1/**".to_string(), + placement: None, }], credential_identity: "provider-a:API_TOKEN".to_string(), workload_credential_handle: String::new(), @@ -8632,6 +8635,7 @@ network_policies: host: "api.example.test".to_string(), port: 443, path: "/allowed".to_string(), + placement: None, }], credential_identity: "provider-a:API_TOKEN".to_string(), workload_credential_handle: String::new(), @@ -9856,6 +9860,7 @@ network_policies: host: "api.example.test".into(), port: 8080, path: "/v1/**".into(), + placement: None, }], credential_identity: "provider-a:API_TOKEN".into(), workload_credential_handle: String::new(), @@ -11889,6 +11894,7 @@ network_policies: host: "allowed.example.test".to_string(), port: 443, path: "/allowed/**".to_string(), + placement: None, }], credential_identity: "provider-a:API_TOKEN".to_string(), workload_credential_handle: String::new(), @@ -15782,6 +15788,7 @@ network_policies: host: ctx.host.clone(), port: u32::from(ctx.port), path: "/mcp".into(), + placement: None, }], credential_identity: "provider:API_TOKEN".into(), workload_credential_handle: String::new(), diff --git a/crates/openshell-supervisor-network/src/l7/rest.rs b/crates/openshell-supervisor-network/src/l7/rest.rs index 3961d8d665..4d6f4820fe 100644 --- a/crates/openshell-supervisor-network/src/l7/rest.rs +++ b/crates/openshell-supervisor-network/src/l7/rest.rs @@ -11349,6 +11349,7 @@ mod tests { host: host.into(), port: 443, path: "/**".into(), + placement: None, }], }, ) @@ -11566,6 +11567,7 @@ mod tests { host: "api.github.com".into(), port: 443, path: "/**".into(), + placement: None, }], }, )]), diff --git a/crates/openshell-supervisor-network/src/l7/websocket.rs b/crates/openshell-supervisor-network/src/l7/websocket.rs index dae95cf6d2..eba9b11381 100644 --- a/crates/openshell-supervisor-network/src/l7/websocket.rs +++ b/crates/openshell-supervisor-network/src/l7/websocket.rs @@ -2695,6 +2695,7 @@ network_policies: host: "gateway.example.test".to_string(), port: 443, path: "/socket".to_string(), + placement: None, }], credential_identity: "provider-a:DISCORD_BOT_TOKEN".to_string(), workload_credential_handle: String::new(), @@ -2844,6 +2845,7 @@ network_policies: host: "gateway.example.test".into(), port: 443, path: "/socket".into(), + placement: None, }], credential_identity: "provider:DISCORD_BOT_TOKEN".into(), workload_credential_handle: String::new(), diff --git a/crates/openshell-supervisor-network/src/proxy.rs b/crates/openshell-supervisor-network/src/proxy.rs index 46709329b6..c385641705 100644 --- a/crates/openshell-supervisor-network/src/proxy.rs +++ b/crates/openshell-supervisor-network/src/proxy.rs @@ -14014,6 +14014,7 @@ network_policies: host: "api.example.test".to_string(), port: 80, path: "/allowed/**".to_string(), + placement: None, }], credential_identity: "provider-a:API_TOKEN".to_string(), workload_credential_handle: String::new(), @@ -16446,6 +16447,7 @@ network_policies: host: "api.example.com".to_string(), port: 80, path: "/allowed/**".to_string(), + placement: None, }], credential_identity: "provider-a:API_TOKEN".to_string(), workload_credential_handle: String::new(), @@ -16491,6 +16493,7 @@ network_policies: host: "api.example.com".to_string(), port: 80, path: "/allowed/**".to_string(), + placement: None, }], credential_identity: "provider-a:API_TOKEN".to_string(), workload_credential_handle: String::new(), @@ -16537,6 +16540,7 @@ network_policies: host: "api.example.com".to_string(), port: 80, path: "/**".to_string(), + placement: None, }], credential_identity: "provider-a:API_TOKEN".to_string(), workload_credential_handle: String::new(), @@ -17261,6 +17265,7 @@ network_policies: host: "bot-api.example.com".into(), port: 80, path: "/**".into(), + placement: None, }], }, )]), @@ -17323,6 +17328,7 @@ network_policies: host: "api.example.com".into(), port: 80, path: "/**".into(), + placement: None, }], }, )]), @@ -17468,6 +17474,7 @@ network_policies: host: "allowed.example.com".to_string(), port: 80, path: "/allowed/**".to_string(), + placement: None, }], credential_identity: "provider-a:API_TOKEN".to_string(), workload_credential_handle: String::new(), @@ -17560,6 +17567,7 @@ network_policies: host: "allowed.example.com".to_string(), port: 80, path: "/allowed/**".to_string(), + placement: None, }], credential_identity: format!("provider-a:{key}"), workload_credential_handle: String::new(), diff --git a/crates/openshell-supervisor-network/src/proxy/relay.rs b/crates/openshell-supervisor-network/src/proxy/relay.rs index 2a6eeab907..e51971f748 100644 --- a/crates/openshell-supervisor-network/src/proxy/relay.rs +++ b/crates/openshell-supervisor-network/src/proxy/relay.rs @@ -2287,6 +2287,7 @@ network_policies: host: "example.com".to_string(), port: 80, path: "/**".to_string(), + placement: None, }], credential_identity: format!("provider:{key}"), workload_credential_handle: if key == "API_KEY" { diff --git a/crates/openshell-supervisor/src/config_runtime.rs b/crates/openshell-supervisor/src/config_runtime.rs index 46c4f8751b..57a1c17bf7 100644 --- a/crates/openshell-supervisor/src/config_runtime.rs +++ b/crates/openshell-supervisor/src/config_runtime.rs @@ -2006,6 +2006,7 @@ mod tests { host: "tools.example.com".into(), port: 443, path: "/v1/**".into(), + placement: None, }], credential_identity: "provider-a:EXTERNAL_TOKEN".into(), workload_credential_handle: String::new(), diff --git a/crates/openshell-supervisor/src/lib.rs b/crates/openshell-supervisor/src/lib.rs index 6278307846..0c66cbb184 100644 --- a/crates/openshell-supervisor/src/lib.rs +++ b/crates/openshell-supervisor/src/lib.rs @@ -2241,10 +2241,9 @@ async fn flush_activity_to_gateway( /// Versioned policy capabilities compiled into this supervisor. fn supported_policy_capabilities() -> Vec { - openshell_core::extension_protocol::capabilities_if( - openshell_core::extension_protocol::POLICY_CEDAR_V1, - cfg!(feature = "experimental"), - ) + openshell_core::extension_protocol::supervisor_policy_capabilities(cfg!( + feature = "experimental" + )) } /// Minimum read-only paths required for a proxy-mode sandbox child process to diff --git a/crates/openshell-supervisor/src/main.rs b/crates/openshell-supervisor/src/main.rs index b455799f1e..7ac524a4f8 100644 --- a/crates/openshell-supervisor/src/main.rs +++ b/crates/openshell-supervisor/src/main.rs @@ -508,10 +508,9 @@ fn main() -> Result<()> { openshell_crypto::tls::ensure_default_provider(); let exit = openshell_supervisor_process::debug_rpc::run( &raw_args[2..], - openshell_core::extension_protocol::capabilities_if( - openshell_core::extension_protocol::POLICY_CEDAR_V1, - cfg!(feature = "experimental"), - ), + openshell_core::extension_protocol::supervisor_policy_capabilities(cfg!( + feature = "experimental" + )), ) .await?; std::process::exit(exit); diff --git a/docs/how-it-works/policies/schema.mdx b/docs/how-it-works/policies/schema.mdx index bb87555ab0..f825a0e503 100644 --- a/docs/how-it-works/policies/schema.mdx +++ b/docs/how-it-works/policies/schema.mdx @@ -171,6 +171,7 @@ the gateway host. | Field | Type | Default | Description | |---|---|---|---| | `credential_binding.provider` | string | None | Binds the static credentials of an attached provider whose profile defines no endpoints. Valid only in a sandbox policy. | +| `credential_binding.placement` | object | Profile placement | Request location for the bound credentials at this endpoint only. Takes `auth_style` and the matching `header_name`, `query_param`, or `path_template`, with the same meanings as in a provider profile. Cannot be combined with `credential_signing`. | | `request_body_credential_rewrite` | bool | `false` | Replaces ordinary static credential placeholders in REST bodies, including those with declared HTTP placement. | | `websocket_credential_rewrite` | bool | `false` | Replaces ordinary static credential placeholders in client WebSocket text messages, including those with declared HTTP placement. Requires `protocol: websocket`. | | `allow_uninspected_credentials` | bool | `false` | Allows a provider-credentialed endpoint to omit request inspection or use `tls: skip`. | diff --git a/docs/how-it-works/providers/profiles.mdx b/docs/how-it-works/providers/profiles.mdx index 9b083fe05e..a243171308 100644 --- a/docs/how-it-works/providers/profiles.mdx +++ b/docs/how-it-works/providers/profiles.mdx @@ -169,6 +169,44 @@ This keeps one source of credential-binding authority for each provider. `credential_binding` is sandbox-scoped and is not accepted in a gateway-global policy. +A binding can set its own `placement` when consumers of one credential expect +it in different request locations. Each endpoint then accepts the credential +only at its own placement, and replacing or removing the provider credential +affects every binding: + +```yaml showLineNumbers={false} +network_policies: + shared_api: + endpoints: + - host: api.example.com + port: 443 + protocol: rest + access: full + credential_binding: + provider: work-api + placement: + auth_style: bearer + header_name: Authorization + - host: gateway.example.com + port: 443 + protocol: rest + access: full + credential_binding: + provider: work-api + placement: + auth_style: header + header_name: x-api-key +``` + +`placement` accepts the profile `auth_style` values and requires the field +that style uses. Fields for other styles are rejected. Without `placement`, the +endpoint uses each credential's profile placement. The placement applies to +every static credential the provider supplies at that endpoint. Bindings of +one provider whose host, port, and path can match the same request must use the +same placement; OpenShell rejects the policy update otherwise. Supervisors that +do not enforce binding placement do not receive the policy or the affected +credentials. + For AWS endpoints, the binding and signing fields have separate jobs. `credential_binding.provider` selects the provider instance that supplies credentials. `credential_signing`, `signing_service`, and `signing_region` diff --git a/e2e/rust/tests/kubernetes_shared_supervisor_spiffe.rs b/e2e/rust/tests/kubernetes_shared_supervisor_spiffe.rs index b89f60fd90..9297a0e224 100644 --- a/e2e/rust/tests/kubernetes_shared_supervisor_spiffe.rs +++ b/e2e/rust/tests/kubernetes_shared_supervisor_spiffe.rs @@ -979,6 +979,7 @@ impl BrokerProbe { sandbox_id: sandbox_id.to_string(), supports_static_credential_bindings: true, supports_stable_placeholder_environment_keys: true, + supports_static_credential_endpoint_placements: true, }); let environment = probe .client diff --git a/proto/openshell.proto b/proto/openshell.proto index 4212445623..113e943cf4 100644 --- a/proto/openshell.proto +++ b/proto/openshell.proto @@ -3067,6 +3067,10 @@ message GetSandboxProviderEnvironmentRequest { // metadata. Gateways withhold credentials that require this behavior when // the capability is absent. bool supports_stable_placeholder_environment_keys = 3; + // Whether the requesting supervisor enforces per-endpoint placement in + // static credential bindings. Gateways withhold credentials whose binding + // carries an endpoint placement when this capability is absent. + bool supports_static_credential_endpoint_placements = 4; } // One network endpoint at which a static provider credential may be resolved. @@ -3074,6 +3078,10 @@ message StaticCredentialEndpointBinding { string host = 1; uint32 port = 2; string path = 3; + // Request location authorized at this endpoint. Absent keeps the + // credential's provider profile placement. Gateways send it only to + // supervisors that set supports_static_credential_endpoint_placements. + openshell.sandbox.v1.NetworkCredentialPlacement placement = 4; } // Endpoint allowlist for one static provider credential environment variable. diff --git a/proto/sandbox.proto b/proto/sandbox.proto index 4699ee244d..8182408948 100644 --- a/proto/sandbox.proto +++ b/proto/sandbox.proto @@ -134,6 +134,24 @@ message NetworkCredentialBinding { // Name of the provider attached to this sandbox whose static credentials // may be resolved for requests admitted by this endpoint. string provider = 1; + // Request location at which this endpoint accepts the provider's static + // credentials. Absent keeps each credential's provider profile placement. + // When set, it replaces that placement for requests admitted by this + // endpoint only; other bindings of the same provider are unaffected. + NetworkCredentialPlacement placement = 2; +} + +// Request location a credential binding authorizes for static credentials. +// Fields match provider profile credential placement metadata. +message NetworkCredentialPlacement { + // One of "basic", "bearer", "header", "query", "path", or "path_subtree". + string auth_style = 1; + // Header name for "bearer" and "header". + string header_name = 2; + // Query parameter name for "query". + string query_param = 3; + // Path with exactly one "{credential}" slot for "path" and "path_subtree". + string path_template = 4; } // TLS handling for a network endpoint. diff --git a/skills/generate-sandbox-policy/SKILL.md b/skills/generate-sandbox-policy/SKILL.md index c36b244f71..38100629c3 100644 --- a/skills/generate-sandbox-policy/SKILL.md +++ b/skills/generate-sandbox-policy/SKILL.md @@ -489,6 +489,11 @@ The policy needs to go somewhere. Determine which mode applies: declares `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY` and covers the signed endpoint. For an endpointless AWS profile, add `credential_binding.provider` with the exact attached provider name. + - When an endpointless provider's credential must appear in a different + request location at one endpoint, set `credential_binding.placement` + (`auth_style` plus its `header_name`, `query_param`, or `path_template`) + on that endpoint. Overlapping bindings of one provider must use the same + placement. 3. **Apply the change**: - **Adding a new policy**: Insert the new policy block under `network_policies`, maintaining the file's existing indentation and style. diff --git a/tests/testkit/testkit/src/policy.rs b/tests/testkit/testkit/src/policy.rs index efbdcf1038..b6d30acdec 100644 --- a/tests/testkit/testkit/src/policy.rs +++ b/tests/testkit/testkit/src/policy.rs @@ -182,6 +182,7 @@ impl Endpoint for proto::NetworkEndpoint { fn credential_binding(&mut self, provider: &str) -> &mut Self { self.credential_binding = Some(proto::NetworkCredentialBinding { provider: provider.to_string(), + placement: None, }); self } From 1453367cdf5ee4321db934410a68abcbd95ee7d7 Mon Sep 17 00:00:00 2001 From: Mrunal Patel Date: Wed, 2 Dec 2026 18:19:26 +0000 Subject: [PATCH 2/6] fix(policy): address credential binding placement review - Read the effective configuration with the trusted loader when recording admission reports and refreshing sandbox tokens, so the supervisor-facing capability gate no longer rejects these internal reads for placement-bearing policies. - Enforce the header value form of an explicit binding placement: bearer accepts only "Bearer ", header only the bare placeholder, and basic only Basic authorization. Profile placements keep their documented behavior. - Treat a "/**" subtree as also matching its root path when checking overlapping bindings of one provider for conflicting placements. - Advertise supported policy capabilities in Health and have the CLI refuse to submit credential_binding.placement to a gateway that does not advertise it, since an older gateway drops the field. Refs #5963 Signed-off-by: Mrunal Patel --- crates/openshell-cli/src/run.rs | 56 +++++++ .../tests/ensure_providers_integration.rs | 1 + .../openshell-cli/tests/mtls_integration.rs | 1 + .../tests/provider_commands_integration.rs | 1 + .../sandbox_create_lifecycle_integration.rs | 1 + .../sandbox_name_fallback_integration.rs | 1 + .../openshell-core/src/extension_protocol.rs | 6 + .../src/provider_credentials.rs | 77 ++++++++- crates/openshell-core/src/secrets.rs | 50 +++++- crates/openshell-policy/src/ambiguity.rs | 29 +++- crates/openshell-policy/src/lib.rs | 15 ++ crates/openshell-sdk/tests/client_mock.rs | 1 + crates/openshell-server/src/grpc/auth_rpc.rs | 54 +++++-- crates/openshell-server/src/grpc/mod.rs | 100 +++++++++++- crates/openshell-server/src/grpc/policy.rs | 152 ++++++++---------- crates/openshell-server/src/storage_proto.rs | 2 +- crates/openshell-server/tests/common/mod.rs | 1 + docs/how-it-works/policies/schema.mdx | 2 +- docs/how-it-works/providers/profiles.mdx | 22 ++- proto/openshell.proto | 6 + 20 files changed, 456 insertions(+), 122 deletions(-) diff --git a/crates/openshell-cli/src/run.rs b/crates/openshell-cli/src/run.rs index 3a7e45582c..d26096bda0 100644 --- a/crates/openshell-cli/src/run.rs +++ b/crates/openshell-cli/src/run.rs @@ -1142,6 +1142,9 @@ pub async fn sandbox_create( .await?; let policy = load_sandbox_policy(policy)?; + if let Some(policy) = &policy { + require_gateway_policy_support(&mut client, policy).await?; + } let resource_limits = if template.is_none() { build_sandbox_resource_limits(cpu, memory)? } else { @@ -2068,6 +2071,38 @@ fn load_sandbox_policy(cli_path: Option<&str>) -> Result> openshell_policy::load_sandbox_policy(cli_path) } +/// Refuse to submit `credential_binding.placement` to a gateway that does not +/// advertise it. An older gateway drops the unknown field while decoding and +/// would apply the provider profile placement at that endpoint instead. +async fn require_gateway_policy_support( + client: &mut GrpcClient, + policy: &SandboxPolicy, +) -> Result<()> { + if !openshell_policy::uses_credential_binding_placement(policy) { + return Ok(()); + } + let health = client + .health(openshell_core::proto::HealthRequest {}) + .await + .into_diagnostic()? + .into_inner(); + check_gateway_policy_support(policy, &health.supported_policy_capabilities) +} + +fn check_gateway_policy_support(policy: &SandboxPolicy, supported: &[String]) -> Result<()> { + if openshell_policy::uses_credential_binding_placement(policy) + && !openshell_core::extension_protocol::has_capability( + supported, + openshell_core::extension_protocol::POLICY_CREDENTIAL_BINDING_PLACEMENT_V1, + ) + { + return Err(miette::miette!( + "the gateway does not support credential_binding.placement; upgrade every gateway replica before using it" + )); + } + Ok(()) +} + /// Sync files to or from a sandbox. /// /// Dispatches to `sandbox_sync_up` or `sandbox_sync_down` based on the @@ -6362,6 +6397,7 @@ pub async fn sandbox_policy_set( .ok_or_else(|| miette::miette!("No policy loaded from {policy_path}"))?; let mut client = grpc_client(server, tls).await?; + require_gateway_policy_support(&mut client, &policy).await?; // Get the current revision to detect no-ops and, for a Cedar file, to // keep the configuration the file cannot carry. @@ -7813,6 +7849,26 @@ mod tests { assert!(update.provider_credential_rules.is_empty()); } + #[test] + fn credential_binding_placement_requires_gateway_support() { + use super::check_gateway_policy_support; + + let policy = |placement: &str| { + openshell_policy::parse_sandbox_policy(&format!( + "version: 1\nnetwork_policies:\n api:\n endpoints:\n - {{host: api.example.com, port: 443, credential_binding: {{provider: p{placement}}}}}\n" + )) + .expect("policy") + }; + let placed = policy(", placement: {auth_style: header, header_name: x-api-key}"); + let supported = openshell_core::extension_protocol::gateway_policy_capabilities(); + + // An older gateway advertises nothing and would drop the field. + assert!(check_gateway_policy_support(&placed, &[]).is_err()); + assert!(check_gateway_policy_support(&placed, &supported).is_ok()); + // Policies without placement never depend on the capability. + assert!(check_gateway_policy_support(&policy(""), &[]).is_ok()); + } + #[test] fn cedar_policy_set_fails_when_the_current_policy_cannot_be_read() { use super::current_policy_revision; diff --git a/crates/openshell-cli/tests/ensure_providers_integration.rs b/crates/openshell-cli/tests/ensure_providers_integration.rs index 3f17d22921..9138f1a84b 100644 --- a/crates/openshell-cli/tests/ensure_providers_integration.rs +++ b/crates/openshell-cli/tests/ensure_providers_integration.rs @@ -93,6 +93,7 @@ impl OpenShell for TestOpenShell { Ok(Response::new(HealthResponse { status: ServiceStatus::Healthy.into(), version: "test".to_string(), + supported_policy_capabilities: Vec::new(), })) } diff --git a/crates/openshell-cli/tests/mtls_integration.rs b/crates/openshell-cli/tests/mtls_integration.rs index d5813cc017..58b5eba7a0 100644 --- a/crates/openshell-cli/tests/mtls_integration.rs +++ b/crates/openshell-cli/tests/mtls_integration.rs @@ -45,6 +45,7 @@ impl OpenShell for TestOpenShell { Ok(Response::new(HealthResponse { status: ServiceStatus::Healthy.into(), version: "test".to_string(), + supported_policy_capabilities: Vec::new(), })) } diff --git a/crates/openshell-cli/tests/provider_commands_integration.rs b/crates/openshell-cli/tests/provider_commands_integration.rs index f5563a7e77..c3112b8400 100644 --- a/crates/openshell-cli/tests/provider_commands_integration.rs +++ b/crates/openshell-cli/tests/provider_commands_integration.rs @@ -251,6 +251,7 @@ impl OpenShell for TestOpenShell { Ok(Response::new(HealthResponse { status: ServiceStatus::Healthy.into(), version: "test".to_string(), + supported_policy_capabilities: Vec::new(), })) } diff --git a/crates/openshell-cli/tests/sandbox_create_lifecycle_integration.rs b/crates/openshell-cli/tests/sandbox_create_lifecycle_integration.rs index 8d616c69ba..5fc743e8ee 100644 --- a/crates/openshell-cli/tests/sandbox_create_lifecycle_integration.rs +++ b/crates/openshell-cli/tests/sandbox_create_lifecycle_integration.rs @@ -196,6 +196,7 @@ impl OpenShell for TestOpenShell { Ok(Response::new(HealthResponse { status: ServiceStatus::Healthy.into(), version: "test".to_string(), + supported_policy_capabilities: Vec::new(), })) } diff --git a/crates/openshell-cli/tests/sandbox_name_fallback_integration.rs b/crates/openshell-cli/tests/sandbox_name_fallback_integration.rs index 7e5a2c879f..4706ca561d 100644 --- a/crates/openshell-cli/tests/sandbox_name_fallback_integration.rs +++ b/crates/openshell-cli/tests/sandbox_name_fallback_integration.rs @@ -62,6 +62,7 @@ impl OpenShell for TestOpenShell { Ok(Response::new(HealthResponse { status: ServiceStatus::Healthy.into(), version: "test".to_string(), + supported_policy_capabilities: Vec::new(), })) } diff --git a/crates/openshell-core/src/extension_protocol.rs b/crates/openshell-core/src/extension_protocol.rs index b7cd0259da..ed36d80c47 100644 --- a/crates/openshell-core/src/extension_protocol.rs +++ b/crates/openshell-core/src/extension_protocol.rs @@ -19,6 +19,12 @@ pub const POLICY_CEDAR_V1: &str = "openshell.policy.cedar.v1"; pub const POLICY_CREDENTIAL_BINDING_PLACEMENT_V1: &str = "openshell.policy.credential-binding-placement.v1"; +/// Versioned policy features a gateway accepts and preserves in `Health`. +#[must_use] +pub fn gateway_policy_capabilities() -> Vec { + vec![POLICY_CREDENTIAL_BINDING_PLACEMENT_V1.to_string()] +} + /// Versioned policy capabilities a supervisor reports in its hello. #[must_use] pub fn supervisor_policy_capabilities(cedar: bool) -> Vec { diff --git a/crates/openshell-core/src/provider_credentials.rs b/crates/openshell-core/src/provider_credentials.rs index e82affae25..fa6ae718b5 100644 --- a/crates/openshell-core/src/provider_credentials.rs +++ b/crates/openshell-core/src/provider_credentials.rs @@ -5,7 +5,7 @@ use crate::secrets::{ CREDENTIAL_PATH_SLOT, CredentialPlacement, CredentialUseMarker, CredentialUses, - STALE_CREDENTIAL_VERSION, SecretResolver, + HeaderValueForm, STALE_CREDENTIAL_VERSION, SecretResolver, }; use crate::{ endpoint_path::EndpointPathPattern, @@ -1514,13 +1514,27 @@ pub fn endpoint_credential_placement( return Err(format!("{field} is not used by auth_style {style}")); } } - placement_from_fields( + let compiled = placement_from_fields( &placement.auth_style, &placement.header_name, &placement.query_param, &placement.path_template, ) - .ok_or_else(|| diagnostic.to_string()) + .ok_or_else(|| diagnostic.to_string())?; + // An explicit binding authorizes one exact header value form, unlike a + // profile placement, which accepts any form in its header. + Ok(match (style.as_str(), compiled) { + ("bearer", CredentialPlacement::Header(name)) => { + CredentialPlacement::ExplicitHeader(name, HeaderValueForm::Bearer) + } + ("header", CredentialPlacement::Header(name)) => { + CredentialPlacement::ExplicitHeader(name, HeaderValueForm::Raw) + } + ("basic", CredentialPlacement::Header(name)) => { + CredentialPlacement::ExplicitHeader(name, HeaderValueForm::Basic) + } + (_, compiled) => compiled, + }) } fn placement_from_fields( @@ -2093,6 +2107,63 @@ mod tests { ); } + #[test] + fn endpoint_placement_enforces_the_header_value_form() { + use base64::Engine as _; + let state = multi_endpoint_state( + vec![ + endpoint( + "bearer.example.com", + "/**", + Some(("bearer", "Authorization")), + ), + endpoint("raw.example.com", "/**", Some(("header", "Authorization"))), + endpoint("basic.example.com", "/**", Some(("basic", ""))), + endpoint("profile.example.com", "/**", None), + ], + HashMap::new(), + ); + let reference = state.snapshot().child_env["API_KEY"].clone(); + let basic = format!( + "Basic {}", + base64::engine::general_purpose::STANDARD.encode(format!("user:{reference}")) + ); + let forms = [ + ("raw", reference.clone()), + ("bearer", format!("Bearer {reference}")), + ("token", format!("token {reference}")), + ("basic", basic), + ]; + for (host, allowed) in [ + ("bearer.example.com", &["bearer"][..]), + ("raw.example.com", &["raw"][..]), + ("basic.example.com", &["basic"][..]), + // Profile placement keeps accepting every form in its header. + ( + "profile.example.com", + &["raw", "bearer", "token", "basic"][..], + ), + ] { + let resolver = state.resolver_for_endpoint(host, 443, "/").unwrap(); + for (form, value) in &forms { + let result = resolver.rewrite_header_value_for_name("Authorization", value); + if allowed.contains(form) { + assert!( + result.as_ref().is_ok_and(Option::is_some), + "{host} must accept {form}: {result:?}" + ); + } else { + assert!( + result.as_ref().is_err_and( + crate::secrets::UnresolvedPlaceholderError::is_placement_mismatch + ), + "{host} must reject {form}: {result:?}" + ); + } + } + } + } + #[test] fn endpoint_placement_replacement_rebinds_without_a_second_value() { let state = multi_endpoint_state( diff --git a/crates/openshell-core/src/secrets.rs b/crates/openshell-core/src/secrets.rs index 38be363a0e..d70844bd46 100644 --- a/crates/openshell-core/src/secrets.rs +++ b/crates/openshell-core/src/secrets.rs @@ -193,12 +193,29 @@ pub struct RewriteTargetResult { /// Credential-specific destinations authorized by the provider profile. #[derive(Debug, Clone, PartialEq, Eq)] pub enum CredentialPlacement { + /// Header name only. Accepts a raw value or any ` ` form, + /// preserving the documented provider profile behavior. Header(String), + /// Header name and the exact value form an endpoint binding authorizes. + ExplicitHeader(String, HeaderValueForm), QueryParam(String), PathTemplate(String), PathSubtree(String), } +/// How a credential placeholder is presented inside a header value. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum HeaderValueForm { + /// The whole header value is the placeholder. + Raw, + /// `Bearer `. + Bearer, + /// `Basic `. + Basic, + /// Any other ` `. Observed only; never authorized. + OtherScheme, +} + pub(crate) const CREDENTIAL_PATH_SLOT: &str = "{credential}"; /// Decode each wire segment independently. A subtree match must not gain a @@ -239,6 +256,8 @@ pub struct SecretResolver { policy_redaction_only: bool, placements: HashMap, request_location: Option, + /// Value form of the header currently being rewritten, if any. + header_form: Option, denied_env_keys: HashSet, identity_bound_env_keys: HashSet, revision_fallback_allowed_revisions: HashMap>>, @@ -517,6 +536,7 @@ impl SecretResolver { policy_redaction_only: false, placements: HashMap::new(), request_location: None, + header_form: None, denied_env_keys: HashSet::new(), identity_bound_env_keys: HashSet::new(), revision_fallback_allowed_revisions: HashMap::new(), @@ -576,6 +596,7 @@ impl SecretResolver { policy_redaction_only: false, placements: HashMap::new(), request_location: None, + header_form: None, denied_env_keys: HashSet::new(), identity_bound_env_keys: HashSet::new(), revision_fallback_allowed_revisions: HashMap::new(), @@ -607,6 +628,7 @@ impl SecretResolver { policy_redaction_only: false, placements, request_location: None, + header_form: None, denied_env_keys, identity_bound_env_keys, revision_fallback_allowed_revisions, @@ -644,6 +666,7 @@ impl SecretResolver { policy_redaction_only: self.policy_redaction_only, placements: self.placements.clone(), request_location: None, + header_form: None, denied_env_keys, identity_bound_env_keys: bound_keys.clone(), revision_fallback_allowed_revisions, @@ -665,6 +688,13 @@ impl SecretResolver { pub fn with_request_location(&self, location: RequestCredentialLocation) -> Self { let mut scoped = self.clone(); scoped.request_location = Some(location); + scoped.header_form = None; + scoped + } + + fn with_header_form(&self, form: HeaderValueForm) -> Self { + let mut scoped = self.clone(); + scoped.header_form = Some(form); scoped } @@ -698,6 +728,10 @@ impl SecretResolver { CredentialPlacement::Header(expected), Some(RequestCredentialLocation::Header(actual)), ) => expected.eq_ignore_ascii_case(actual), + ( + CredentialPlacement::ExplicitHeader(expected, form), + Some(RequestCredentialLocation::Header(actual)), + ) => expected.eq_ignore_ascii_case(actual) && self.header_form == Some(*form), ( CredentialPlacement::QueryParam(expected), Some(RequestCredentialLocation::QueryParam(actual)), @@ -900,7 +934,10 @@ impl SecretResolver { value: &str, ) -> Result, UnresolvedPlaceholderError> { // Direct placeholder match: `x-api-key: openshell:resolve:env:KEY` - if let Some(secret) = self.resolve_placeholder(value.trim()) { + if let Some(secret) = self + .with_header_form(HeaderValueForm::Raw) + .resolve_placeholder(value.trim()) + { return Ok(Some(secret.to_string())); } @@ -909,7 +946,9 @@ impl SecretResolver { // Basic auth decoding: `Basic ` where the decoded content // contains a placeholder (e.g. `user:openshell:resolve:env:PASS`). if let Some(encoded) = basic_auth_token(trimmed) - && let Some(rewritten) = self.rewrite_basic_auth_token(encoded)? + && let Some(rewritten) = self + .with_header_form(HeaderValueForm::Basic) + .rewrite_basic_auth_token(encoded)? { return Ok(Some(format!("Basic {rewritten}"))); } @@ -923,7 +962,12 @@ impl SecretResolver { }; let prefix = &trimmed[..split_at]; let candidate = trimmed[split_at..].trim(); - if let Some(secret) = self.resolve_placeholder(candidate) { + let form = if prefix.eq_ignore_ascii_case("bearer") { + HeaderValueForm::Bearer + } else { + HeaderValueForm::OtherScheme + }; + if let Some(secret) = self.with_header_form(form).resolve_placeholder(candidate) { return Ok(Some(format!("{prefix} {secret}"))); } diff --git a/crates/openshell-policy/src/ambiguity.rs b/crates/openshell-policy/src/ambiguity.rs index dacc74e730..9b55db37af 100644 --- a/crates/openshell-policy/src/ambiguity.rs +++ b/crates/openshell-policy/src/ambiguity.rs @@ -107,7 +107,7 @@ pub fn find_endpoint_ambiguities(policy: &SandboxPolicy) -> Vec bool { runtime_path_patterns_overlap(left, right) } +/// Overlap as static credential binding paths match at runtime, where a +/// trailing `/**` also selects the named path itself (`/v1/**` matches `/v1`). +fn credential_path_patterns_overlap(left: &str, right: &str) -> bool { + let variants = |pattern: &str| { + let subtree_root = pattern + .strip_suffix("/**") + .filter(|prefix| !prefix.is_empty()); + std::iter::once(pattern.to_string()) + .chain(subtree_root.map(str::to_string)) + .collect::>() + }; + variants(left).iter().any(|left| { + variants(right) + .iter() + .any(|right| path_patterns_overlap(left, right)) + }) +} + /// Match the runtime route-selection rank used by `L7EndpointConfig`. /// /// Overlapping endpoints with different ranks do not compete for request @@ -1022,6 +1040,11 @@ mod tests { bound("*.example.com", "", Some("x-token")), bound("api.example.com", "", Some("x-api-key")), ), + // A subtree selector also matches its root path at runtime. + ( + bound("api.example.com", "/v1", None), + bound("api.example.com", "/v1/**", Some("x-api-key")), + ), ] { let ambiguities = find_endpoint_ambiguities(&policy_with(left, right)); assert_eq!(ambiguities.len(), 1); @@ -1046,6 +1069,10 @@ mod tests { bound("api.example.com", "/v1/**", None), bound("api.example.com", "/v2/**", Some("x-api-key")), ), + ( + bound("api.example.com", "/v1", None), + bound("api.example.com", "/v10/**", Some("x-api-key")), + ), ] { assert!(find_endpoint_ambiguities(&policy_with(left, right)).is_empty()); } diff --git a/crates/openshell-policy/src/lib.rs b/crates/openshell-policy/src/lib.rs index d0b36e148a..0a46817aa4 100644 --- a/crates/openshell-policy/src/lib.rs +++ b/crates/openshell-policy/src/lib.rs @@ -2708,6 +2708,21 @@ pub fn validate_authored_rule_names( } /// Validate credential-binding structure without resolving attached providers. +/// Whether any endpoint's credential binding sets its own placement. +#[must_use] +pub fn uses_credential_binding_placement(policy: &SandboxPolicy) -> bool { + policy + .network_policies + .values() + .flat_map(|rule| &rule.endpoints) + .any(|endpoint| { + endpoint + .credential_binding + .as_ref() + .is_some_and(|binding| binding.placement.is_some()) + }) +} + pub fn validate_credential_bindings( policy: &SandboxPolicy, ) -> std::result::Result<(), Vec> { diff --git a/crates/openshell-sdk/tests/client_mock.rs b/crates/openshell-sdk/tests/client_mock.rs index 39d2f6b01e..166017714a 100644 --- a/crates/openshell-sdk/tests/client_mock.rs +++ b/crates/openshell-sdk/tests/client_mock.rs @@ -353,6 +353,7 @@ impl OpenShell for TestOpenShell { Ok(Response::new(proto::HealthResponse { status: proto::ServiceStatus::Healthy.into(), version: "test-1.2.3".to_string(), + supported_policy_capabilities: Vec::new(), })) } diff --git a/crates/openshell-server/src/grpc/auth_rpc.rs b/crates/openshell-server/src/grpc/auth_rpc.rs index 1f56bd708b..bdc9507460 100644 --- a/crates/openshell-server/src/grpc/auth_rpc.rs +++ b/crates/openshell-server/src/grpc/auth_rpc.rs @@ -21,8 +21,8 @@ use crate::auth::identity::IdentityProvider; use crate::auth::principal::{Principal, SandboxIdentitySource, SandboxPrincipal}; use openshell_core::proto::{ ExtensionServiceCredential, GetCurrentUserRequest, GetCurrentUserResponse, - GetSandboxConfigRequest, IssueSandboxTokenRequest, IssueSandboxTokenResponse, - RefreshSandboxTokenRequest, RefreshSandboxTokenResponse, Sandbox, + IssueSandboxTokenRequest, IssueSandboxTokenResponse, RefreshSandboxTokenRequest, + RefreshSandboxTokenResponse, Sandbox, }; use openshell_extension_core::{ExtensionAudience, ExtensionCallerKind, MAX_EXTENSION_TOKEN_TTL}; use std::collections::{HashMap, HashSet}; @@ -347,22 +347,10 @@ pub async fn handle_refresh_sandbox_token( "extension credential minting rate limit exceeded for this sandbox", )); } else { - let mut config_request = Request::new(GetSandboxConfigRequest { - supported_capabilities: vec![ - openshell_core::extension_protocol::POLICY_CEDAR_V1.to_string(), - ], - name: sandbox_record - .metadata - .as_ref() - .map_or_else(String::new, |metadata| metadata.name.clone()), - workspace_scope: None, - }); - config_request - .extensions_mut() - .insert(Principal::Sandbox(sandbox.clone())); - let available = super::policy::handle_get_sandbox_config(state, config_request) + // The refresh is already authenticated for this sandbox. The + // supervisor-facing capability gate does not apply to this read. + let available = super::policy::load_sandbox_config(state, &sandbox_record) .await? - .into_inner() .supervisor_middleware_services; mint_extension_credentials( issuer, @@ -938,6 +926,38 @@ mod tests { ); } + #[tokio::test] + async fn refresh_reads_middleware_services_from_a_placement_policy() { + use crate::grpc::test_support::{PLACEMENT_PROVIDER, store_credential_placement_fixture}; + + let state = state_with_issuer().await; + let policy = store_credential_placement_fixture(&state).await; + let mut sandbox = state + .store + .get_message::("sandbox-a") + .await + .expect("load sandbox") + .expect("sandbox"); + let spec = sandbox.spec.as_mut().expect("spec"); + spec.policy = Some(policy); + spec.providers = vec![PLACEMENT_PROVIDER.to_string()]; + state.store.put_message(&sandbox).await.unwrap(); + + let mut request = Request::new(RefreshSandboxTokenRequest { + extension_service_names: vec!["unknown-service".to_string()], + }); + request + .extensions_mut() + .insert(sandbox_principal("sandbox-a")); + authorize_refresh(&state, &mut request).await; + // The gateway's own configuration read must not apply the + // supervisor-facing capability gate; it reaches service selection. + let error = handle_refresh_sandbox_token(&state, request) + .await + .expect_err("unknown extension service must be rejected"); + assert_eq!(error.code(), tonic::Code::PermissionDenied, "{error:?}"); + } + #[tokio::test] async fn failed_refresh_does_not_consume_the_gateway_bearer() { let state = state_with_issuer().await; diff --git a/crates/openshell-server/src/grpc/mod.rs b/crates/openshell-server/src/grpc/mod.rs index 5bfb592196..7a7b0bb226 100644 --- a/crates/openshell-server/src/grpc/mod.rs +++ b/crates/openshell-server/src/grpc/mod.rs @@ -284,6 +284,8 @@ impl OpenShell for OpenShellService { Ok(Response::new(HealthResponse { status: ServiceStatus::Healthy.into(), version: openshell_core::VERSION.to_string(), + supported_policy_capabilities: + openshell_core::extension_protocol::gateway_policy_capabilities(), })) } @@ -1562,10 +1564,10 @@ pub mod test_support { supports_provider_readiness: false, redirected: false, supports_session_redirect: false, - supported_capabilities: openshell_core::extension_protocol::capabilities_if( - openshell_core::extension_protocol::POLICY_CEDAR_V1, - features == StreamFeatures::Apply, - ), + supported_capabilities: + openshell_core::extension_protocol::supervisor_policy_capabilities( + features == StreamFeatures::Apply, + ), })), }) .await @@ -1758,6 +1760,96 @@ pub mod test_support { ..Default::default() } } + + /// Provider attached by [`store_credential_placement_fixture`]. + pub const PLACEMENT_PROVIDER: &str = "work-api"; + + /// Store an endpointless provider profile and an attached-ready provider, + /// and return a policy binding its one static credential with a Bearer + /// placement at one endpoint and a raw `x-api-key` placement at another. + pub async fn store_credential_placement_fixture( + state: &ServerState, + ) -> openshell_core::proto::SandboxPolicy { + use openshell_core::proto::{ + NetworkAccessPreset, NetworkCredentialBinding, NetworkCredentialPlacement, + NetworkEndpoint, NetworkPolicyRule, Provider, ProviderProfile, ProviderProfileCategory, + ProviderProfileCredential, SandboxPolicy, datamodel::v1::ObjectMeta, + }; + + state + .store + .put_message(&crate::storage_proto::StoredProviderProfile { + metadata: Some(ObjectMeta { + id: "profile-shared-api".to_string(), + name: "shared-api".to_string(), + workspace: "default".to_string(), + ..Default::default() + }), + profile: Some(ProviderProfile { + id: "shared-api".to_string(), + display_name: "Shared API".to_string(), + category: ProviderProfileCategory::Other as i32, + credentials: vec![ProviderProfileCredential { + name: "api_key".to_string(), + env_vars: vec!["API_KEY".to_string()], + ..Default::default() + }], + ..Default::default() + }), + }) + .await + .unwrap(); + state + .store + .put_message(&Provider { + metadata: Some(ObjectMeta { + id: format!("provider-{PLACEMENT_PROVIDER}"), + name: PLACEMENT_PROVIDER.to_string(), + workspace: "default".to_string(), + ..Default::default() + }), + r#type: "shared-api".to_string(), + credentials: std::iter::once(("API_KEY".to_string(), "api-secret".to_string())) + .collect(), + profile_workspace: "default".to_string(), + ..Default::default() + }) + .await + .unwrap(); + + let endpoint = |host: &str, auth_style: &str, header_name: &str| NetworkEndpoint { + host: host.to_string(), + port: 443, + protocol: "rest".to_string(), + access: NetworkAccessPreset::Full as i32, + credential_binding: Some(NetworkCredentialBinding { + provider: PLACEMENT_PROVIDER.to_string(), + placement: Some(NetworkCredentialPlacement { + auth_style: auth_style.to_string(), + header_name: header_name.to_string(), + ..Default::default() + }), + }), + ..Default::default() + }; + let mut policy = SandboxPolicy { + network_policies: std::iter::once(( + "shared_api".to_string(), + NetworkPolicyRule { + name: "shared_api".to_string(), + endpoints: vec![ + endpoint("bearer.example.com", "bearer", "Authorization"), + endpoint("raw.example.com", "header", "x-api-key"), + ], + ..Default::default() + }, + )) + .collect(), + ..Default::default() + }; + openshell_policy::ensure_sandbox_process_identity(&mut policy); + policy + } } // --------------------------------------------------------------------------- diff --git a/crates/openshell-server/src/grpc/policy.rs b/crates/openshell-server/src/grpc/policy.rs index 3950e99424..2e72487544 100644 --- a/crates/openshell-server/src/grpc/policy.rs +++ b/crates/openshell-server/src/grpc/policy.rs @@ -2943,7 +2943,7 @@ pub fn require_policy_capabilities( if !openshell_core::extension_protocol::has_capability( &supported_capabilities, openshell_core::extension_protocol::POLICY_CREDENTIAL_BINDING_PLACEMENT_V1, - ) && policy.is_some_and(policy_has_credential_binding_placement) + ) && policy.is_some_and(openshell_policy::uses_credential_binding_placement) { return Err(Status::unimplemented( CREDENTIAL_BINDING_PLACEMENT_SUPPORT_REQUIRED, @@ -2954,19 +2954,6 @@ pub fn require_policy_capabilities( const CREDENTIAL_BINDING_PLACEMENT_SUPPORT_REQUIRED: &str = "credential_binding.placement requires a supervisor that enforces endpoint credential placement"; -fn policy_has_credential_binding_placement(policy: &ProtoSandboxPolicy) -> bool { - policy - .network_policies - .values() - .flat_map(|rule| &rule.endpoints) - .any(|endpoint| { - endpoint - .credential_binding - .as_ref() - .is_some_and(|binding| binding.placement.is_some()) - }) -} - /// Resolve the same effective configuration for authenticated RPCs and trusted /// readiness snapshots. Callers must authorize external access before entering. pub(super) async fn load_sandbox_config( @@ -5287,8 +5274,6 @@ pub(super) async fn handle_report_sandbox_configuration( .await .map_err(|e| Status::internal(format!("fetch sandbox failed: {e}")))? .ok_or_else(|| Status::not_found("sandbox not found"))?; - let sandbox_name = sandbox.object_name().to_string(); - let workspace = sandbox.object_workspace().to_string(); crate::compute::provisioning_deadline::refresh_configuration( &state.store, &mut sandbox, @@ -5322,18 +5307,11 @@ pub(super) async fn handle_report_sandbox_configuration( "supervisor configuration instance has changed", )); } + // The report is already authorized for this sandbox. Read the effective + // configuration directly: the supervisor-facing capability gate decides + // what a supervisor may receive, not what the gateway may compare. if reported == ConfigurationAdmissionState::Accepted { - let mut config_request = Request::new(GetSandboxConfigRequest { - supported_capabilities: vec![ - openshell_core::extension_protocol::POLICY_CEDAR_V1.to_string(), - ], - name: sandbox_name.clone(), - workspace_scope: Some(openshell_core::proto::workspace_selector(workspace.clone())), - }); - *config_request.extensions_mut() = request.extensions().clone(); - let config = handle_get_sandbox_config(state, config_request) - .await? - .into_inner(); + let config = load_sandbox_config(state, &sandbox).await?; if !config.configuration_admitted || !configuration_generation_matches(&admission, &config) { return Err(Status::aborted( @@ -5344,19 +5322,11 @@ pub(super) async fn handle_report_sandbox_configuration( } else if reported == ConfigurationAdmissionState::Rejected { // Runtime error strings may contain parser payloads. Only gateway-authored // diagnostics may be exposed verbatim through public sandbox status. - let mut config_request = Request::new(GetSandboxConfigRequest { - supported_capabilities: vec![ - openshell_core::extension_protocol::POLICY_CEDAR_V1.to_string(), - ], - workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), - name: sandbox_name, - }); - *config_request.extensions_mut() = request.extensions().clone(); - admission.error = match handle_get_sandbox_config(state, config_request).await { - Ok(config) if !configuration_generation_matches(&admission, config.get_ref()) => { + admission.error = match load_sandbox_config(state, &sandbox).await { + Ok(config) if !configuration_generation_matches(&admission, &config) => { return Err(Status::aborted("rejected configuration generation has changed")); } - Ok(config) if !config.get_ref().configuration_error.is_empty() => config.into_inner().configuration_error, + Ok(config) if !config.configuration_error.is_empty() => config.configuration_error, _ => "Effective configuration could not be activated; replace the policy or repair attached providers".to_string(), }; if let Some(current) = current @@ -15438,61 +15408,20 @@ mod tests { #[tokio::test] async fn provider_environment_delivers_endpoint_placements_to_capable_supervisors() { + use crate::grpc::test_support::{PLACEMENT_PROVIDER, store_credential_placement_fixture}; use openshell_core::proto::{ - GetSandboxProviderEnvironmentRequest, NetworkCredentialBinding, - NetworkCredentialPlacement, ProviderProfile, ProviderProfileCategory, + ConfigurationAdmissionState as Admission, GetSandboxConfigRequest, + GetSandboxProviderEnvironmentRequest, NetworkCredentialPlacement, + ReportSandboxConfigurationRequest, SandboxConfigurationAdmission, }; let state = test_server_state().await; - state - .store - .put_message(&StoredProviderProfile { - metadata: Some(openshell_core::proto::datamodel::v1::ObjectMeta { - id: "profile-shared-api".to_string(), - name: "shared-api".to_string(), - workspace: "default".to_string(), - ..Default::default() - }), - profile: Some(ProviderProfile { - id: "shared-api".to_string(), - display_name: "Shared API".to_string(), - category: ProviderProfileCategory::Other as i32, - credentials: vec![openshell_core::proto::ProviderProfileCredential { - name: "api_key".to_string(), - env_vars: vec!["API_KEY".to_string()], - ..Default::default() - }], - endpoints: Vec::new(), - ..Default::default() - }), - }) - .await - .unwrap(); - let mut provider = test_provider("work-api", "shared-api"); - provider.credentials = HashMap::from([("API_KEY".to_string(), "api-secret".to_string())]); - state.store.put_message(&provider).await.unwrap(); - + let policy = store_credential_placement_fixture(&state).await; let placement = |auth_style: &str, header_name: &str| NetworkCredentialPlacement { auth_style: auth_style.to_string(), header_name: header_name.to_string(), ..Default::default() }; - let mut policy = test_policy_with_rule("shared_api", "bearer.example.com"); - let rule = policy.network_policies.get_mut("shared_api").unwrap(); - rule.endpoints[0].protocol = "rest".to_string(); - rule.endpoints[0].access = openshell_core::proto::NetworkAccessPreset::Full as i32; - let mut raw = rule.endpoints[0].clone(); - raw.host = "raw.example.com".to_string(); - rule.endpoints[0].credential_binding = Some(NetworkCredentialBinding { - provider: "work-api".to_string(), - placement: Some(placement("bearer", "Authorization")), - }); - raw.credential_binding = Some(NetworkCredentialBinding { - provider: "work-api".to_string(), - placement: Some(placement("header", "x-api-key")), - }); - rule.endpoints.push(raw); - openshell_policy::ensure_sandbox_process_identity(&mut policy); assert!(require_policy_capabilities(Vec::new(), Some(&policy)).is_err()); assert!( @@ -15509,7 +15438,7 @@ mod tests { "sb-endpoint-placement", "endpoint-placement", policy, - vec!["work-api".to_string()], + vec![PLACEMENT_PROVIDER.to_string()], )) .await .unwrap(); @@ -15552,6 +15481,59 @@ mod tests { legacy.readiness_reason, ProviderReadinessReason::UnsupportedSupervisor as i32 ); + + // A capable supervisor's admission report is recorded. The gateway + // compares the generation with its own read, not a supervisor's view. + let sandbox_id = "sb-endpoint-placement"; + let instance_id = uuid::Uuid::new_v4().to_string(); + let report = |admission| { + with_sandbox( + Request::new(ReportSandboxConfigurationRequest { + sandbox_id: sandbox_id.to_string(), + admission: Some(admission), + expected_instance_id: String::new(), + }), + sandbox_id, + ) + }; + handle_report_sandbox_configuration( + &state, + report(SandboxConfigurationAdmission { + instance_id: instance_id.clone(), + state: Admission::Pending.into(), + ..Default::default() + }), + ) + .await + .unwrap(); + let config = handle_get_sandbox_config( + &state, + with_sandbox( + Request::new(GetSandboxConfigRequest { + name: "endpoint-placement".to_string(), + supported_capabilities: + openshell_core::extension_protocol::supervisor_policy_capabilities(false), + ..Default::default() + }), + sandbox_id, + ), + ) + .await + .unwrap() + .into_inner(); + assert!(config.configuration_admitted); + let accepted = SandboxConfigurationAdmission { + instance_id, + state: Admission::Accepted.into(), + policy_version: config.version, + policy_hash: config.policy_hash, + config_revision: config.config_revision, + provider_env_revision: config.provider_env_revision, + error: String::new(), + }; + handle_report_sandbox_configuration(&state, report(accepted)) + .await + .expect("capable supervisor acceptance must be recorded"); } #[tokio::test] diff --git a/crates/openshell-server/src/storage_proto.rs b/crates/openshell-server/src/storage_proto.rs index ed5b2468fd..d5957e91d8 100644 --- a/crates/openshell-server/src/storage_proto.rs +++ b/crates/openshell-server/src/storage_proto.rs @@ -252,7 +252,7 @@ mod tests { // The service backend HTTP version is part of both schemas. Legacy // endpoint records omit it and continue to use HTTP/1.1. const PUBLIC_RPC_SCHEMA_SHA256: &str = - "14ebaf33fdc17b0fdcf1226e611b3fb3641360cc66090fbef13aa006c27b670e"; + "7eccd2a087b810110d4aac9a3048b54ef1647c7fc89daffd837ae3f85488d18e"; // The storage.v2 refresh root adds retired handles and the first mint's // provider revision. All fields from the prior root retain their wire tags. const DURABLE_SCHEMA_SHA256: &str = diff --git a/crates/openshell-server/tests/common/mod.rs b/crates/openshell-server/tests/common/mod.rs index 71e3c6b0e6..e2d91e4b58 100644 --- a/crates/openshell-server/tests/common/mod.rs +++ b/crates/openshell-server/tests/common/mod.rs @@ -132,6 +132,7 @@ impl OpenShell for TestOpenShell { Ok(Response::new(HealthResponse { status: ServiceStatus::Healthy.into(), version: "test".to_string(), + supported_policy_capabilities: Vec::new(), })) } diff --git a/docs/how-it-works/policies/schema.mdx b/docs/how-it-works/policies/schema.mdx index f825a0e503..65a5e3bab3 100644 --- a/docs/how-it-works/policies/schema.mdx +++ b/docs/how-it-works/policies/schema.mdx @@ -171,7 +171,7 @@ the gateway host. | Field | Type | Default | Description | |---|---|---|---| | `credential_binding.provider` | string | None | Binds the static credentials of an attached provider whose profile defines no endpoints. Valid only in a sandbox policy. | -| `credential_binding.placement` | object | Profile placement | Request location for the bound credentials at this endpoint only. Takes `auth_style` and the matching `header_name`, `query_param`, or `path_template`, with the same meanings as in a provider profile. Cannot be combined with `credential_signing`. | +| `credential_binding.placement` | object | Profile placement | Request location for the bound credentials at this endpoint only. Takes `auth_style` and the matching `header_name`, `query_param`, or `path_template`, with the same meanings as in a provider profile, and also fixes the header value form. Requires a gateway that supports it. Cannot be combined with `credential_signing`. | | `request_body_credential_rewrite` | bool | `false` | Replaces ordinary static credential placeholders in REST bodies, including those with declared HTTP placement. | | `websocket_credential_rewrite` | bool | `false` | Replaces ordinary static credential placeholders in client WebSocket text messages, including those with declared HTTP placement. Requires `protocol: websocket`. | | `allow_uninspected_credentials` | bool | `false` | Allows a provider-credentialed endpoint to omit request inspection or use `tls: skip`. | diff --git a/docs/how-it-works/providers/profiles.mdx b/docs/how-it-works/providers/profiles.mdx index a243171308..6607a326ce 100644 --- a/docs/how-it-works/providers/profiles.mdx +++ b/docs/how-it-works/providers/profiles.mdx @@ -199,13 +199,21 @@ network_policies: ``` `placement` accepts the profile `auth_style` values and requires the field -that style uses. Fields for other styles are rejected. Without `placement`, the -endpoint uses each credential's profile placement. The placement applies to -every static credential the provider supplies at that endpoint. Bindings of -one provider whose host, port, and path can match the same request must use the -same placement; OpenShell rejects the policy update otherwise. Supervisors that -do not enforce binding placement do not receive the policy or the affected -credentials. +that style uses. Fields for other styles are rejected. Unlike a profile +placement, a binding placement also fixes the header value form: `bearer` +accepts only `Bearer `, `header` only the bare placeholder, and +`basic` only an `Authorization: Basic` value. Without `placement`, the endpoint +uses each credential's profile placement. The placement applies to every static +credential the provider supplies at that endpoint. + +Bindings of one provider whose host, port, and path can match the same request +must use the same placement; OpenShell rejects the policy update otherwise. A +`/v1/**` path also matches `/v1`. + +Upgrade every gateway replica before using `placement`. An older gateway drops +the field and applies the profile placement, so the CLI refuses to submit such a +policy to a gateway that does not advertise support. Supervisors that do not +enforce binding placement do not receive the policy or the affected credentials. For AWS endpoints, the binding and signing fields have separate jobs. `credential_binding.provider` selects the provider instance that supplies diff --git a/proto/openshell.proto b/proto/openshell.proto index 113e943cf4..a009afb1be 100644 --- a/proto/openshell.proto +++ b/proto/openshell.proto @@ -1076,6 +1076,12 @@ message HealthResponse { // Service version. string version = 2; + + // Versioned policy features this gateway accepts and preserves, such as + // "openshell.policy.credential-binding-placement.v1". Clients check it + // before submitting a policy that uses one, because an older gateway + // silently drops fields it does not know. + repeated string supported_policy_capabilities = 3; } // Current-user request. The identity comes from the authenticated request. From 8362b6e8046223925aa4b7a3b45c9ed2d1ef8ee0 Mon Sep 17 00:00:00 2001 From: Mrunal Patel Date: Wed, 2 Dec 2026 19:39:41 +0000 Subject: [PATCH 3/6] fix(policy): align placement overlap with runtime credential matchers - Check overlapping bindings of one provider with host and path matchers that follow HostPattern and EndpointPathPattern: host labels are globs that never cross a dot, a "**" label matches one or more labels, and "/**" is a literal prefix subtree. Run this check even when the request-pipeline host check reports no overlap. - Classify header rewrite failures with the same form-aware resolver used for the lookup, so an expired credential in a correctly formed header is reported as unavailable rather than a placement mismatch. Refs #5963 Signed-off-by: Mrunal Patel --- .../src/provider_credentials.rs | 55 ++++ crates/openshell-core/src/secrets.rs | 15 +- crates/openshell-policy/src/ambiguity.rs | 243 ++++++++++++++++-- 3 files changed, 282 insertions(+), 31 deletions(-) diff --git a/crates/openshell-core/src/provider_credentials.rs b/crates/openshell-core/src/provider_credentials.rs index fa6ae718b5..f716fdc860 100644 --- a/crates/openshell-core/src/provider_credentials.rs +++ b/crates/openshell-core/src/provider_credentials.rs @@ -2164,6 +2164,61 @@ mod tests { } } + #[test] + fn expired_credential_in_a_correct_header_form_is_not_a_placement_mismatch() { + use base64::Engine as _; + let now_ms = i64::try_from( + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_millis(), + ) + .unwrap(); + let mut bound = binding("unused.example.com", 443, "/**"); + bound.endpoints = vec![ + endpoint( + "bearer.example.com", + "/**", + Some(("bearer", "Authorization")), + ), + endpoint("raw.example.com", "/**", Some(("header", "x-api-key"))), + endpoint("basic.example.com", "/**", Some(("basic", ""))), + ]; + let state = ProviderCredentialState::from_bound_environment( + 7, + HashMap::from([("API_KEY".into(), "synthetic".into())]), + HashMap::from([("API_KEY".into(), now_ms - 1)]), + HashMap::new(), + HashMap::from([("API_KEY".into(), bound)]), + vec![], + ) + .unwrap(); + let reference = state.snapshot().child_env["API_KEY"].clone(); + let basic = format!( + "Basic {}", + base64::engine::general_purpose::STANDARD.encode(format!("user:{reference}")) + ); + for (host, header, value) in [ + ( + "bearer.example.com", + "Authorization", + format!("Bearer {reference}"), + ), + ("raw.example.com", "x-api-key", reference), + ("basic.example.com", "Authorization", basic), + ] { + let error = state + .resolver_for_endpoint(host, 443, "/") + .unwrap() + .rewrite_header_value_for_name(header, &value) + .expect_err("expired credential must not resolve"); + assert!( + !error.is_placement_mismatch() && !error.is_endpoint_mismatch(), + "{host}: expired credential must be reported as unavailable: {error:?}" + ); + } + } + #[test] fn endpoint_placement_replacement_rebinds_without_a_second_value() { let state = multi_endpoint_state( diff --git a/crates/openshell-core/src/secrets.rs b/crates/openshell-core/src/secrets.rs index d70844bd46..a1c02cdfcf 100644 --- a/crates/openshell-core/src/secrets.rs +++ b/crates/openshell-core/src/secrets.rs @@ -933,11 +933,11 @@ impl SecretResolver { &self, value: &str, ) -> Result, UnresolvedPlaceholderError> { + // Each form classifies its own failures, so an unavailable credential + // in a correctly formed header is not reported as a placement mismatch. + let raw = self.with_header_form(HeaderValueForm::Raw); // Direct placeholder match: `x-api-key: openshell:resolve:env:KEY` - if let Some(secret) = self - .with_header_form(HeaderValueForm::Raw) - .resolve_placeholder(value.trim()) - { + if let Some(secret) = raw.resolve_placeholder(value.trim()) { return Ok(Some(secret.to_string())); } @@ -956,7 +956,7 @@ impl SecretResolver { // Prefixed placeholder: `Bearer openshell:resolve:env:KEY` let Some(split_at) = trimmed.find(char::is_whitespace) else { if contains_reserved_credential_marker(trimmed) { - return Err(self.unresolved_for("header", trimmed)); + return Err(raw.unresolved_for("header", trimmed)); } return Ok(None); }; @@ -967,12 +967,13 @@ impl SecretResolver { } else { HeaderValueForm::OtherScheme }; - if let Some(secret) = self.with_header_form(form).resolve_placeholder(candidate) { + let prefixed = self.with_header_form(form); + if let Some(secret) = prefixed.resolve_placeholder(candidate) { return Ok(Some(format!("{prefix} {secret}"))); } if contains_reserved_credential_marker(candidate) { - return Err(self.unresolved_for("header", candidate)); + return Err(prefixed.unresolved_for("header", candidate)); } Ok(None) diff --git a/crates/openshell-policy/src/ambiguity.rs b/crates/openshell-policy/src/ambiguity.rs index 9b55db37af..c4e4201a95 100644 --- a/crates/openshell-policy/src/ambiguity.rs +++ b/crates/openshell-policy/src/ambiguity.rs @@ -85,28 +85,32 @@ pub fn find_endpoint_ambiguities(policy: &SandboxPolicy) -> Vec bool { runtime_path_patterns_overlap(left, right) } -/// Overlap as static credential binding paths match at runtime, where a -/// trailing `/**` also selects the named path itself (`/v1/**` matches `/v1`). +/// Whether two credential binding hosts can match one request host, using the +/// semantics of `openshell_core::host_pattern::HostPattern`: each DNS label is +/// a case-insensitive glob (`*`, `?`, `[...]`) that never crosses a `.`, and a +/// label that is exactly `**` matches one or more labels. +fn credential_host_patterns_overlap(left: &str, right: &str) -> bool { + enum Label { + Recursive, + Glob(Vec), + } + let labels = |pattern: &str| { + pattern + .to_ascii_lowercase() + .split('.') + .map(|label| { + if label == "**" { + Some(Label::Recursive) + } else { + tokenize_runtime_path_glob(label).map(Label::Glob) + } + }) + .collect::>>() + }; + if left.is_empty() || right.is_empty() { + return true; + } + let (Some(left), Some(right)) = (labels(left), labels(right)) else { + // Invalid host patterns are rejected elsewhere; stay conservative. + return true; + }; + + // Product search over label positions. A recursive label consumes the + // other side's label and may either stay active or finish, so it always + // consumes at least one label. + let mut queue = VecDeque::from([(0_usize, 0_usize)]); + let mut seen = HashSet::new(); + while let Some((i, j)) = queue.pop_front() { + if !seen.insert((i, j)) { + continue; + } + if i == left.len() && j == right.len() { + return true; + } + let (Some(l), Some(r)) = (left.get(i), right.get(j)) else { + continue; + }; + let shares_label = match (l, r) { + (Label::Glob(l), Label::Glob(r)) => token_languages_overlap(l, r, '.'), + _ => true, + }; + if !shares_label { + continue; + } + queue.push_back((i + 1, j + 1)); + if matches!(l, Label::Recursive) { + queue.push_back((i, j + 1)); + } + if matches!(r, Label::Recursive) { + queue.push_back((i + 1, j)); + } + } + false +} + +/// Whether two credential binding paths can match one request path, using the +/// semantics of `openshell_core::endpoint_path::EndpointPathPattern`: an empty +/// path, `**`, or `/**` matches everything; `/**` matches the literal +/// prefix and its descendants; other paths are globs that also match their own +/// source text. fn credential_path_patterns_overlap(left: &str, right: &str) -> bool { - let variants = |pattern: &str| { - let subtree_root = pattern - .strip_suffix("/**") - .filter(|prefix| !prefix.is_empty()); - std::iter::once(pattern.to_string()) - .chain(subtree_root.map(str::to_string)) - .collect::>() + let literal = |text: &str| text.chars().map(GlobToken::Literal).collect::>(); + let languages = |pattern: &str| -> Option>> { + if pattern.is_empty() || pattern == "**" || pattern == "/**" { + return None; + } + if let Some(prefix) = pattern.strip_suffix("/**") { + let mut descendants = literal(prefix); + descendants.push(GlobToken::Literal('/')); + descendants.push(GlobToken::Star { + crosses_delimiter: true, + }); + return Some(vec![literal(prefix), descendants]); + } + let mut languages = vec![literal(pattern)]; + languages.extend(tokenize_runtime_path_glob(pattern)); + Some(languages) + }; + let (Some(left), Some(right)) = (languages(left), languages(right)) else { + return true; }; - variants(left).iter().any(|left| { - variants(right) + left.iter().any(|left| { + right .iter() - .any(|right| path_patterns_overlap(left, right)) + .any(|right| token_languages_overlap(left, right, '/')) }) } @@ -1045,6 +1127,23 @@ mod tests { bound("api.example.com", "/v1", None), bound("api.example.com", "/v1/**", Some("x-api-key")), ), + // Host labels are globs, so `?` matches one character. + ( + bound("api?.example.com", "", None), + bound("api1.example.com", "", Some("x-api-key")), + ), + ( + bound("api[0-9].example.com", "", None), + bound("api7.example.com", "", Some("x-api-key")), + ), + ( + bound("**.example.com", "", None), + bound("a.b.example.com", "", Some("x-api-key")), + ), + ( + bound("api.example.com", "/v*", None), + bound("api.example.com", "/v1/users", Some("x-api-key")), + ), ] { let ambiguities = find_endpoint_ambiguities(&policy_with(left, right)); assert_eq!(ambiguities.len(), 1); @@ -1073,11 +1172,107 @@ mod tests { bound("api.example.com", "/v1", None), bound("api.example.com", "/v10/**", Some("x-api-key")), ), + // A subtree prefix is literal at runtime: `/v*/**` matches only + // `/v*` and its descendants. + ( + bound("api.example.com", "/v*/**", None), + bound("api.example.com", "/v1", Some("x-api-key")), + ), + ( + bound("**.example.com", "", None), + bound("example.com", "", Some("x-api-key")), + ), + ( + bound("api?.example.com", "", None), + bound("api12.example.com", "", Some("x-api-key")), + ), ] { assert!(find_endpoint_ambiguities(&policy_with(left, right)).is_empty()); } } + #[test] + fn credential_overlap_never_misses_a_runtime_match() { + use openshell_core::endpoint_path::EndpointPathPattern; + use openshell_core::host_pattern::HostPattern; + + let hosts = [ + "api.example.com", + "api?.example.com", + "api[0-9].example.com", + "*.example.com", + "**.example.com", + "api*.example.com", + "a.**.com", + "API1.Example.com", + ]; + let host_samples = [ + "api.example.com", + "api1.example.com", + "api12.example.com", + "a.b.example.com", + "example.com", + "a.x.y.com", + ]; + for left in hosts { + for right in hosts { + let (l, r) = ( + HostPattern::new(left).unwrap(), + HostPattern::new(right).unwrap(), + ); + if host_samples + .iter() + .any(|host| l.matches(host) && r.matches(host)) + { + assert!( + credential_host_patterns_overlap(left, right), + "{left} / {right}" + ); + } + } + } + + let paths = [ + "", + "/**", + "/v1", + "/v1/**", + "/v*", + "/v*/**", + "/v?", + "/v[0-9]/users", + "/v1/*", + "/**/admin", + ]; + let path_samples = [ + "/v1", + "/v1/users", + "/v*", + "/v*/x", + "/v2", + "/v10", + "/v1/admin", + "/x/admin", + ]; + for left in paths { + for right in paths { + let (l, r) = ( + EndpointPathPattern::new(left), + EndpointPathPattern::new(right), + ); + if path_samples + .iter() + .any(|path| l.matches(path) && r.matches(path)) + { + assert!( + credential_path_patterns_overlap(left, right), + "{left} / {right}" + ); + } + } + } + } + #[test] fn json_rpc_body_limit_is_compared_only_within_the_same_protocol() { let mut json_rpc = endpoint("api.example.com", 443); From 655c9fcc76c5e640e438846891aeaacf857ebd6b Mon Sep 17 00:00:00 2001 From: Mrunal Patel Date: Wed, 2 Dec 2026 20:14:40 +0000 Subject: [PATCH 4/6] fix(policy): close remaining credential placement gaps - Answer exact credential binding paths and hosts with the runtime matcher, model "**/" as whole path components, and treat selectors the overlap check cannot model as overlapping. - Deny explicitly placed credentials in request-body and WebSocket rewriting and in trusted signing lookups. Profile placements keep honoring the endpoint's rewrite options. - Deliver a placement-bearing policy to a polling supervisor without the placement capability as an unadmitted configuration, so it applies its policy validation failure mode instead of retrying with its previous placement. Refs #5963 Signed-off-by: Mrunal Patel --- .../src/provider_credentials.rs | 87 ++++++++++- crates/openshell-core/src/secrets.rs | 30 +++- crates/openshell-policy/src/ambiguity.rs | 144 +++++++++++++++--- crates/openshell-server/src/grpc/policy.rs | 71 +++++++-- docs/how-it-works/providers/profiles.mdx | 15 +- 5 files changed, 309 insertions(+), 38 deletions(-) diff --git a/crates/openshell-core/src/provider_credentials.rs b/crates/openshell-core/src/provider_credentials.rs index f716fdc860..4e30f0ecc5 100644 --- a/crates/openshell-core/src/provider_credentials.rs +++ b/crates/openshell-core/src/provider_credentials.rs @@ -710,11 +710,18 @@ impl ProviderCredentialState { }; let mut allowed = HashSet::new(); let mut placements = HashMap::new(); + let mut explicit_placement_keys = HashSet::new(); for (key, binding) in &inner.static_credential_bindings { match endpoint_placement(binding, &host_labels, port, &request_path) { - EndpointPlacement::Authorized(placement) => { + EndpointPlacement::Authorized { + placement, + explicit, + } => { allowed.insert(key.clone()); placements.insert(key.clone(), placement.clone()); + if explicit { + explicit_placement_keys.insert(key.clone()); + } } // Bindings that disagree on placement for one request select // no location, so the credential is not resolved. @@ -766,7 +773,8 @@ impl ProviderCredentialState { &inner.known_static_credential_keys, &allowed, revision_fallback_allowed_revisions, - ); + ) + .with_explicit_placement_keys(explicit_placement_keys); // Attributed to the same snapshot as `revision` above. Arc::new(self.track_resolver(scoped, &inner)) }); @@ -1672,7 +1680,11 @@ fn binding_error(message: &str) -> StaticCredentialBindingError { } enum EndpointPlacement<'a> { - Authorized(&'a CredentialPlacement), + Authorized { + placement: &'a CredentialPlacement, + /// Some matching endpoint binding set this placement itself. + explicit: bool, + }, Conflicting, Unbound, } @@ -1686,10 +1698,12 @@ fn endpoint_placement<'a>( path: &str, ) -> EndpointPlacement<'a> { let mut selected = None; + let mut explicit = false; for endpoint in &binding.endpoints { if !static_credential_endpoint_matches(endpoint, host_labels, port, path) { continue; } + explicit |= endpoint.placement.is_some(); let placement = endpoint.placement.as_ref().unwrap_or(&binding.placement); match selected { None => selected = Some(placement), @@ -1697,7 +1711,12 @@ fn endpoint_placement<'a>( Some(_) => return EndpointPlacement::Conflicting, } } - selected.map_or(EndpointPlacement::Unbound, EndpointPlacement::Authorized) + selected.map_or(EndpointPlacement::Unbound, |placement| { + EndpointPlacement::Authorized { + placement, + explicit, + } + }) } fn static_credential_endpoint_matches( @@ -2219,6 +2238,66 @@ mod tests { } } + #[test] + fn explicit_placement_excludes_payload_rewriting_and_signing() { + let state = multi_endpoint_state( + vec![ + endpoint("explicit.example.com", "/**", Some(("header", "x-api-key"))), + endpoint("profile.example.com", "/**", None), + ], + HashMap::new(), + ); + let reference = state.snapshot().child_env["API_KEY"].clone(); + let explicit = state + .resolver_for_endpoint("explicit.example.com", 443, "/") + .unwrap(); + assert_eq!( + explicit + .rewrite_header_value_for_name("x-api-key", &reference) + .unwrap(), + Some("synthetic".into()) + ); + let mut body = format!("{{\"key\":\"{reference}\"}}"); + assert!( + explicit + .rewrite_text_placeholders(&mut body, "body") + .unwrap_err() + .is_placement_mismatch() + ); + let mut message = reference.clone(); + assert!( + explicit + .rewrite_websocket_text_placeholders(&mut message) + .unwrap_err() + .is_placement_mismatch() + ); + assert!( + explicit + .resolve_current_env_key_checked("API_KEY", "sigv4") + .unwrap_err() + .is_placement_mismatch() + ); + + // Profile placement keeps honoring explicit endpoint rewrite policy. + let profile = state + .resolver_for_endpoint("profile.example.com", 443, "/") + .unwrap(); + let mut body = format!("{{\"key\":\"{reference}\"}}"); + assert_eq!( + profile + .rewrite_text_placeholders(&mut body, "body") + .unwrap(), + 1 + ); + assert!(body.contains("synthetic")); + assert_eq!( + profile + .resolve_current_env_key_checked("API_KEY", "sigv4") + .unwrap(), + Some("synthetic") + ); + } + #[test] fn endpoint_placement_replacement_rebinds_without_a_second_value() { let state = multi_endpoint_state( diff --git a/crates/openshell-core/src/secrets.rs b/crates/openshell-core/src/secrets.rs index a1c02cdfcf..266e7db4db 100644 --- a/crates/openshell-core/src/secrets.rs +++ b/crates/openshell-core/src/secrets.rs @@ -258,6 +258,10 @@ pub struct SecretResolver { request_location: Option, /// Value form of the header currently being rewritten, if any. header_form: Option, + /// Keys whose placement an endpoint binding set explicitly. They resolve + /// only at that placement: never in rewritten bodies, WebSocket messages, + /// or trusted signing. + explicit_placement_keys: HashSet, denied_env_keys: HashSet, identity_bound_env_keys: HashSet, revision_fallback_allowed_revisions: HashMap>>, @@ -537,6 +541,7 @@ impl SecretResolver { placements: HashMap::new(), request_location: None, header_form: None, + explicit_placement_keys: HashSet::new(), denied_env_keys: HashSet::new(), identity_bound_env_keys: HashSet::new(), revision_fallback_allowed_revisions: HashMap::new(), @@ -597,6 +602,7 @@ impl SecretResolver { placements: HashMap::new(), request_location: None, header_form: None, + explicit_placement_keys: HashSet::new(), denied_env_keys: HashSet::new(), identity_bound_env_keys: HashSet::new(), revision_fallback_allowed_revisions: HashMap::new(), @@ -609,12 +615,14 @@ impl SecretResolver { pub fn merge<'a>(resolvers: impl IntoIterator) -> Option { let mut by_placeholder = HashMap::new(); let mut placements = HashMap::new(); + let mut explicit_placement_keys = HashSet::new(); let mut denied_env_keys = HashSet::new(); let mut identity_bound_env_keys = HashSet::new(); let mut revision_fallback_allowed_revisions = HashMap::new(); for resolver in resolvers { by_placeholder.extend(resolver.by_placeholder.clone()); placements.extend(resolver.placements.clone()); + explicit_placement_keys.extend(resolver.explicit_placement_keys.iter().cloned()); denied_env_keys.extend(resolver.denied_env_keys.iter().cloned()); identity_bound_env_keys.extend(resolver.identity_bound_env_keys.iter().cloned()); revision_fallback_allowed_revisions @@ -629,6 +637,7 @@ impl SecretResolver { placements, request_location: None, header_form: None, + explicit_placement_keys, denied_env_keys, identity_bound_env_keys, revision_fallback_allowed_revisions, @@ -667,6 +676,7 @@ impl SecretResolver { placements: self.placements.clone(), request_location: None, header_form: None, + explicit_placement_keys: self.explicit_placement_keys.clone(), denied_env_keys, identity_bound_env_keys: bound_keys.clone(), revision_fallback_allowed_revisions, @@ -683,6 +693,12 @@ impl SecretResolver { self } + /// Mark keys whose placement an endpoint binding set explicitly. + pub(crate) fn with_explicit_placement_keys(mut self, keys: HashSet) -> Self { + self.explicit_placement_keys = keys; + self + } + /// Select the actual structured request destination before resolving input. #[must_use] pub fn with_request_location(&self, location: RequestCredentialLocation) -> Self { @@ -717,8 +733,10 @@ impl SecretResolver { self.request_location, Some(RequestCredentialLocation::Body | RequestCredentialLocation::WebSocket) ) { - // Only explicit endpoint-policy rewrite wrappers choose these contexts. - return true; + // Only explicit endpoint-policy rewrite wrappers choose these + // contexts. A binding placement names the one location its + // credential may appear, which excludes payload rewriting. + return !self.explicit_placement_keys.contains(key); } let Some(placement) = self.placements.get(key) else { return matches!(self.request_location.as_ref(), Some(RequestCredentialLocation::Header(name)) if name.eq_ignore_ascii_case("authorization")); @@ -881,6 +899,14 @@ impl SecretResolver { reason: UnresolvedPlaceholderReason::EndpointMismatch, }); } + // Trusted transforms such as signing place the value themselves, which + // an explicit binding placement does not authorize. + if self.explicit_placement_keys.contains(key) { + return Err(UnresolvedPlaceholderError { + location, + reason: UnresolvedPlaceholderReason::PlacementMismatch, + }); + } let placeholder = placeholder_for_env_key(key); let resolved = self .by_placeholder diff --git a/crates/openshell-policy/src/ambiguity.rs b/crates/openshell-policy/src/ambiguity.rs index c4e4201a95..60fc8d226c 100644 --- a/crates/openshell-policy/src/ambiguity.rs +++ b/crates/openshell-policy/src/ambiguity.rs @@ -3,6 +3,8 @@ //! Validation for endpoint selectors whose policy-derived behavior conflicts. +use openshell_core::endpoint_path::EndpointPathPattern; +use openshell_core::host_pattern::HostPattern; use openshell_core::proto::{ NetworkCredentialPlacement, NetworkEndpoint, NetworkEnforcementMode, NetworkTlsMode, SandboxPolicy, @@ -475,6 +477,13 @@ fn credential_host_patterns_overlap(left: &str, right: &str) -> bool { if left.is_empty() || right.is_empty() { return true; } + // An exact host selects one request host, so the runtime matcher answers + // the question directly. + for (exact, other) in [(left, right), (right, left)] { + if !exact.contains(['*', '?', '[']) { + return HostPattern::new(other).map_or(true, |pattern| pattern.matches(exact)); + } + } let (Some(left), Some(right)) = (labels(left), labels(right)) else { // Invalid host patterns are rejected elsewhere; stay conservative. return true; @@ -517,26 +526,19 @@ fn credential_host_patterns_overlap(left: &str, right: &str) -> bool { /// semantics of `openshell_core::endpoint_path::EndpointPathPattern`: an empty /// path, `**`, or `/**` matches everything; `/**` matches the literal /// prefix and its descendants; other paths are globs that also match their own -/// source text. +/// source text. A selector that cannot be modeled is treated as overlapping. fn credential_path_patterns_overlap(left: &str, right: &str) -> bool { - let literal = |text: &str| text.chars().map(GlobToken::Literal).collect::>(); - let languages = |pattern: &str| -> Option>> { - if pattern.is_empty() || pattern == "**" || pattern == "/**" { - return None; - } - if let Some(prefix) = pattern.strip_suffix("/**") { - let mut descendants = literal(prefix); - descendants.push(GlobToken::Literal('/')); - descendants.push(GlobToken::Star { - crosses_delimiter: true, - }); - return Some(vec![literal(prefix), descendants]); + // An exact path selects one request path, so the runtime matcher answers + // the question directly. + for (exact, other) in [(left, right), (right, left)] { + if !exact.is_empty() && !exact.contains(['*', '?', '[']) { + return EndpointPathPattern::new(other).matches(exact); } - let mut languages = vec![literal(pattern)]; - languages.extend(tokenize_runtime_path_glob(pattern)); - Some(languages) - }; - let (Some(left), Some(right)) = (languages(left), languages(right)) else { + } + let (Some(left), Some(right)) = ( + credential_path_languages(left), + credential_path_languages(right), + ) else { return true; }; left.iter().any(|left| { @@ -546,6 +548,72 @@ fn credential_path_patterns_overlap(left: &str, right: &str) -> bool { }) } +/// Token sequences whose union is the request paths a credential binding path +/// selects, or `None` when the selector matches everything or cannot be +/// modeled. +fn credential_path_languages(pattern: &str) -> Option>> { + const MAX_RECURSIVE_COMPONENTS: usize = 6; + let literal = |text: &str| text.chars().map(GlobToken::Literal).collect::>(); + if pattern.is_empty() || pattern == "**" || pattern == "/**" { + return None; + } + if let Some(prefix) = pattern.strip_suffix("/**") { + let mut descendants = literal(prefix); + descendants.push(GlobToken::Literal('/')); + descendants.push(GlobToken::Star { + crosses_delimiter: true, + }); + return Some(vec![literal(prefix), descendants]); + } + + // A `**/` component matches zero or more whole components, so it is + // either absent or any text ending in `/`. Expand each occurrence. + let mut pieces = vec![String::new()]; + let mut rest = pattern; + while let Some(index) = rest.find("**/") { + let aligned = index == 0 || rest[..index].ends_with('/'); + let (before, after) = rest.split_at(index + 3); + pieces.last_mut()?.push_str(&before[..index]); + if aligned { + pieces.push(String::new()); + } else { + pieces.last_mut()?.push_str("**/"); + } + rest = after; + } + pieces.last_mut()?.push_str(rest); + if pieces.len() - 1 > MAX_RECURSIVE_COMPONENTS { + return None; + } + let pieces = pieces + .iter() + .map(|piece| tokenize_runtime_path_glob(piece)) + .collect::>>()?; + + let mut languages = vec![Vec::new()]; + for (index, piece) in pieces.into_iter().enumerate() { + if index > 0 { + let mut expanded = Vec::with_capacity(languages.len() * 2); + for language in languages { + let mut components = language.clone(); + components.push(GlobToken::Star { + crosses_delimiter: true, + }); + components.push(GlobToken::Literal('/')); + expanded.push(language); + expanded.push(components); + } + languages = expanded; + } + for language in &mut languages { + language.extend(piece.iter().cloned()); + } + } + // The runtime also matches a selector's own text exactly. + languages.push(literal(pattern)); + Some(languages) +} + /// Match the runtime route-selection rank used by `L7EndpointConfig`. /// /// Overlapping endpoints with different ranks do not compete for request @@ -1144,6 +1212,15 @@ mod tests { bound("api.example.com", "/v*", None), bound("api.example.com", "/v1/users", Some("x-api-key")), ), + // A character class whose first member is `]` still contains `a`. + ( + bound("api.example.com", "/docs/[]a]", None), + bound("api.example.com", "/docs/a", Some("x-api-key")), + ), + ( + bound("api.example.com", "/a/**/b", None), + bound("api.example.com", "/a/x/y/b", Some("x-api-key")), + ), ] { let ambiguities = find_endpoint_ambiguities(&policy_with(left, right)); assert_eq!(ambiguities.len(), 1); @@ -1186,6 +1263,15 @@ mod tests { bound("api?.example.com", "", None), bound("api12.example.com", "", Some("x-api-key")), ), + // `**/` matches whole components, so it cannot match `x` in `xb`. + ( + bound("api.example.com", "/a/**/b", None), + bound("api.example.com", "/a/xb", Some("x-api-key")), + ), + ( + bound("api.example.com", "/a/**/b", None), + bound("api.example.com", "/a/*c", Some("x-api-key")), + ), ] { assert!(find_endpoint_ambiguities(&policy_with(left, right)).is_empty()); } @@ -1243,6 +1329,12 @@ mod tests { "/v[0-9]/users", "/v1/*", "/**/admin", + "/a/**/b", + "/a/xb", + "/a/*b", + "/docs/[]a]", + "/docs/a", + "/docs/[!a]", ]; let path_samples = [ "/v1", @@ -1253,6 +1345,14 @@ mod tests { "/v10", "/v1/admin", "/x/admin", + "/admin", + "/a/b", + "/a/xb", + "/a/x/b", + "/a/x/y/b", + "/docs/a", + "/docs/]", + "/docs/b", ]; for left in paths { for right in paths { @@ -1269,6 +1369,14 @@ mod tests { "{left} / {right}" ); } + // An exact selector is answered by the runtime matcher itself. + if !left.is_empty() && !left.contains(['*', '?', '[']) { + assert_eq!( + credential_path_patterns_overlap(left, right), + r.matches(left), + "{left} / {right}" + ); + } } } } diff --git a/crates/openshell-server/src/grpc/policy.rs b/crates/openshell-server/src/grpc/policy.rs index 2e72487544..7159a166cb 100644 --- a/crates/openshell-server/src/grpc/policy.rs +++ b/crates/openshell-server/src/grpc/policy.rs @@ -2916,19 +2916,48 @@ async fn handle_get_sandbox_config_inner( .await?; let config = load_sandbox_config(state, &sandbox).await?; if matches!(principal, Principal::Sandbox(_)) { + if placement_capability_missing(&req.supported_capabilities, config.policy.as_ref()) { + return Ok(Response::new(unsupported_placement_config(config))); + } require_policy_capabilities(req.supported_capabilities, config.policy.as_ref())?; } Ok(Response::new(config)) } +/// Deliver a placement-bearing policy to a polling supervisor that cannot +/// enforce it as a configuration that is not admitted, as push delivery does. +/// Supervisors treat an RPC error as transient and would keep their previous +/// policy and credentials, including the old placement; an unadmitted +/// configuration applies their configured validation failure mode instead. +fn unsupported_placement_config(config: GetSandboxConfigResponse) -> GetSandboxConfigResponse { + GetSandboxConfigResponse { + policy: None, + supervisor_middleware_services: Vec::new(), + configuration_admitted: false, + configuration_error: CREDENTIAL_BINDING_PLACEMENT_SUPPORT_REQUIRED.to_string(), + ..config + } +} + +fn placement_capability_missing( + supported_capabilities: &[String], + policy: Option<&ProtoSandboxPolicy>, +) -> bool { + !openshell_core::extension_protocol::has_capability( + supported_capabilities, + openshell_core::extension_protocol::POLICY_CREDENTIAL_BINDING_PLACEMENT_V1, + ) && policy.is_some_and(openshell_policy::uses_credential_binding_placement) +} + const CEDAR_SUPPORT_REQUIRED: &str = "Cedar policy requires a supervisor with Cedar support"; -/// Refuses a Cedar policy to a supervisor that did not report Cedar support. +/// Refuses a policy that needs a capability the supervisor did not report. /// -/// Callers must not answer with an empty compatibility configuration -/// instead: an older supervisor might treat it as a usable YAML +/// Callers must not answer a Cedar policy with an empty compatibility +/// configuration instead: an older supervisor might treat it as a usable YAML /// configuration. Pushed configuration delivers the refusal as a -/// configuration that is not admitted. +/// configuration that is not admitted, and polling delivers a missing +/// placement capability the same way. pub fn require_policy_capabilities( supported_capabilities: Vec, policy: Option<&ProtoSandboxPolicy>, @@ -2940,11 +2969,7 @@ pub fn require_policy_capabilities( { return Err(Status::unimplemented(CEDAR_SUPPORT_REQUIRED)); } - if !openshell_core::extension_protocol::has_capability( - &supported_capabilities, - openshell_core::extension_protocol::POLICY_CREDENTIAL_BINDING_PLACEMENT_V1, - ) && policy.is_some_and(openshell_policy::uses_credential_binding_placement) - { + if placement_capability_missing(&supported_capabilities, policy) { return Err(Status::unimplemented( CREDENTIAL_BINDING_PLACEMENT_SUPPORT_REQUIRED, )); @@ -15534,6 +15559,34 @@ mod tests { handle_report_sandbox_configuration(&state, report(accepted)) .await .expect("capable supervisor acceptance must be recorded"); + + // A polling supervisor without the capability receives a + // configuration that is not admitted, so it applies its validation + // failure mode instead of retrying with its previous placement. + let legacy_config = handle_get_sandbox_config( + &state, + with_sandbox( + Request::new(GetSandboxConfigRequest { + name: "endpoint-placement".to_string(), + supported_capabilities: vec![ + openshell_core::extension_protocol::POLICY_CEDAR_V1.to_string(), + ], + ..Default::default() + }), + sandbox_id, + ), + ) + .await + .expect("legacy supervisor receives an unadmitted configuration") + .into_inner(); + assert!(!legacy_config.configuration_admitted); + assert!(legacy_config.policy.is_none()); + assert!(!legacy_config.configuration_error.is_empty()); + assert_eq!(legacy_config.version, config.version); + assert_eq!( + legacy_config.provider_env_revision, + config.provider_env_revision + ); } #[tokio::test] diff --git a/docs/how-it-works/providers/profiles.mdx b/docs/how-it-works/providers/profiles.mdx index 6607a326ce..7476c67186 100644 --- a/docs/how-it-works/providers/profiles.mdx +++ b/docs/how-it-works/providers/profiles.mdx @@ -202,9 +202,11 @@ network_policies: that style uses. Fields for other styles are rejected. Unlike a profile placement, a binding placement also fixes the header value form: `bearer` accepts only `Bearer `, `header` only the bare placeholder, and -`basic` only an `Authorization: Basic` value. Without `placement`, the endpoint -uses each credential's profile placement. The placement applies to every static -credential the provider supplies at that endpoint. +`basic` only an `Authorization: Basic` value. A binding placement also +excludes request-body and WebSocket rewriting and trusted AWS signing for that +credential, even when the endpoint enables them. Without `placement`, the +endpoint uses each credential's profile placement. The placement applies to +every static credential the provider supplies at that endpoint. Bindings of one provider whose host, port, and path can match the same request must use the same placement; OpenShell rejects the policy update otherwise. A @@ -212,8 +214,11 @@ must use the same placement; OpenShell rejects the policy update otherwise. A Upgrade every gateway replica before using `placement`. An older gateway drops the field and applies the profile placement, so the CLI refuses to submit such a -policy to a gateway that does not advertise support. Supervisors that do not -enforce binding placement do not receive the policy or the affected credentials. +policy to a gateway that does not advertise support. A supervisor that does not +enforce binding placement receives the policy as not admitted and applies the +gateway's policy validation failure mode: `fail_closed` blocks the sandbox's +network access, and `retain_last_valid` keeps its last valid policy and +credentials until the supervisor is upgraded. For AWS endpoints, the binding and signing fields have separate jobs. `credential_binding.provider` selects the provider instance that supplies From 556fee276cd3d6502d8ca1fc081406c0c51b2349 Mon Sep 17 00:00:00 2001 From: Mrunal Patel Date: Wed, 2 Dec 2026 21:09:13 +0000 Subject: [PATCH 5/6] fix(policy): scope signing to unplaced keys and prove literal path disjointness - Treat an explicitly placed credential as absent in trusted signing lookups, so a foreign optional session token is ignored while a missing required key still fails as unavailable. - Skip the sandbox write and watcher notification when a repeated rejection report changes nothing. - Reject overlap between credential binding paths only when their mandatory literal prefixes and suffixes agree, before falling back to the conservative check. Refs #5963 Signed-off-by: Mrunal Patel --- .../src/provider_credentials.rs | 7 +- crates/openshell-core/src/secrets.rs | 9 +- crates/openshell-policy/src/ambiguity.rs | 62 +++++++++++ crates/openshell-server/src/grpc/policy.rs | 44 ++++++++ .../src/l7/relay.rs | 105 ++++++++++++++++++ 5 files changed, 219 insertions(+), 8 deletions(-) diff --git a/crates/openshell-core/src/provider_credentials.rs b/crates/openshell-core/src/provider_credentials.rs index 4e30f0ecc5..50bc6bf900 100644 --- a/crates/openshell-core/src/provider_credentials.rs +++ b/crates/openshell-core/src/provider_credentials.rs @@ -2271,11 +2271,12 @@ mod tests { .unwrap_err() .is_placement_mismatch() ); - assert!( + assert_eq!( explicit .resolve_current_env_key_checked("API_KEY", "sigv4") - .unwrap_err() - .is_placement_mismatch() + .unwrap(), + None, + "an explicitly placed key is not a signing input" ); // Profile placement keeps honoring explicit endpoint rewrite policy. diff --git a/crates/openshell-core/src/secrets.rs b/crates/openshell-core/src/secrets.rs index 266e7db4db..b577a021b9 100644 --- a/crates/openshell-core/src/secrets.rs +++ b/crates/openshell-core/src/secrets.rs @@ -900,12 +900,11 @@ impl SecretResolver { }); } // Trusted transforms such as signing place the value themselves, which - // an explicit binding placement does not authorize. + // an explicit binding placement does not authorize. Such a key is not + // a signing input: an optional one is ignored, and a missing required + // one fails as unavailable at the caller. if self.explicit_placement_keys.contains(key) { - return Err(UnresolvedPlaceholderError { - location, - reason: UnresolvedPlaceholderReason::PlacementMismatch, - }); + return Ok(None); } let placeholder = placeholder_for_env_key(key); let resolved = self diff --git a/crates/openshell-policy/src/ambiguity.rs b/crates/openshell-policy/src/ambiguity.rs index 60fc8d226c..a963367c39 100644 --- a/crates/openshell-policy/src/ambiguity.rs +++ b/crates/openshell-policy/src/ambiguity.rs @@ -535,6 +535,12 @@ fn credential_path_patterns_overlap(left: &str, right: &str) -> bool { return EndpointPathPattern::new(other).matches(exact); } } + // Every path a selector matches starts with its literal prefix and, for a + // glob, ends with its literal suffix. Disagreeing literals prove the + // selectors disjoint even when the rest cannot be modeled. + if !credential_path_literals_compatible(left, right) { + return false; + } let (Some(left), Some(right)) = ( credential_path_languages(left), credential_path_languages(right), @@ -548,6 +554,35 @@ fn credential_path_patterns_overlap(left: &str, right: &str) -> bool { }) } +/// Whether two credential binding paths can share a request path as far as +/// their mandatory literal prefixes and suffixes are concerned. +fn credential_path_literals_compatible(left: &str, right: &str) -> bool { + let universal = |pattern: &str| pattern.is_empty() || pattern == "**" || pattern == "/**"; + if universal(left) || universal(right) { + return true; + } + // Text before the first metacharacter is literal in the glob, in a + // subtree prefix, and in the selector's own source text. + let prefix = |pattern: &str| { + let end = pattern.find(['*', '?', '[']).unwrap_or(pattern.len()); + pattern[..end].to_string() + }; + // A subtree matches any descendant, so only globs have a fixed suffix. + // Text after the last `*`, `?`, or `]` is literal; stopping at a literal + // `]` only shortens the suffix. + let suffix = |pattern: &str| { + if pattern.ends_with("/**") { + return String::new(); + } + let start = pattern.rfind(['*', '?', ']']).map_or(0, |index| index + 1); + pattern[start..].to_string() + }; + let (left_prefix, right_prefix) = (prefix(left), prefix(right)); + let (left_suffix, right_suffix) = (suffix(left), suffix(right)); + (left_prefix.starts_with(&right_prefix) || right_prefix.starts_with(&left_prefix)) + && (left_suffix.ends_with(&right_suffix) || right_suffix.ends_with(&left_suffix)) +} + /// Token sequences whose union is the request paths a credential binding path /// selects, or `None` when the selector matches everything or cannot be /// modeled. @@ -1263,6 +1298,20 @@ mod tests { bound("api?.example.com", "", None), bound("api12.example.com", "", Some("x-api-key")), ), + // Literal first components prove these disjoint even though the + // rest of each selector cannot be modeled. + ( + bound("api.example.com", "/alpha/[]a]", None), + bound("api.example.com", "/beta/*", Some("x-api-key")), + ), + ( + bound("api.example.com", "/alpha/**/**/**/**/**/**/**/item", None), + bound("api.example.com", "/beta/*", Some("x-api-key")), + ), + ( + bound("api.example.com", "/v1/*.json", None), + bound("api.example.com", "/v1/*.yaml", Some("x-api-key")), + ), // `**/` matches whole components, so it cannot match `x` in `xb`. ( bound("api.example.com", "/a/**/b", None), @@ -1335,6 +1384,12 @@ mod tests { "/docs/[]a]", "/docs/a", "/docs/[!a]", + "/alpha/[]a]", + "/beta/*", + "/alpha/**/**/**/**/**/**/**/item", + "/v1/*.json", + "/v1/*.yaml", + "/v*/**", ]; let path_samples = [ "/v1", @@ -1353,6 +1408,13 @@ mod tests { "/docs/a", "/docs/]", "/docs/b", + "/alpha/a", + "/alpha/x/y/item", + "/alpha/item", + "/beta/x", + "/v1/a.json", + "/v1/a.yaml", + "/v*/x", ]; for left in paths { for right in paths { diff --git a/crates/openshell-server/src/grpc/policy.rs b/crates/openshell-server/src/grpc/policy.rs index 7159a166cb..bb37a5d4dc 100644 --- a/crates/openshell-server/src/grpc/policy.rs +++ b/crates/openshell-server/src/grpc/policy.rs @@ -5403,6 +5403,18 @@ pub(super) async fn handle_report_sandbox_configuration( .map_err(Status::internal)?; } } + // A supervisor reports the same rejection on every poll while the + // desired generation stays unadmitted. Skip the write and the watcher + // notification when the report changes nothing. + let status = sandbox.status.as_ref(); + if reported == ConfigurationAdmissionState::Rejected + && status.and_then(|status| status.configuration_admission.as_ref()) == Some(&admission) + && status.and_then(|status| status.provisioning.as_ref()) == provisioning.as_ref() + { + return Ok(Response::new( + openshell_core::proto::ReportSandboxConfigurationResponse {}, + )); + } let updated = state .store .update_message_cas::(&sandbox_id, expected_version, |sandbox| { @@ -15547,6 +15559,7 @@ mod tests { .unwrap() .into_inner(); assert!(config.configuration_admitted); + let accepted_instance_id = instance_id.clone(); let accepted = SandboxConfigurationAdmission { instance_id, state: Admission::Accepted.into(), @@ -15587,6 +15600,37 @@ mod tests { legacy_config.provider_env_revision, config.provider_env_revision ); + + // The legacy supervisor reports the same rejection on each poll. Only + // the first report changes the sandbox record. + let rejection = SandboxConfigurationAdmission { + instance_id: accepted_instance_id, + state: Admission::Rejected.into(), + policy_version: legacy_config.version, + policy_hash: legacy_config.policy_hash.clone(), + config_revision: legacy_config.config_revision, + provider_env_revision: legacy_config.provider_env_revision, + error: "runtime detail".to_string(), + }; + let resource_version = || async { + state + .store + .get_message::(sandbox_id) + .await + .unwrap() + .unwrap() + .metadata + .unwrap() + .resource_version + }; + handle_report_sandbox_configuration(&state, report(rejection.clone())) + .await + .unwrap(); + let after_first = resource_version().await; + handle_report_sandbox_configuration(&state, report(rejection)) + .await + .unwrap(); + assert_eq!(resource_version().await, after_first); } #[tokio::test] diff --git a/crates/openshell-supervisor-network/src/l7/relay.rs b/crates/openshell-supervisor-network/src/l7/relay.rs index e4408098aa..95eadf8b17 100644 --- a/crates/openshell-supervisor-network/src/l7/relay.rs +++ b/crates/openshell-supervisor-network/src/l7/relay.rs @@ -6060,6 +6060,111 @@ mod tests { assert!(!sent.contains("synthetic-signing-secret")); } + /// Relay one AWS-signed request where `placed` keys carry an explicit binding + /// placement, returning what the upstream received or the relay error. + async fn relay_sigv4_with_placed_keys(placed: &[&str]) -> Result { + let values = TestHashMap::from([ + ("AWS_ACCESS_KEY_ID".into(), "synthetic-access-key".into()), + ( + "AWS_SECRET_ACCESS_KEY".into(), + "synthetic-signing-secret".into(), + ), + ("AWS_SESSION_TOKEN".into(), "synthetic-session-token".into()), + ]); + let bindings = values + .keys() + .map(|key: &String| { + let mut binding = endpoint_binding(&format!("aws:{key}")); + if placed.contains(&key.as_str()) { + binding.endpoints[0].placement = + Some(openshell_core::proto::NetworkCredentialPlacement { + auth_style: "header".to_string(), + header_name: "x-other-token".to_string(), + ..Default::default() + }); + } + (key.clone(), binding) + }) + .collect(); + let state = ProviderCredentialState::from_bound_environment( + 1, + values, + TestHashMap::new(), + TestHashMap::new(), + bindings, + Vec::new(), + ) + .unwrap(); + let resolver = state + .resolver_for_endpoint("allowed.example.test", 443, "/allowed/api") + .unwrap(); + let request = crate::l7::rest::request_from_buffered_http( + "GET", + "/allowed/api", + "/allowed/api", + b"GET /allowed/api HTTP/1.1\r\nHost: allowed.example.test\r\n\r\n".to_vec(), + ) + .unwrap(); + let (mut _app, mut client) = tokio::io::duplex(8192); + let (mut upstream, mut service) = tokio::io::duplex(8192); + let service_task = tokio::spawn(async move { + let mut bytes = Vec::new(); + let mut byte = [0]; + while service.read_exact(&mut byte).await.is_ok() { + bytes.push(byte[0]); + if bytes.ends_with(b"\r\n\r\n") { + service + .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n") + .await + .unwrap(); + break; + } + } + String::from_utf8(bytes).unwrap() + }); + let result = crate::l7::rest::relay_http_request_with_options_guarded( + &request, + &mut client, + &mut upstream, + crate::l7::rest::RelayRequestOptions { + resolver: Some(&resolver), + credential_signing: crate::l7::CredentialSigning::SigV4NoBody, + signing_service: "execute-api", + signing_region: "us-west-2", + host: "allowed.example.test", + port: 443, + ..Default::default() + }, + ) + .await; + drop(upstream); + let sent = service_task.await.unwrap(); + result.map(|_| sent).map_err(|error| error.to_string()) + } + + #[tokio::test] + async fn sigv4_ignores_an_explicitly_placed_optional_session_token() { + let sent = relay_sigv4_with_placed_keys(&["AWS_SESSION_TOKEN"]) + .await + .expect("long-lived key pair still signs"); + assert!(sent.contains("AWS4-HMAC-SHA256"), "{sent}"); + assert!(sent.contains("synthetic-access-key")); + assert!(!sent.contains("synthetic-session-token")); + } + + #[tokio::test] + async fn sigv4_fails_when_a_required_key_is_explicitly_placed() { + for key in ["AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY"] { + let error = relay_sigv4_with_placed_keys(&[key]) + .await + .expect_err("a required signing key must not come from an explicit placement"); + assert!( + error.contains("AWS credentials not found"), + "{key}: {error}" + ); + } + } + #[tokio::test] async fn header_endpoint_mismatch_traces_refusal_without_failing_request_root() { use crate::test_support::request_tracing::{RequestTracing, span_attribute}; From 93ce9156454e38c86454ba0cc2838d4d356727f7 Mon Sep 17 00:00:00 2001 From: Mrunal Patel Date: Thu, 3 Dec 2026 00:24:32 +0000 Subject: [PATCH 6/6] fix(policy): model a trailing recursive wildcard like the runtime glob A component-aligned "**/" at the end of a credential binding path matches any remainder, and at the start it can match nothing, so its slash is not required in either position. Apply this in both the glob expansion and the literal suffix check, so "/a/**/" and "/a/*b" are reported as overlapping. Refs #5963 Signed-off-by: Mrunal Patel --- crates/openshell-policy/src/ambiguity.rs | 50 ++++++++++++++++++++++-- 1 file changed, 46 insertions(+), 4 deletions(-) diff --git a/crates/openshell-policy/src/ambiguity.rs b/crates/openshell-policy/src/ambiguity.rs index a963367c39..f6eac56e2d 100644 --- a/crates/openshell-policy/src/ambiguity.rs +++ b/crates/openshell-policy/src/ambiguity.rs @@ -575,7 +575,23 @@ fn credential_path_literals_compatible(left: &str, right: &str) -> bool { return String::new(); } let start = pattern.rfind(['*', '?', ']']).map_or(0, |index| index + 1); - pattern[start..].to_string() + let suffix = &pattern[start..]; + // A component-aligned `**/` consumes its own slash. At the end of a + // pattern it matches any remainder, and at the start it can match + // nothing, so that slash is not required in either position. + let before = &pattern[..start]; + if let Some(head) = before.strip_suffix("**") + && (head.is_empty() || head.ends_with('/')) + && let Some(rest) = suffix.strip_prefix('/') + { + if rest.is_empty() { + return String::new(); + } + if head.is_empty() { + return rest.to_string(); + } + } + suffix.to_string() }; let (left_prefix, right_prefix) = (prefix(left), prefix(right)); let (left_suffix, right_suffix) = (suffix(left), suffix(right)); @@ -601,8 +617,9 @@ fn credential_path_languages(pattern: &str) -> Option>> { return Some(vec![literal(prefix), descendants]); } - // A `**/` component matches zero or more whole components, so it is - // either absent or any text ending in `/`. Expand each occurrence. + // A component-aligned `**/` matches zero or more whole components, so it + // is either absent or any text ending in `/`; at the end of the pattern + // it matches any remainder. Expand each occurrence. let mut pieces = vec![String::new()]; let mut rest = pattern; while let Some(index) = rest.find("**/") { @@ -625,9 +642,17 @@ fn credential_path_languages(pattern: &str) -> Option>> { .map(|piece| tokenize_runtime_path_glob(piece)) .collect::>>()?; + let last = pieces.len() - 1; let mut languages = vec![Vec::new()]; for (index, piece) in pieces.into_iter().enumerate() { - if index > 0 { + if index > 0 && index == last && piece.is_empty() { + // A trailing `**/` matches any remainder, with or without a slash. + for language in &mut languages { + language.push(GlobToken::Star { + crosses_delimiter: true, + }); + } + } else if index > 0 { let mut expanded = Vec::with_capacity(languages.len() * 2); for language in languages { let mut components = language.clone(); @@ -1247,6 +1272,15 @@ mod tests { bound("api.example.com", "/v*", None), bound("api.example.com", "/v1/users", Some("x-api-key")), ), + // A trailing `**/` matches any remainder, so `/a/b` matches both. + ( + bound("api.example.com", "/a/**/", None), + bound("api.example.com", "/a/*b", Some("x-api-key")), + ), + ( + bound("api.example.com", "**/b", None), + bound("api.example.com", "/x/*b", Some("x-api-key")), + ), // A character class whose first member is `]` still contains `a`. ( bound("api.example.com", "/docs/[]a]", None), @@ -1390,6 +1424,9 @@ mod tests { "/v1/*.json", "/v1/*.yaml", "/v*/**", + "/a/**/", + "**/b", + "/x/*b", ]; let path_samples = [ "/v1", @@ -1415,6 +1452,11 @@ mod tests { "/v1/a.json", "/v1/a.yaml", "/v*/x", + "/a/", + "/a/x/", + "/x/b", + "b", + "/x/ab", ]; for left in paths { for right in paths {