From 97b9b31c75824108ae23c0919224343ecb03a620 Mon Sep 17 00:00:00 2001 From: stevenlee-oai <213687449+stevenlee-oai@users.noreply.github.com> Date: Thu, 26 Nov 2026 05:42:12 +0000 Subject: [PATCH 1/6] feat(policy): isolate overlapping credential-bound accounts Signed-off-by: stevenlee-oai <213687449+stevenlee-oai@users.noreply.github.com> --- .../openshell-core/src/extension_protocol.rs | 4 + crates/openshell-core/src/grpc_client.rs | 1 + crates/openshell-core/src/policy_l7.rs | 11 +- .../src/provider_credentials.rs | 144 ++++++++++- crates/openshell-core/src/secrets_body.rs | 2 + .../src/l7/mod.rs | 4 +- .../src/policy_types.rs | 3 + crates/openshell-policy/src/ambiguity.rs | 162 ++++++++++-- crates/openshell-policy/src/lib.rs | 93 ++++++- crates/openshell-providers/src/profiles.rs | 24 ++ crates/openshell-server/src/grpc/policy.rs | 162 ++++++++++-- .../grpc/policy/token_grant_owners_tests.rs | 231 ++++++++++++++++++ crates/openshell-server/src/grpc/provider.rs | 2 + .../src/google_cloud_metadata.rs | 2 + .../src/l7/relay.rs | 55 ++++- .../l7/relay/token_grant_ownership_tests.rs | 81 ++++++ .../src/l7/rest.rs | 4 + .../src/l7/websocket.rs | 4 + .../openshell-supervisor-network/src/proxy.rs | 16 ++ .../src/proxy/relay.rs | 2 + .../src/config_runtime.rs | 34 ++- crates/openshell-supervisor/src/lib.rs | 12 +- docs/how-it-works/policies/schema.mdx | 6 +- docs/how-it-works/providers/profiles.mdx | 52 +++- .../kubernetes_shared_supervisor_spiffe.rs | 1 + proto/openshell.proto | 6 + proto/sandbox.proto | 4 + .../conformance/src/credential_gating.rs | 153 ++++++++++++ 28 files changed, 1222 insertions(+), 53 deletions(-) diff --git a/crates/openshell-core/src/extension_protocol.rs b/crates/openshell-core/src/extension_protocol.rs index 1d6d57960b..4764f3c29d 100644 --- a/crates/openshell-core/src/extension_protocol.rs +++ b/crates/openshell-core/src/extension_protocol.rs @@ -12,6 +12,10 @@ use crate::proto::extension::v1::{PeerMetadata, ProtocolVersion}; pub const PROTOCOL_MAJOR: u32 = 1; pub const PROTOCOL_MINOR: u32 = 0; +/// A peer can enforce request-policy ownership for static credential bindings. +pub const POLICY_REQUEST_BOUND_CREDENTIALS_V1: &str = + "openshell.policy.request-bound-credentials.v1"; + /// Policy format implemented by a peer's registered Cedar backend. pub const POLICY_CEDAR_V1: &str = "openshell.policy.cedar.v1"; diff --git a/crates/openshell-core/src/grpc_client.rs b/crates/openshell-core/src/grpc_client.rs index 2429f255cc..43e98ddb08 100644 --- a/crates/openshell-core/src/grpc_client.rs +++ b/crates/openshell-core/src/grpc_client.rs @@ -1484,6 +1484,7 @@ pub async fn fetch_provider_environment_with_stable_placeholders( let response = client .get_sandbox_provider_environment(GetSandboxProviderEnvironmentRequest { + supports_request_policy_bound_credentials: true, sandbox_id: sandbox_id.to_string(), supports_static_credential_bindings: true, supports_stable_placeholder_environment_keys: true, diff --git a/crates/openshell-core/src/policy_l7.rs b/crates/openshell-core/src/policy_l7.rs index 26be9fee57..b7202ed852 100644 --- a/crates/openshell-core/src/policy_l7.rs +++ b/crates/openshell-core/src/policy_l7.rs @@ -36,6 +36,7 @@ pub fn network_enforcement_mode_from_str(value: &str) -> Option Some(NetworkEnforcementMode::Unspecified), "enforce" => Some(NetworkEnforcementMode::Enforce), + "enforce-credential-bound" => Some(NetworkEnforcementMode::EnforceCredentialBound), "audit" => Some(NetworkEnforcementMode::Audit), _ => None, } @@ -45,6 +46,7 @@ pub fn network_enforcement_mode_to_str(value: i32) -> Option<&'static str> { match NetworkEnforcementMode::try_from(value).ok()? { NetworkEnforcementMode::Unspecified => Some(""), NetworkEnforcementMode::Enforce => Some("enforce"), + NetworkEnforcementMode::EnforceCredentialBound => Some("enforce-credential-bound"), NetworkEnforcementMode::Audit => Some("audit"), } } @@ -193,9 +195,12 @@ pub fn validate_endpoint_modes(tls: &str, enforcement: &str, access: &str) -> Ve let mut errors = Vec::new(); errors.extend(unknown_tls_value(tls)); - if !matches!(enforcement, "" | "enforce" | "audit") { + if !matches!( + enforcement, + "" | "enforce" | "enforce-credential-bound" | "audit" + ) { errors.push(format!( - "unknown enforcement value '{enforcement}' (expected enforce or audit)" + "unknown enforcement value '{enforcement}' (expected enforce, enforce-credential-bound, or audit)" )); } if !matches!(access, "" | "read-only" | "read-write" | "full") { @@ -400,7 +405,7 @@ mod tests { #[test] fn endpoint_modes_accept_documented_values_and_defaults() { for tls in ["", "skip"] { - for enforcement in ["", "enforce", "audit"] { + for enforcement in ["", "enforce", "enforce-credential-bound", "audit"] { for access in ["", "read-only", "read-write", "full"] { assert!(validate_endpoint_modes(tls, enforcement, access).is_empty()); } diff --git a/crates/openshell-core/src/provider_credentials.rs b/crates/openshell-core/src/provider_credentials.rs index 9f81a00590..948431c5a2 100644 --- a/crates/openshell-core/src/provider_credentials.rs +++ b/crates/openshell-core/src/provider_credentials.rs @@ -18,6 +18,84 @@ use std::sync::{Arc, RwLock}; const MAX_RETAINED_CREDENTIAL_GENERATIONS: usize = 8; +/// Refuse a request-bound policy whose Gateway snapshot omits the owner metadata +/// required for safe resolution. In particular, an older Gateway must not turn +/// an overlapping credential policy into legacy unrestricted bindings. +pub fn validate_request_bound_credential_snapshot( + policy: &crate::proto::SandboxPolicy, + bindings: &HashMap, +) -> Result<(), StaticCredentialBindingError> { + let endpoints: Vec<_> = policy + .network_policies + .values() + .flat_map(|rule| &rule.endpoints) + .filter(|endpoint| { + endpoint.enforcement + == crate::proto::NetworkEnforcementMode::EnforceCredentialBound as i32 + }) + .collect(); + if endpoints + .iter() + .any(|endpoint| endpoint.token_grant_owner.is_empty()) + { + return Err(binding_error( + "request-bound endpoint is missing its Gateway-issued policy owner", + )); + } + for binding in bindings.values() { + if binding.request_policy_owners.is_empty() != binding.request_policy_provider.is_empty() { + return Err(binding_error( + "request-bound credential has incomplete Provider identity", + )); + } + let mut matching_owners = HashSet::new(); + let mut matching_owned_route = false; + for target in &binding.endpoints { + for endpoint in endpoints.iter().filter(|endpoint| { + endpoint.host.eq_ignore_ascii_case(&target.host) + && (if endpoint.ports.is_empty() { + endpoint.port == target.port + } else { + endpoint.ports.contains(&target.port) + }) + && canonical_binding_path(&endpoint.path) + == canonical_binding_path(&target.path) + }) { + matching_owned_route = true; + if endpoint + .credential_binding + .as_ref() + .is_some_and(|item| item.provider == binding.request_policy_provider) + { + matching_owners.insert(endpoint.token_grant_owner.as_str()); + } + } + } + if matching_owned_route && binding.request_policy_owners.is_empty() { + return Err(binding_error( + "request-bound credential is missing its policy owners", + )); + } + if binding + .request_policy_owners + .iter() + .any(|owner| owner.is_empty() || !matching_owners.contains(owner.as_str())) + { + return Err(binding_error( + "request-bound credential contains an invalid policy owner", + )); + } + } + Ok(()) +} + +fn canonical_binding_path(path: &str) -> &str { + match path { + "" | "**" | "/**" => "/**", + path => path, + } +} + #[derive(Debug, Clone, Default)] pub struct ProviderCredentialSnapshot { /// Identifies this local installation, including repairs at the same revision. @@ -225,6 +303,7 @@ struct CompiledStaticCredentialBinding { endpoints: Vec, credential_identity: String, workload_credential_handle: String, + request_policy_owners: HashSet, } #[derive(Debug, Clone)] @@ -661,6 +740,38 @@ impl ProviderCredentialState { self.resolver_for_endpoint_with_revision(host, port, path).0 } + /// Whether this endpoint has static credentials that require request-owner admission. + #[must_use] + pub fn has_request_policy_bound_credentials_for_endpoint( + &self, + host: &str, + port: u16, + path: &str, + ) -> bool { + let request_path = path.split_once('?').map_or(path, |(path, _)| path); + let Ok(request_path) = crate::secrets::redact_target_for_policy(request_path) else { + return false; + }; + let normalized_host = host.to_ascii_lowercase(); + let host_labels = normalized_host.split('.').collect::>(); + self.inner + .read() + .expect("provider credential state poisoned") + .static_credential_bindings + .values() + .any(|binding| { + !binding.request_policy_owners.is_empty() + && binding.endpoints.iter().any(|endpoint| { + static_credential_endpoint_matches( + endpoint, + &host_labels, + port, + &request_path, + ) + }) + }) + } + /// Resolve provider placeholders for one endpoint and return the provider /// revision observed from the same locked state snapshot. /// @@ -690,6 +801,22 @@ impl ProviderCredentialState { Option>, Option>, u64, + ) { + self.resolver_and_body_classifier_for_endpoint_with_owners(host, port, path, None) + } + + /// Resolve only static credentials whose own request policy admitted the request. + #[must_use] + pub fn resolver_and_body_classifier_for_endpoint_with_owners( + &self, + host: &str, + port: u16, + path: &str, + admitted_owners: Option<&HashSet>, + ) -> ( + Option>, + Option>, + u64, ) { let request_path = path.split_once('?').map_or(path, |(path, _)| path); let request_path = crate::secrets::redact_target_for_policy(request_path); @@ -710,9 +837,17 @@ impl ProviderCredentialState { .static_credential_bindings .iter() .filter(|(_, binding)| { - binding.endpoints.iter().any(|endpoint| { - static_credential_endpoint_matches(endpoint, &host_labels, port, &request_path) - }) + (binding.request_policy_owners.is_empty() + || admitted_owners + .is_some_and(|owners| !owners.is_disjoint(&binding.request_policy_owners))) + && binding.endpoints.iter().any(|endpoint| { + static_credential_endpoint_matches( + endpoint, + &host_labels, + port, + &request_path, + ) + }) }) .map(|(key, _)| key.clone()) .collect(); @@ -1447,6 +1582,7 @@ fn compile_static_credential_bindings( placement, credential_identity: binding.credential_identity, workload_credential_handle: binding.workload_credential_handle, + request_policy_owners: binding.request_policy_owners.into_iter().collect(), }, )) }) @@ -1782,6 +1918,8 @@ mod tests { fn binding(host: &str, port: u32, path: &str) -> StaticCredentialBinding { StaticCredentialBinding { + request_policy_provider: String::new(), + request_policy_owners: Vec::new(), endpoints: vec![StaticCredentialEndpointBinding { host: host.to_string(), port, diff --git a/crates/openshell-core/src/secrets_body.rs b/crates/openshell-core/src/secrets_body.rs index c9464f8e50..0c87096658 100644 --- a/crates/openshell-core/src/secrets_body.rs +++ b/crates/openshell-core/src/secrets_body.rs @@ -352,6 +352,8 @@ mod tests { HashMap::from([( "KEY".into(), StaticCredentialBinding { + request_policy_provider: String::new(), + request_policy_owners: Vec::new(), credential_identity: "provider".into(), workload_credential_handle: handle, endpoints: vec![StaticCredentialEndpointBinding { diff --git a/crates/openshell-policy-runtime-interface/src/l7/mod.rs b/crates/openshell-policy-runtime-interface/src/l7/mod.rs index 6334851b13..bf7735559e 100644 --- a/crates/openshell-policy-runtime-interface/src/l7/mod.rs +++ b/crates/openshell-policy-runtime-interface/src/l7/mod.rs @@ -165,7 +165,9 @@ pub fn parse_l7_config(config: &EndpointConfig) -> Option { }; let enforcement = match config.enforcement { - EnforcementSetting::Enforce => EnforcementMode::Enforce, + EnforcementSetting::Enforce | EnforcementSetting::EnforceCredentialBound => { + EnforcementMode::Enforce + } EnforcementSetting::Default | EnforcementSetting::Audit => EnforcementMode::Audit, EnforcementSetting::Unknown => unreachable!("endpoint modes were validated above"), }; diff --git a/crates/openshell-policy-runtime-interface/src/policy_types.rs b/crates/openshell-policy-runtime-interface/src/policy_types.rs index 11d9156ebb..c2e4b12260 100644 --- a/crates/openshell-policy-runtime-interface/src/policy_types.rs +++ b/crates/openshell-policy-runtime-interface/src/policy_types.rs @@ -108,6 +108,8 @@ pub enum EnforcementSetting { Default, /// Deny violations. Enforce, + /// Deny violations and restrict static credentials to their admitting owner. + EnforceCredentialBound, /// Log violations and forward the request. Audit, /// A value the runtime does not accept. @@ -119,6 +121,7 @@ impl From<&str> for EnforcementSetting { match label { "" => Self::Default, "enforce" => Self::Enforce, + "enforce-credential-bound" => Self::EnforceCredentialBound, "audit" => Self::Audit, _ => Self::Unknown, } diff --git a/crates/openshell-policy/src/ambiguity.rs b/crates/openshell-policy/src/ambiguity.rs index efb846a9a1..48f39fc1ce 100644 --- a/crates/openshell-policy/src/ambiguity.rs +++ b/crates/openshell-policy/src/ambiguity.rs @@ -46,6 +46,7 @@ impl fmt::Display for EndpointAmbiguity { struct EndpointRef<'a> { policy: &'a str, + provider_rule: bool, index: usize, endpoint: &'a NetworkEndpoint, } @@ -72,6 +73,7 @@ pub fn find_endpoint_ambiguities(policy: &SandboxPolicy) -> Vec Vec i32 { } fn normalized_enforcement(value: i32) -> i32 { - if value == NetworkEnforcementMode::Enforce as i32 { - NetworkEnforcementMode::Enforce as i32 + if value == NetworkEnforcementMode::Enforce as i32 + || value == NetworkEnforcementMode::EnforceCredentialBound as i32 + { + value } else if NetworkEnforcementMode::try_from(value).is_ok() { NetworkEnforcementMode::Audit as i32 } else { @@ -365,6 +382,41 @@ fn normalized_enforcement(value: i32) -> i32 { } } +fn credential_bound(endpoint: &NetworkEndpoint) -> bool { + endpoint.enforcement == NetworkEnforcementMode::EnforceCredentialBound as i32 +} + +fn credential_endpoint(endpoint: &EndpointRef<'_>) -> bool { + endpoint.endpoint.credential_binding.is_some() + || (endpoint.provider_rule && endpoint.endpoint.provider_credentialed) +} + +fn compatible_credential_bound_selectors(left: &NetworkEndpoint, right: &NetworkEndpoint) -> bool { + credential_bound(left) + && credential_bound(right) + && left.credential_binding.is_some() + && right.credential_binding.is_some() + && left.host.eq_ignore_ascii_case(&right.host) + && effective_ports(left) == effective_ports(right) + && left.path == right.path +} + +fn credential_bound_overlap_conflicts( + left: &EndpointRef<'_>, + right: &EndpointRef<'_>, +) -> Vec { + let one_is_protected = credential_bound(left.endpoint) || credential_bound(right.endpoint); + if one_is_protected + && credential_endpoint(left) + && credential_endpoint(right) + && !compatible_credential_bound_selectors(left.endpoint, right.endpoint) + { + vec!["overlapping credential routes must both use enforce-credential-bound with the same exact host, ports, and path".to_string()] + } else { + Vec::new() + } +} + fn normalized_strings(values: &[String]) -> Vec { values .iter() @@ -396,6 +448,28 @@ fn normalized_mcp_strict_tool_names(endpoint: &NetworkEndpoint) -> bool { .unwrap_or(true) } +fn normalized_mcp_versions(endpoint: &NetworkEndpoint) -> Vec { + let versions = endpoint + .mcp + .as_ref() + .map(|options| options.versions.as_slice()) + .unwrap_or_default(); + if versions.is_empty() { + vec![ + openshell_core::mcp::DEFAULT_MCP_PROTOCOL_VERSION + .as_str() + .to_string(), + ] + } else { + versions + .iter() + .cloned() + .collect::>() + .into_iter() + .collect() + } +} + fn host_patterns_overlap(left: &str, right: &str) -> bool { if left.is_empty() || right.is_empty() { return true; @@ -787,6 +861,62 @@ mod tests { assert!(find_endpoint_ambiguities(&policy_with(left, right)).is_empty()); } + #[test] + fn account_bound_overlap_requires_exact_protected_credential_routes() { + let mut left = endpoint("mcp.example.com", 443); + left.path = "/mcp".into(); + left.protocol = "mcp".into(); + left.enforcement = NetworkEnforcementMode::EnforceCredentialBound as i32; + left.credential_binding = Some(openshell_core::proto::NetworkCredentialBinding { + provider: "account-a".into(), + }); + let mut right = left.clone(); + right.credential_binding.as_mut().unwrap().provider = "account-b".into(); + assert!(find_endpoint_ambiguities(&policy_with(left.clone(), right.clone())).is_empty()); + + right.path = "/**".into(); + let partial = find_endpoint_ambiguities(&policy_with(left.clone(), right.clone())); + assert!(partial.iter().any(|ambiguity| { + ambiguity + .conflicts + .iter() + .any(|conflict| conflict.contains("same exact host")) + })); + + right.path = left.path.clone(); + right.enforcement = NetworkEnforcementMode::Enforce as i32; + assert!(!find_endpoint_ambiguities(&policy_with(left.clone(), right.clone())).is_empty()); + + right.credential_binding = None; + right.provider_credentialed = true; + right.path = "/**".into(); + let mut profile_policy = policy_with(left, right); + let profile_rule = profile_policy.network_policies.remove("right").unwrap(); + profile_policy + .network_policies + .insert("_provider_third".into(), profile_rule); + assert!(!find_endpoint_ambiguities(&profile_policy).is_empty()); + } + + #[test] + fn covered_unbound_sibling_does_not_become_an_independent_credential_source() { + let mut bound = endpoint("api.example.com", 443); + bound.path = "/api/**".into(); + bound.protocol = "rest".into(); + bound.enforcement = NetworkEnforcementMode::EnforceCredentialBound as i32; + bound.credential_binding = Some(openshell_core::proto::NetworkCredentialBinding { + provider: "account-a".into(), + }); + let mut sibling = endpoint("api.example.com", 443); + sibling.path = "/api/admin".into(); + sibling.protocol = "rest".into(); + sibling.enforcement = NetworkEnforcementMode::Enforce as i32; + // The Gateway stamps coverage on ordinary rules as well as the source's + // own route. That marker alone must not create a second source. + sibling.provider_credentialed = true; + assert!(find_endpoint_ambiguities(&policy_with(bound, sibling)).is_empty()); + } + #[test] fn advisor_provenance_does_not_make_endpoints_ambiguous() { let explicit = endpoint("api.example.com", 443); diff --git a/crates/openshell-policy/src/lib.rs b/crates/openshell-policy/src/lib.rs index ff6cdd8d5a..e4c67bbbe2 100644 --- a/crates/openshell-policy/src/lib.rs +++ b/crates/openshell-policy/src/lib.rs @@ -37,8 +37,8 @@ use openshell_core::mcp::{ }; use openshell_core::proto::{ FilesystemPolicy, GraphqlOperation, L7Allow, L7DenyRule, L7QueryMatcher, L7Rule, - LandlockPolicy, McpOptions, NetworkBinary, NetworkEndpoint, NetworkPolicyRule, ProcessPolicy, - SandboxPolicy, + LandlockPolicy, McpOptions, NetworkBinary, NetworkEndpoint, NetworkEnforcementMode, + NetworkPolicyRule, ProcessPolicy, SandboxPolicy, }; use prost::Message; @@ -1858,6 +1858,7 @@ fn validate_sandbox_policy_with_mcp_presence( // receive stable validation errors for equivalent policy inputs. let mut network_policies: Vec<_> = policy.network_policies.iter().collect(); network_policies.sort_by_key(|(name, _)| *name); + let mut credential_binding_modes = HashMap::<&str, bool>::new(); // Check network policy endpoint hosts for TLD wildcards. for (key, rule) in network_policies { @@ -1978,6 +1979,54 @@ fn validate_sandbox_policy_with_mcp_presence( .unwrap_or(false), }; let mut l7_errors = validate_l7_endpoint_semantics(&fields); + let credential_bound = + ep.enforcement == NetworkEnforcementMode::EnforceCredentialBound as i32; + if credential_bound { + if ep + .credential_binding + .as_ref() + .is_none_or(|binding| binding.provider.trim().is_empty()) + { + l7_errors.push( + "enforce-credential-bound requires credential_binding.provider".to_string(), + ); + } + if !matches!( + L7Protocol::parse(&ep.protocol), + Some(L7Protocol::Rest | L7Protocol::Mcp) + ) { + l7_errors.push( + "enforce-credential-bound requires rest or mcp inspection".to_string(), + ); + } + if ep.host.contains('*') || ep.host.contains('?') || ep.host.contains('[') { + l7_errors.push("enforce-credential-bound requires an exact host".to_string()); + } + if ep.tls == openshell_core::proto::NetworkTlsMode::Skip as i32 + || ep.allow_uninspected_credentials + || ep.websocket_credential_rewrite + || ep.request_body_credential_rewrite + || !ep.credential_signing.is_empty() + { + l7_errors.push("enforce-credential-bound cannot use uninspected credentials, credential signing, or body/WebSocket rewriting".to_string()); + } + } + if let Some(binding) = &ep.credential_binding { + match credential_binding_modes.entry(binding.provider.as_str()) { + std::collections::hash_map::Entry::Occupied(entry) + if *entry.get() != credential_bound => + { + l7_errors.push(format!( + "provider '{}' cannot mix ordinary and enforce-credential-bound endpoints", + binding.provider + )); + } + std::collections::hash_map::Entry::Vacant(entry) => { + entry.insert(credential_bound); + } + _ => {} + } + } l7_errors.extend(validate_endpoint_mode_values( ep.tls, ep.enforcement, @@ -6067,6 +6116,46 @@ network_policies: assert!(yaml_out.contains("provider: work-gcp")); } + #[test] + fn credential_bound_enforcement_round_trips_and_requires_a_concrete_provider() { + let yaml = "version: 1\nnetwork_policies:\n account:\n endpoints:\n - host: mcp.example.com\n port: 443\n protocol: mcp\n enforcement: enforce-credential-bound\n mcp: {allow_all_known_mcp_methods: true}\n credential_binding: {provider: account-a}\n"; + let policy = parse_sandbox_policy(yaml).expect("account-bound YAML should parse"); + let endpoint = &policy.network_policies["account"].endpoints[0]; + assert_eq!( + endpoint.enforcement, + NetworkEnforcementMode::EnforceCredentialBound as i32 + ); + validate_sandbox_policy(&policy).expect("account-bound endpoint should validate"); + let serialized = serialize_sandbox_policy(&policy).expect("serialize account-bound YAML"); + assert!(serialized.contains("enforce-credential-bound")); + assert_eq!(parse_sandbox_policy(&serialized).unwrap(), policy); + + let mut mixed_case = policy.clone(); + mixed_case + .network_policies + .get_mut("account") + .unwrap() + .endpoints[0] + .protocol = "MCP".to_string(); + validate_sandbox_policy(&mixed_case).expect("established protocol aliases stay valid"); + + let mut missing = policy.clone(); + missing + .network_policies + .get_mut("account") + .unwrap() + .endpoints[0] + .credential_binding = None; + assert!( + validate_sandbox_policy(&missing) + .unwrap_err() + .iter() + .any(|violation| violation + .to_string() + .contains("requires credential_binding.provider")) + ); + } + #[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..5b69d6250e 100644 --- a/crates/openshell-providers/src/profiles.rs +++ b/crates/openshell-providers/src/profiles.rs @@ -2876,6 +2876,14 @@ pub fn validate_catalog_profiles( msg, )); } + if endpoint.enforcement == "enforce-credential-bound" { + diagnostics.push(ProfileValidationDiagnostic::error( + source, + profile_id, + format!("endpoints[{index}]"), + "enforce-credential-bound is only valid on a sandbox policy endpoint with credential_binding.provider", + )); + } for msg in validate_explicit_tcp_additional_fields( &endpoint.protocol, &additional_l7_profile_fields(endpoint), @@ -4019,6 +4027,8 @@ credentials: let binding = |profile: &ProviderTypeProfile| StaticCredentialBinding { credential_identity: profile.id.clone(), workload_credential_handle: String::new(), + request_policy_owners: Vec::new(), + request_policy_provider: String::new(), endpoints: profile .to_proto() .endpoints @@ -7087,6 +7097,20 @@ endpoints: assert!(message.contains("unknown access value 'read-wirte'")); } + #[test] + fn validate_rejects_account_bound_mode_in_provider_profiles() { + let profile = parse_profile_yaml( + "id: account-mode\ndisplay_name: Account mode\nendpoints:\n - host: mcp.example.com\n port: 443\n protocol: mcp\n enforcement: enforce-credential-bound\n mcp: {allow_all_known_mcp_methods: true}\n", + ) + .expect("profile YAML parses"); + let diagnostics = validate_profile_set(&[("account.yaml".to_string(), profile)]); + assert!(diagnostics.iter().any(|diagnostic| { + diagnostic + .message + .contains("only valid on a sandbox policy endpoint") + })); + } + #[test] fn validate_rejects_protocol_without_rules_or_access() { let profile = parse_profile_yaml( diff --git a/crates/openshell-server/src/grpc/policy.rs b/crates/openshell-server/src/grpc/policy.rs index b9d5fa8fff..0012855a87 100644 --- a/crates/openshell-server/src/grpc/policy.rs +++ b/crates/openshell-server/src/grpc/policy.rs @@ -2110,8 +2110,9 @@ fn apply_captured_policy_context( extend_credentialed_scopes_from_policy_bindings( &mut provider_context.credentialed_scopes, &policy_credential_bindings, - &provider_context.endpointless_provider_names, + &provider_context.endpointless_provider_ids, ); + stamp_request_bound_credential_owners(&mut policy, &provider_context.endpointless_provider_ids); stamp_provider_credentialed_endpoints(&mut policy, &provider_context.credentialed_scopes); if matches!(policy_source, PolicySource::Global) { openshell_core::policy_identity::stamp_global_token_grant_owners(&mut policy); @@ -2919,9 +2920,30 @@ pub fn require_policy_capabilities( { return Err(Status::unimplemented(CEDAR_SUPPORT_REQUIRED)); } + if policy.is_some_and(policy_uses_request_bound_credentials) + && !openshell_core::extension_protocol::has_capability( + &supported_capabilities, + openshell_core::extension_protocol::POLICY_REQUEST_BOUND_CREDENTIALS_V1, + ) + { + return Err(Status::unimplemented( + "request-bound credentials require a compatible supervisor", + )); + } Ok(()) } +fn policy_uses_request_bound_credentials(policy: &ProtoSandboxPolicy) -> bool { + policy + .network_policies + .values() + .flat_map(|rule| &rule.endpoints) + .any(|endpoint| { + endpoint.enforcement + == openshell_core::proto::NetworkEnforcementMode::EnforceCredentialBound as i32 + }) +} + /// 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( @@ -3070,10 +3092,14 @@ async fn build_sandbox_config_snapshot_with_sources( extend_credentialed_scopes_from_policy_bindings( &mut provider_policy_context.credentialed_scopes, &policy_credential_bindings, - &provider_policy_context.endpointless_provider_names, + &provider_policy_context.endpointless_provider_ids, ); let mut configuration_error = String::new(); if let Some(effective_policy) = policy.as_mut() { + stamp_request_bound_credential_owners( + effective_policy, + &provider_policy_context.endpointless_provider_ids, + ); stamp_provider_credentialed_endpoints( effective_policy, &provider_policy_context.credentialed_scopes, @@ -3584,7 +3610,7 @@ pub(super) struct CredentialedEndpointScope { struct ProviderPolicyContext { layers: Vec, credentialed_scopes: Vec, - endpointless_provider_names: HashSet, + endpointless_provider_ids: HashMap, } async fn provider_policy_context_with_catalog( @@ -3610,7 +3636,7 @@ fn provider_policy_context_from_records( ) -> ProviderPolicyContext { let mut layers = Vec::new(); let mut credentialed_scopes = Vec::new(); - let mut endpointless_provider_names = HashSet::new(); + let mut endpointless_provider_ids = HashMap::new(); for record in records { let name = &record.name; @@ -3631,7 +3657,7 @@ fn provider_policy_context_from_records( }; if !super::provider::provider_profile_endpoints_are_active(&profile, provider) { - endpointless_provider_names.insert(name.clone()); + endpointless_provider_ids.insert(name.clone(), record.object_id.clone()); continue; } @@ -3643,7 +3669,7 @@ fn provider_policy_context_from_records( endpoint.token_grant_owner = owner; } if rule.endpoints.is_empty() { - endpointless_provider_names.insert(name.clone()); + endpointless_provider_ids.insert(name.clone(), record.object_id.clone()); } if profile.has_credentialed_endpoints() { for endpoint in &mut rule.endpoints { @@ -3667,7 +3693,33 @@ fn provider_policy_context_from_records( ProviderPolicyContext { layers, credentialed_scopes, - endpointless_provider_names, + endpointless_provider_ids, + } +} + +fn stamp_request_bound_credential_owners( + policy: &mut ProtoSandboxPolicy, + provider_ids: &HashMap, +) { + for rule in policy.network_policies.values_mut() { + let baseline = rule.clone(); + for (index, endpoint) in rule.endpoints.iter_mut().enumerate() { + if endpoint.enforcement + != openshell_core::proto::NetworkEnforcementMode::EnforceCredentialBound as i32 + { + continue; + } + let Some(id) = endpoint + .credential_binding + .as_ref() + .and_then(|binding| provider_ids.get(&binding.provider)) + else { + continue; + }; + endpoint.token_grant_owner = + openshell_core::policy_identity::provider_token_grant_owners(id, &baseline)[index] + .clone(); + } } } @@ -3685,10 +3737,10 @@ fn endpoint_ports(endpoint: &NetworkEndpoint) -> Vec { fn extend_credentialed_scopes_from_policy_bindings( scopes: &mut Vec, bindings: &HashMap>, - endpointless_provider_names: &HashSet, + endpointless_provider_ids: &HashMap, ) { for (provider_name, provider_bindings) in bindings { - if !endpointless_provider_names.contains(provider_name) { + if !endpointless_provider_ids.contains_key(provider_name) { continue; } for binding in provider_bindings { @@ -3896,18 +3948,39 @@ 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_request_policy_bound_credentials = + request.get_ref().supports_request_policy_bound_credentials; let principal = crate::auth::guard::enforce_sandbox_scope(&request, &sandbox_id)?; drop(request); let sandbox = super::sandbox::fetch_and_authorize_sandbox(state, &principal, &sandbox_id).await?; - let environment = load_sandbox_provider_environment( + let mut environment = load_sandbox_provider_environment( state, &sandbox, supports_static_credential_bindings, supports_stable_placeholder_environment_keys, ) .await?; + if !supports_request_policy_bound_credentials { + let unsupported: Vec<_> = environment + .static_credential_bindings + .iter() + .filter(|(_, binding)| !binding.request_policy_owners.is_empty()) + .map(|(key, _)| key.clone()) + .collect(); + if !unsupported.is_empty() { + environment.readiness_reason = ProviderReadinessReason::UnsupportedSupervisor as i32; + } + for key in unsupported { + environment.environment.remove(&key); + environment.static_credential_bindings.remove(&key); + environment.credential_expiration_times.remove(&key); + environment + .stable_placeholder_environment_keys + .retain(|candidate| candidate != &key); + } + } Ok(Response::new(environment)) } @@ -4126,6 +4199,40 @@ pub async fn build_provider_environment_snapshot_from_inputs( .dynamic_credentials .extend(static_request_metadata); + for record in provider_records { + let mut owners: Vec<_> = effective_policy + .network_policies + .values() + .flat_map(|rule| &rule.endpoints) + .filter(|endpoint| { + endpoint.enforcement + == openshell_core::proto::NetworkEnforcementMode::EnforceCredentialBound as i32 + && endpoint + .credential_binding + .as_ref() + .is_some_and(|binding| binding.provider == record.name) + }) + .map(|endpoint| endpoint.token_grant_owner.clone()) + .filter(|owner| !owner.is_empty()) + .collect(); + owners.sort(); + owners.dedup(); + if owners.is_empty() { + continue; + } + for key in record + .provider + .credentials + .keys() + .chain(record.provider.credential_handles.keys()) + { + if let Some(binding) = provider_environment.static_credential_bindings.get_mut(key) { + binding.request_policy_owners.clone_from(&owners); + binding.request_policy_provider.clone_from(&record.name); + } + } + } + info!( sandbox_id = %sandbox_id, provider_count = provider_names.len(), @@ -7724,7 +7831,7 @@ struct PolicyCredentialBindingValidationContext<'a> { catalog: &'a EffectiveProviderProfileCatalog, records: &'a [super::provider::ProviderEnvironmentRecord], credentialed_scopes: &'a [CredentialedEndpointScope], - endpointless_provider_names: &'a HashSet, + endpointless_provider_ids: &'a HashMap, } struct SandboxPolicyMergeValidationData { @@ -7732,7 +7839,7 @@ struct SandboxPolicyMergeValidationData { catalog: EffectiveProviderProfileCatalog, records: Vec, credentialed_scopes: Vec, - endpointless_provider_names: HashSet, + endpointless_provider_ids: HashMap, } impl SandboxPolicyMergeValidationData { @@ -7741,7 +7848,7 @@ impl SandboxPolicyMergeValidationData { catalog: &self.catalog, records: &self.records, credentialed_scopes: &self.credentialed_scopes, - endpointless_provider_names: &self.endpointless_provider_names, + endpointless_provider_ids: &self.endpointless_provider_ids, } } } @@ -7785,7 +7892,7 @@ async fn sandbox_policy_merge_validation_data_with_catalog( let ProviderPolicyContext { layers, credentialed_scopes, - endpointless_provider_names, + endpointless_provider_ids, } = provider_policy_context_from_records(catalog, &records); let provider_layers = if composition_enabled { layers @@ -7802,7 +7909,7 @@ async fn sandbox_policy_merge_validation_data_with_catalog( catalog: catalog.clone(), records, credentialed_scopes, - endpointless_provider_names, + endpointless_provider_ids, }) } @@ -7827,7 +7934,7 @@ fn validate_operator_merged_credential_policy( extend_credentialed_scopes_from_policy_bindings( &mut credentialed_scopes, bindings, - context.endpointless_provider_names, + context.endpointless_provider_ids, ); // Recompute the credential flags without clearing owner IDs that provider // composition already derived for this effective policy. @@ -12904,6 +13011,7 @@ mod tests { let environment = handle_get_sandbox_provider_environment( &state, with_user(Request::new(GetSandboxProviderEnvironmentRequest { + supports_request_policy_bound_credentials: true, sandbox_id: "sb-snapshot-consistency".to_string(), supports_static_credential_bindings: true, supports_stable_placeholder_environment_keys: true, @@ -14985,6 +15093,7 @@ mod tests { let legacy_env = handle_get_sandbox_provider_environment( &state, with_user(Request::new(GetSandboxProviderEnvironmentRequest { + supports_request_policy_bound_credentials: true, sandbox_id: "sb-provider-env".to_string(), supports_static_credential_bindings: true, supports_stable_placeholder_environment_keys: true, @@ -14998,6 +15107,7 @@ mod tests { let v2_env = handle_get_sandbox_provider_environment( &state, with_user(Request::new(GetSandboxProviderEnvironmentRequest { + supports_request_policy_bound_credentials: true, sandbox_id: "sb-provider-env".to_string(), supports_static_credential_bindings: true, supports_stable_placeholder_environment_keys: true, @@ -15071,6 +15181,7 @@ mod tests { let response = handle_get_sandbox_provider_environment( &state, with_user(Request::new(GetSandboxProviderEnvironmentRequest { + supports_request_policy_bound_credentials: true, sandbox_id: "sb-files-and-credentials".to_string(), supports_static_credential_bindings: true, supports_stable_placeholder_environment_keys: false, @@ -15131,6 +15242,7 @@ mod tests { let response = handle_get_sandbox_provider_environment( &state, with_user(Request::new(GetSandboxProviderEnvironmentRequest { + supports_request_policy_bound_credentials: true, sandbox_id: "sb-cedar-env".to_string(), supports_static_credential_bindings: true, supports_stable_placeholder_environment_keys: true, @@ -15179,6 +15291,7 @@ mod tests { let response = handle_get_sandbox_provider_environment( &state, with_user(Request::new(GetSandboxProviderEnvironmentRequest { + supports_request_policy_bound_credentials: true, sandbox_id: "sb-static-ready".to_string(), supports_static_credential_bindings: true, supports_stable_placeholder_environment_keys: false, @@ -15238,6 +15351,7 @@ mod tests { let response = handle_get_sandbox_provider_environment( &state, with_user(Request::new(GetSandboxProviderEnvironmentRequest { + supports_request_policy_bound_credentials: true, sandbox_id: "sb-legacy-provider-env".to_string(), supports_static_credential_bindings: false, supports_stable_placeholder_environment_keys: false, @@ -15283,6 +15397,7 @@ mod tests { let response = handle_get_sandbox_provider_environment( &state, with_user(Request::new(GetSandboxProviderEnvironmentRequest { + supports_request_policy_bound_credentials: true, sandbox_id: "sb-unbound-provider-env".to_string(), supports_static_credential_bindings: true, supports_stable_placeholder_environment_keys: true, @@ -15399,6 +15514,7 @@ mod tests { let incompatible_environment = handle_get_sandbox_provider_environment( &state, with_user(Request::new(GetSandboxProviderEnvironmentRequest { + supports_request_policy_bound_credentials: true, sandbox_id: "sb-policy-binding".to_string(), supports_static_credential_bindings: supports_bindings, supports_stable_placeholder_environment_keys: supports_stable, @@ -15443,6 +15559,7 @@ mod tests { let environment = handle_get_sandbox_provider_environment( &state, with_user(Request::new(GetSandboxProviderEnvironmentRequest { + supports_request_policy_bound_credentials: true, sandbox_id: "sb-policy-binding".to_string(), supports_static_credential_bindings: true, supports_stable_placeholder_environment_keys: true, @@ -15522,6 +15639,7 @@ mod tests { let next_environment = handle_get_sandbox_provider_environment( &state, with_user(Request::new(GetSandboxProviderEnvironmentRequest { + supports_request_policy_bound_credentials: true, sandbox_id: "sb-policy-binding".to_string(), supports_static_credential_bindings: true, supports_stable_placeholder_environment_keys: true, @@ -15589,6 +15707,7 @@ mod tests { let unbound_environment = handle_get_sandbox_provider_environment( &state, with_user(Request::new(GetSandboxProviderEnvironmentRequest { + supports_request_policy_bound_credentials: true, sandbox_id: "sb-policy-binding".to_string(), supports_static_credential_bindings: true, supports_stable_placeholder_environment_keys: true, @@ -15686,6 +15805,7 @@ mod tests { let response = handle_get_sandbox_provider_environment( &state, with_user(Request::new(GetSandboxProviderEnvironmentRequest { + supports_request_policy_bound_credentials: true, sandbox_id: "sb-mixed-provider-env".to_string(), supports_static_credential_bindings: true, supports_stable_placeholder_environment_keys: true, @@ -15795,6 +15915,7 @@ mod tests { let response = handle_get_sandbox_provider_environment( &state, with_user(Request::new(GetSandboxProviderEnvironmentRequest { + supports_request_policy_bound_credentials: true, sandbox_id: "sb-token-exchange-subject".to_string(), supports_static_credential_bindings: true, supports_stable_placeholder_environment_keys: true, @@ -15863,6 +15984,7 @@ mod tests { let first = handle_get_sandbox_provider_environment( &state, with_user(Request::new(GetSandboxProviderEnvironmentRequest { + supports_request_policy_bound_credentials: true, sandbox_id: "sb-provider-revision".to_string(), supports_static_credential_bindings: true, supports_stable_placeholder_environment_keys: true, @@ -15903,6 +16025,7 @@ mod tests { let second = handle_get_sandbox_provider_environment( &state, with_user(Request::new(GetSandboxProviderEnvironmentRequest { + supports_request_policy_bound_credentials: true, sandbox_id: "sb-provider-revision".to_string(), supports_static_credential_bindings: true, supports_stable_placeholder_environment_keys: true, @@ -16567,6 +16690,7 @@ mod tests { let baseline_env = handle_get_sandbox_provider_environment( &state, with_user(Request::new(GetSandboxProviderEnvironmentRequest { + supports_request_policy_bound_credentials: true, sandbox_id: "sb-attach-lifecycle".to_string(), supports_static_credential_bindings: true, supports_stable_placeholder_environment_keys: true, @@ -16601,6 +16725,7 @@ mod tests { let attached_env = handle_get_sandbox_provider_environment( &state, with_user(Request::new(GetSandboxProviderEnvironmentRequest { + supports_request_policy_bound_credentials: true, sandbox_id: "sb-attach-lifecycle".to_string(), supports_static_credential_bindings: true, supports_stable_placeholder_environment_keys: true, @@ -16643,6 +16768,7 @@ mod tests { let detached_env = handle_get_sandbox_provider_environment( &state, with_user(Request::new(GetSandboxProviderEnvironmentRequest { + supports_request_policy_bound_credentials: true, sandbox_id: "sb-attach-lifecycle".to_string(), supports_static_credential_bindings: true, supports_stable_placeholder_environment_keys: true, @@ -16748,6 +16874,7 @@ mod tests { let baseline_env = handle_get_sandbox_provider_environment( &state, with_user(Request::new(GetSandboxProviderEnvironmentRequest { + supports_request_policy_bound_credentials: true, sandbox_id: "sb-attach-lifecycle".to_string(), supports_static_credential_bindings: true, supports_stable_placeholder_environment_keys: true, @@ -16785,6 +16912,7 @@ mod tests { let attached_env = handle_get_sandbox_provider_environment( &state, with_user(Request::new(GetSandboxProviderEnvironmentRequest { + supports_request_policy_bound_credentials: true, sandbox_id: "sb-attach-lifecycle".to_string(), supports_static_credential_bindings: true, supports_stable_placeholder_environment_keys: true, @@ -16826,6 +16954,7 @@ mod tests { let detached_env = handle_get_sandbox_provider_environment( &state, with_user(Request::new(GetSandboxProviderEnvironmentRequest { + supports_request_policy_bound_credentials: true, sandbox_id: "sb-attach-lifecycle".to_string(), supports_static_credential_bindings: true, supports_stable_placeholder_environment_keys: true, @@ -26847,6 +26976,7 @@ mod tests { let err = handle_get_sandbox_provider_environment( &state, non_member_request(GetSandboxProviderEnvironmentRequest { + supports_request_policy_bound_credentials: true, sandbox_id: "sandbox-other".into(), supports_static_credential_bindings: true, supports_stable_placeholder_environment_keys: true, 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..08499d7896 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 @@ -288,3 +288,234 @@ async fn global_policy_replaces_grant_authorities_and_preserves_profile_destinat .all(|credential| !credential.token_grant_owners.contains(&previous_owner)) ); } + +#[tokio::test] +async fn two_static_provider_bindings_activate_with_distinct_policy_owners() { + use crate::grpc::test_support::authed_request; + use openshell_core::proto::{NetworkCredentialBinding, NetworkPolicyRule, UpdateConfigRequest}; + + let state = test_server_state().await; + for (name, profile_id, key, token) in [ + ("static-a", "static-a-profile", "ACCOUNT_A", "token-a"), + ("static-b", "static-b-profile", "ACCOUNT_B", "token-b"), + ] { + store_profile( + &state, + ProviderProfile { + id: profile_id.into(), + display_name: profile_id.into(), + credentials: vec![ProviderProfileCredential { + name: key.into(), + env_vars: vec![key.into()], + auth_style: "bearer".into(), + header_name: "Authorization".into(), + ..Default::default() + }], + ..Default::default() + }, + ) + .await; + let mut provider = tests::test_provider(name, profile_id); + provider.profile_workspace.clear(); + provider.credentials = HashMap::from([(key.into(), token.into())]); + state.store.put_message(&provider).await.unwrap(); + } + let mut sandbox = tests::test_sandbox( + "sb-static-accounts", + "static-accounts", + ProtoSandboxPolicy::default(), + vec!["static-a".into(), "static-b".into()], + ); + sandbox.spec.as_mut().unwrap().policy = None; + state.store.put_message(&sandbox).await.unwrap(); + let mut policy = ProtoSandboxPolicy { + version: 1, + filesystem: Some(openshell_core::proto::FilesystemPolicy { + include_workdir: true, + ..Default::default() + }), + process: Some(openshell_core::proto::ProcessPolicy { + run_as_user: "sandbox".into(), + run_as_group: "sandbox".into(), + }), + landlock: Some(openshell_core::proto::LandlockPolicy { + compatibility: "best_effort".into(), + }), + ..Default::default() + }; + for (name, tools) in [ + ("static-a", vec!["search"]), + ("static-b", vec!["search", "send"]), + ] { + policy.network_policies.insert( + name.into(), + NetworkPolicyRule { + name: name.into(), + binaries: vec![NetworkBinary { + path: "/usr/bin/curl".into(), + }], + endpoints: vec![NetworkEndpoint { + host: "api.example.test".into(), + port: 8080, + path: "/mcp".into(), + protocol: "mcp".into(), + enforcement: NetworkEnforcementMode::EnforceCredentialBound.into(), + mcp: Some(openshell_core::proto::McpOptions { + versions: vec!["2025-11-25".into()], + ..Default::default() + }), + rules: vec![openshell_core::proto::L7Rule { + allow: Some(openshell_core::proto::L7Allow { + method: "tools/call".into(), + params: HashMap::from([( + "name".into(), + openshell_core::proto::L7QueryMatcher { + any: tools.into_iter().map(str::to_string).collect(), + ..Default::default() + }, + )]), + ..Default::default() + }), + }], + credential_binding: Some(NetworkCredentialBinding { + provider: name.into(), + }), + ..Default::default() + }], + }, + ); + } + handle_update_config( + &state, + authed_request(UpdateConfigRequest { + sandbox: "static-accounts".into(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), + policy: Some(policy), + ..Default::default() + }), + ) + .await + .expect("activate two accounts without ambiguous provider selection"); + let config = load_sandbox_config(&state, &sandbox).await.unwrap(); + let policy = config.policy.unwrap(); + let snapshot = build_provider_environment_snapshot(&state, &sandbox, true, true) + .await + .unwrap(); + for (key, provider) in [("ACCOUNT_A", "static-a"), ("ACCOUNT_B", "static-b")] { + let endpoint = &policy.network_policies[provider].endpoints[0]; + assert!(!endpoint.token_grant_owner.is_empty()); + let value = snapshot + .values + .iter() + .find(|value| value.name == key) + .unwrap(); + assert_eq!( + value + .static_credential_binding + .as_ref() + .unwrap() + .request_policy_owners, + vec![endpoint.token_grant_owner.clone()] + ); + } + assert_ne!( + policy.network_policies["static-a"].endpoints[0].token_grant_owner, + policy.network_policies["static-b"].endpoints[0].token_grant_owner + ); + for supported in [false, true] { + let polled = handle_get_sandbox_provider_environment( + &state, + authed_request( + openshell_core::proto::GetSandboxProviderEnvironmentRequest { + sandbox_id: "sb-static-accounts".into(), + supports_static_credential_bindings: true, + supports_stable_placeholder_environment_keys: true, + supports_request_policy_bound_credentials: supported, + }, + ), + ) + .await + .unwrap() + .into_inner(); + assert_eq!( + polled.environment.contains_key("ACCOUNT_A"), + supported, + "startup polling must refuse an old supervisor and deliver to a capable one" + ); + } + assert!( + require_policy_capabilities(Vec::new(), Some(&policy)).is_err(), + "old pushed supervisor must be rejected" + ); + assert!( + require_policy_capabilities( + vec![ + openshell_core::extension_protocol::POLICY_REQUEST_BOUND_CREDENTIALS_V1.to_string() + ], + Some(&policy) + ) + .is_ok() + ); + let environment = + openshell_core::grpc_client::ProviderEnvironmentResult::try_from(snapshot.clone()).unwrap(); + openshell_core::provider_credentials::validate_request_bound_credential_snapshot( + &policy, + &environment.static_credential_bindings, + ) + .unwrap(); + let mut swapped = environment.static_credential_bindings.clone(); + let b_owners = swapped["ACCOUNT_B"].request_policy_owners.clone(); + swapped.get_mut("ACCOUNT_A").unwrap().request_policy_owners = b_owners; + assert!( + openshell_core::provider_credentials::validate_request_bound_credential_snapshot( + &policy, &swapped + ) + .is_err(), + "account A cannot use account B's owners" + ); + let mut stripped = environment.static_credential_bindings.clone(); + stripped + .get_mut("ACCOUNT_A") + .unwrap() + .request_policy_owners + .clear(); + assert!( + openshell_core::provider_credentials::validate_request_bound_credential_snapshot( + &policy, &stripped + ) + .is_err(), + "stripped metadata must not activate" + ); + let mut remaining = policy.clone(); + remaining + .network_policies + .retain(|name, _| !openshell_policy::is_provider_rule_name(name)); + remaining.network_policies.remove("static-b"); + handle_update_config( + &state, + authed_request(UpdateConfigRequest { + sandbox: "static-accounts".into(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), + policy: Some(remaining), + ..Default::default() + }), + ) + .await + .expect("withdraw account B"); + let remaining_snapshot = build_provider_environment_snapshot(&state, &sandbox, true, true) + .await + .unwrap(); + let a = remaining_snapshot + .values + .iter() + .find(|value| value.name == "ACCOUNT_A") + .unwrap(); + assert!( + !a.static_credential_binding + .as_ref() + .unwrap() + .request_policy_owners + .is_empty(), + "remaining account stays restricted after withdrawal" + ); +} diff --git a/crates/openshell-server/src/grpc/provider.rs b/crates/openshell-server/src/grpc/provider.rs index 277174f49c..776d5cd2cd 100644 --- a/crates/openshell-server/src/grpc/provider.rs +++ b/crates/openshell-server/src/grpc/provider.rs @@ -1807,6 +1807,8 @@ fn static_credential_binding( format!("refresh:{workload_credential_handle}") }; StaticCredentialBinding { + request_policy_provider: String::new(), + request_policy_owners: Vec::new(), endpoints: endpoints.to_vec(), credential_identity, workload_credential_handle, diff --git a/crates/openshell-supervisor-network/src/google_cloud_metadata.rs b/crates/openshell-supervisor-network/src/google_cloud_metadata.rs index ea5d0c16bd..63f5f7d9e5 100644 --- a/crates/openshell-supervisor-network/src/google_cloud_metadata.rs +++ b/crates/openshell-supervisor-network/src/google_cloud_metadata.rs @@ -376,6 +376,8 @@ mod tests { fn token_binding() -> openshell_core::proto::StaticCredentialBinding { openshell_core::proto::StaticCredentialBinding { + request_policy_provider: String::new(), + request_policy_owners: Vec::new(), endpoints: vec![openshell_core::proto::StaticCredentialEndpointBinding { host: "storage.googleapis.com".into(), port: 443, diff --git a/crates/openshell-supervisor-network/src/l7/relay.rs b/crates/openshell-supervisor-network/src/l7/relay.rs index 4512dce4cb..28d949052d 100644 --- a/crates/openshell-supervisor-network/src/l7/relay.rs +++ b/crates/openshell-supervisor-network/src/l7/relay.rs @@ -140,6 +140,14 @@ fn request_default_port(ctx: &L7EvalContext) -> Option { fn scoped_context_for_request( ctx: &L7EvalContext, request: &crate::l7::provider::L7Request, +) -> Option { + scoped_context_for_request_with_owners(ctx, request, None) +} + +fn scoped_context_for_request_with_owners( + ctx: &L7EvalContext, + request: &crate::l7::provider::L7Request, + admitted_owners: Option<&HashSet>, ) -> Option { let mut scoped = ctx.clone(); if matches!( @@ -160,8 +168,13 @@ fn scoped_context_for_request( return Some(scoped); } let credentials = ctx.provider_credentials.as_ref()?; - let (resolver, classifier, revision) = - credentials.resolver_and_body_classifier_for_endpoint(&ctx.host, ctx.port, &request.target); + let (resolver, classifier, revision) = credentials + .resolver_and_body_classifier_for_endpoint_with_owners( + &ctx.host, + ctx.port, + &request.target, + admitted_owners, + ); scoped.secret_resolver = resolver; scoped.body_classifier = classifier; scoped.provider_credential_revision = Some(revision); @@ -211,7 +224,18 @@ pub(crate) async fn prepare_inspected_request( .values() .any(|credential| credential.token_grant.is_some()) }); - let (req, injected) = if let Some(snapshot) = grant_snapshot { + let needs_owners = grant_snapshot.is_some() + || scoped + .provider_credentials + .as_ref() + .is_some_and(|credentials| { + credentials.has_request_policy_bound_credentials_for_endpoint( + &scoped.host, + scoped.port, + &req.target, + ) + }); + let owners = if needs_owners { // Middleware can replace an inspected body. Recompute owner admission for // the body that will be sent, even when another endpoint allowed both the // original and transformed requests. Request method/path/query are immutable. @@ -241,12 +265,16 @@ pub(crate) async fn prepare_inspected_request( } L7Protocol::Rest | L7Protocol::Websocket | L7Protocol::Sql => {} } - let owners = admitted_token_grant_owners(engine, &scoped, ¤t_info)?; + Some(admitted_token_grant_owners(engine, &scoped, ¤t_info)?) + } else { + None + }; + let (req, injected) = if let Some(snapshot) = grant_snapshot { crate::l7::token_grant_injection::inject_for_admitted_owners_correlated( req, &scoped, snapshot, - &owners, + owners.as_ref().expect("grant request has admitted owners"), request_id, observation_context.filter(|context| { let policy_hash = @@ -268,7 +296,8 @@ pub(crate) async fn prepare_inspected_request( if let Some(guard) = credential_generation_guard(&scoped) { guard.ensure_current()?; } - let scoped = scoped_context_for_request(&scoped, &req).unwrap_or(scoped); + let scoped = + scoped_context_for_request_with_owners(&scoped, &req, owners.as_ref()).unwrap_or(scoped); Ok((req, scoped, injected)) } @@ -5150,6 +5179,8 @@ mod tests { fn endpoint_binding(identity: &str) -> StaticCredentialBinding { StaticCredentialBinding { + request_policy_provider: String::new(), + request_policy_owners: Vec::new(), endpoints: vec![StaticCredentialEndpointBinding { host: "allowed.example.test".to_string(), port: 443, @@ -7869,6 +7900,8 @@ network_policies: TestHashMap::from([( "API_TOKEN".to_string(), StaticCredentialBinding { + request_policy_provider: String::new(), + request_policy_owners: Vec::new(), endpoints: vec![StaticCredentialEndpointBinding { host: "api.example.test".to_string(), port: 8080, @@ -7973,6 +8006,8 @@ network_policies: TestHashMap::from([( "API_TOKEN".to_string(), StaticCredentialBinding { + request_policy_provider: String::new(), + request_policy_owners: Vec::new(), endpoints: vec![StaticCredentialEndpointBinding { host: "api.example.test".to_string(), port: u32::from(port), @@ -8628,6 +8663,8 @@ network_policies: TestHashMap::from([( "API_TOKEN".to_string(), StaticCredentialBinding { + request_policy_provider: String::new(), + request_policy_owners: Vec::new(), endpoints: vec![StaticCredentialEndpointBinding { host: "api.example.test".to_string(), port: 443, @@ -9848,6 +9885,8 @@ network_policies: TestHashMap::from([( "API_TOKEN".into(), StaticCredentialBinding { + request_policy_provider: String::new(), + request_policy_owners: Vec::new(), endpoints: vec![StaticCredentialEndpointBinding { host: "api.example.test".into(), port: 8080, @@ -11881,6 +11920,8 @@ network_policies: TestHashMap::from([( "API_TOKEN".to_string(), StaticCredentialBinding { + request_policy_provider: String::new(), + request_policy_owners: Vec::new(), endpoints: vec![StaticCredentialEndpointBinding { host: "allowed.example.test".to_string(), port: 443, @@ -15774,6 +15815,8 @@ network_policies: TestHashMap::from([( "API_TOKEN".into(), StaticCredentialBinding { + request_policy_provider: String::new(), + request_policy_owners: Vec::new(), endpoints: vec![StaticCredentialEndpointBinding { host: ctx.host.clone(), port: u32::from(ctx.port), diff --git a/crates/openshell-supervisor-network/src/l7/relay/token_grant_ownership_tests.rs b/crates/openshell-supervisor-network/src/l7/relay/token_grant_ownership_tests.rs index 4357309eb8..82390a874a 100644 --- a/crates/openshell-supervisor-network/src/l7/relay/token_grant_ownership_tests.rs +++ b/crates/openshell-supervisor-network/src/l7/relay/token_grant_ownership_tests.rs @@ -1984,3 +1984,84 @@ async fn response_middleware_sees_the_forwarded_request_head_without_injected_gr ] ); } + +#[tokio::test] +async fn static_accounts_share_an_mcp_endpoint_without_sharing_authority() { + use openshell_core::proto::{StaticCredentialBinding, StaticCredentialEndpointBinding}; + + let mut a = route("a-search", "/mcp"); + a.protocol = "mcp"; + a.method = "search"; + let mut b_search = route("b-search", "/mcp"); + b_search.protocol = "mcp"; + b_search.method = "search"; + let mut b_send = route("b-send", "/mcp"); + b_send.protocol = "mcp"; + b_send.method = "send"; + let mut fixture = Fixture::new(&[a, b_search, b_send], &[], 3); + let binding = |identity: &str, owners: &[&str]| StaticCredentialBinding { + request_policy_provider: identity.split(':').next().unwrap().into(), + endpoints: vec![StaticCredentialEndpointBinding { + host: HOST.into(), + port: PORT.into(), + path: "/mcp".into(), + }], + credential_identity: identity.into(), + workload_credential_handle: String::new(), + request_policy_owners: owners.iter().map(|owner| (*owner).to_string()).collect(), + }; + fixture.state = ProviderCredentialState::from_bound_environment( + 1, + HashMap::from([ + ("ACCOUNT_A".into(), "token-a".into()), + ("ACCOUNT_B".into(), "token-b".into()), + ]), + HashMap::new(), + HashMap::new(), + HashMap::from([ + ( + "ACCOUNT_A".into(), + binding("provider-a:ACCOUNT_A", &["a-search"]), + ), + ( + "ACCOUNT_B".into(), + binding("provider-b:ACCOUNT_B", &["b-search", "b-send"]), + ), + ]), + Vec::new(), + ) + .unwrap(); + let issued = fixture.state.snapshot().child_env.clone(); + for (account, tool, token) in [ + ("ACCOUNT_A", "search", Some("token-a")), + ("ACCOUNT_B", "search", Some("token-b")), + ("ACCOUNT_B", "send", Some("token-b")), + ("ACCOUNT_A", "send", None), + ] { + let mut connection = fixture.connect(); + let body = native_protocol_body("mcp", tool); + let head = format!( + "POST /mcp HTTP/1.1\r\nHost: {HOST}:{PORT}\r\nMCP-Protocol-Version: 2025-11-25\r\nAuthorization: Bearer {}\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n", + issued[account], + body.len() + ); + connection.app.write_all(head.as_bytes()).await.unwrap(); + connection.app.write_all(&body).await.unwrap(); + let response = connection.response().await; + let capture = connection.finish().await; + if let Some(token) = token { + assert!( + response.starts_with("HTTP/1.1 204"), + "{account}/{tool}: {response}" + ); + assert_eq!(capture.requests.len(), 1); + assert!(capture.requests[0].contains(&format!("Authorization: Bearer {token}"))); + } else { + assert!(!response.starts_with("HTTP/1.1 204")); + assert_eq!( + capture.bytes_seen, 0, + "mismatched account must be denied before upstream" + ); + } + } +} diff --git a/crates/openshell-supervisor-network/src/l7/rest.rs b/crates/openshell-supervisor-network/src/l7/rest.rs index af73e7bdc5..d17bf23bcb 100644 --- a/crates/openshell-supervisor-network/src/l7/rest.rs +++ b/crates/openshell-supervisor-network/src/l7/rest.rs @@ -11301,6 +11301,8 @@ mod tests { ( key.clone(), StaticCredentialBinding { + request_policy_provider: String::new(), + request_policy_owners: Vec::new(), credential_identity: format!("fixture:{key}"), workload_credential_handle: String::new(), endpoints: vec![StaticCredentialEndpointBinding { @@ -11518,6 +11520,8 @@ mod tests { HashMap::from([( "GITHUB_TOKEN".into(), StaticCredentialBinding { + request_policy_provider: String::new(), + request_policy_owners: Vec::new(), credential_identity: "github".into(), workload_credential_handle: String::new(), endpoints: vec![StaticCredentialEndpointBinding { diff --git a/crates/openshell-supervisor-network/src/l7/websocket.rs b/crates/openshell-supervisor-network/src/l7/websocket.rs index dae95cf6d2..9d29bfdb58 100644 --- a/crates/openshell-supervisor-network/src/l7/websocket.rs +++ b/crates/openshell-supervisor-network/src/l7/websocket.rs @@ -2691,6 +2691,8 @@ network_policies: HashMap::from([( "DISCORD_BOT_TOKEN".to_string(), StaticCredentialBinding { + request_policy_provider: String::new(), + request_policy_owners: Vec::new(), endpoints: vec![StaticCredentialEndpointBinding { host: "gateway.example.test".to_string(), port: 443, @@ -2840,6 +2842,8 @@ network_policies: HashMap::from([( "DISCORD_BOT_TOKEN".to_string(), StaticCredentialBinding { + request_policy_provider: String::new(), + request_policy_owners: Vec::new(), endpoints: vec![StaticCredentialEndpointBinding { host: "gateway.example.test".into(), port: 443, diff --git a/crates/openshell-supervisor-network/src/proxy.rs b/crates/openshell-supervisor-network/src/proxy.rs index 5226f66d2c..20727d275f 100644 --- a/crates/openshell-supervisor-network/src/proxy.rs +++ b/crates/openshell-supervisor-network/src/proxy.rs @@ -14009,6 +14009,8 @@ network_policies: TestHashMap::from([( "API_TOKEN".to_string(), StaticCredentialBinding { + request_policy_provider: String::new(), + request_policy_owners: Vec::new(), endpoints: vec![StaticCredentialEndpointBinding { host: "api.example.test".to_string(), port: 80, @@ -16440,6 +16442,8 @@ network_policies: TestHashMap::from([( "API_TOKEN".to_string(), StaticCredentialBinding { + request_policy_provider: String::new(), + request_policy_owners: Vec::new(), endpoints: vec![StaticCredentialEndpointBinding { host: "api.example.com".to_string(), port: 80, @@ -16485,6 +16489,8 @@ network_policies: TestHashMap::from([( "API_TOKEN".to_string(), StaticCredentialBinding { + request_policy_provider: String::new(), + request_policy_owners: Vec::new(), endpoints: vec![StaticCredentialEndpointBinding { host: "api.example.com".to_string(), port: 80, @@ -16531,6 +16537,8 @@ network_policies: TestHashMap::from([( "API_TOKEN".to_string(), StaticCredentialBinding { + request_policy_provider: String::new(), + request_policy_owners: Vec::new(), endpoints: vec![StaticCredentialEndpointBinding { host: "api.example.com".to_string(), port: 80, @@ -17233,6 +17241,8 @@ network_policies: TestHashMap::from([( "BOT_TOKEN".into(), StaticCredentialBinding { + request_policy_provider: String::new(), + request_policy_owners: Vec::new(), credential_identity: "provider:BOT_TOKEN".into(), workload_credential_handle: String::new(), endpoints: vec![StaticCredentialEndpointBinding { @@ -17295,6 +17305,8 @@ network_policies: TestHashMap::from([( "API_KEY".into(), StaticCredentialBinding { + request_policy_provider: String::new(), + request_policy_owners: Vec::new(), credential_identity: "provider".into(), workload_credential_handle: String::new(), endpoints: vec![StaticCredentialEndpointBinding { @@ -17442,6 +17454,8 @@ network_policies: TestHashMap::from([( "API_TOKEN".to_string(), StaticCredentialBinding { + request_policy_provider: String::new(), + request_policy_owners: Vec::new(), endpoints: vec![StaticCredentialEndpointBinding { host: "allowed.example.com".to_string(), port: 80, @@ -17534,6 +17548,8 @@ network_policies: ( key.clone(), StaticCredentialBinding { + request_policy_provider: String::new(), + request_policy_owners: Vec::new(), endpoints: vec![StaticCredentialEndpointBinding { host: "allowed.example.com".to_string(), port: 80, diff --git a/crates/openshell-supervisor-network/src/proxy/relay.rs b/crates/openshell-supervisor-network/src/proxy/relay.rs index 2a6eeab907..32e7941321 100644 --- a/crates/openshell-supervisor-network/src/proxy/relay.rs +++ b/crates/openshell-supervisor-network/src/proxy/relay.rs @@ -2283,6 +2283,8 @@ network_policies: ( key.to_string(), openshell_core::proto::StaticCredentialBinding { + request_policy_provider: String::new(), + request_policy_owners: Vec::new(), endpoints: vec![openshell_core::proto::StaticCredentialEndpointBinding { host: "example.com".to_string(), port: 80, diff --git a/crates/openshell-supervisor/src/config_runtime.rs b/crates/openshell-supervisor/src/config_runtime.rs index 46c4f8751b..b7d39802a0 100644 --- a/crates/openshell-supervisor/src/config_runtime.rs +++ b/crates/openshell-supervisor/src/config_runtime.rs @@ -775,6 +775,26 @@ impl ConfigRuntime { }); } }; + let valid = result.policy.as_ref().map_or(Ok(()), |policy| { + openshell_core::provider_credentials::validate_request_bound_credential_snapshot( + policy, + &provider.static_credential_bindings, + ) + }); + if let Err(error) = valid { + self.revoke_provider_environment( + ctx, + desired_identity.clone(), + ProviderReadinessReason::CredentialInstallFailed, + result.provider_env_revision, + ) + .await; + return Err(ConfigRejection { + code: "invalid_provider_environment", + detail: error.to_string(), + admission_error: error.to_string(), + }); + } if let Ok(prepared) = CapturedProviderEnvironment::prepare(&provider) { return Ok(prepared); } @@ -940,7 +960,12 @@ impl ConfigRuntime { None } else { match self - .prepare_delivered_provider(ctx, provider_environment, &desired_environment) + .prepare_delivered_provider( + ctx, + provider_environment, + &desired_environment, + snapshot.policy.as_ref(), + ) .await { Ok(prepared) => Some(prepared), @@ -1091,6 +1116,7 @@ impl ConfigRuntime { ctx: &PolicyPollLoopContext, snapshot: openshell_core::proto::ProviderEnvironmentSnapshot, desired: &EnvironmentIdentity, + policy: Option<&openshell_core::proto::SandboxPolicy>, ) -> std::result::Result { let identity = EnvironmentIdentity { attachment_epoch: snapshot.provider_attachment_epoch.clone(), @@ -1124,6 +1150,10 @@ impl ConfigRuntime { true, ) } + Ok(provider) if policy.is_some_and(|policy| openshell_core::provider_credentials::validate_request_bound_credential_snapshot(policy, &provider.static_credential_bindings).is_err()) => { + self.revoke_provider_environment(ctx, desired.clone(), ProviderReadinessReason::CredentialInstallFailed, revision).await; + config_apply_failure("invalid_provider_environment", "request-bound credential metadata is invalid", false) + } Ok(provider) => match CapturedProviderEnvironment::prepare(&provider) { Ok(prepared) => return Ok(prepared), Err(error) => { @@ -2002,6 +2032,8 @@ mod tests { result.static_credential_bindings.insert( "EXTERNAL_TOKEN".into(), StaticCredentialBinding { + request_policy_provider: String::new(), + request_policy_owners: Vec::new(), endpoints: vec![StaticCredentialEndpointBinding { host: "tools.example.com".into(), port: 443, diff --git a/crates/openshell-supervisor/src/lib.rs b/crates/openshell-supervisor/src/lib.rs index 3ec4035113..167b5ed7b0 100644 --- a/crates/openshell-supervisor/src/lib.rs +++ b/crates/openshell-supervisor/src/lib.rs @@ -2241,10 +2241,13 @@ async fn flush_activity_to_gateway( /// Versioned policy capabilities compiled into this supervisor. fn supported_policy_capabilities() -> Vec { - openshell_core::extension_protocol::capabilities_if( + let mut capabilities = openshell_core::extension_protocol::capabilities_if( openshell_core::extension_protocol::POLICY_CEDAR_V1, cfg!(feature = "experimental"), - ) + ); + capabilities + .push(openshell_core::extension_protocol::POLICY_REQUEST_BOUND_CREDENTIALS_V1.to_string()); + capabilities } /// Minimum read-only paths required for a proxy-mode sandbox child process to @@ -3472,6 +3475,11 @@ fn prepare_startup_configuration( // it builds, as a reload validates while staging. A Cedar policy builds // no OPA engine (see `openshell_supervisor_network::policy_engine`), and // a build without Cedar support rejects it here. + openshell_core::provider_credentials::validate_request_bound_credential_snapshot( + policy, + &provider.static_credential_bindings, + ) + .map_err(|error| miette::miette!("Provider credential bindings are invalid: {error}"))?; let engine = policy_runtime::from_proto(policy)?; let mut process_policy = SandboxPolicy::try_from(policy.clone())?; let filesystem = engine.effective_filesystem(policy)?; diff --git a/docs/how-it-works/policies/schema.mdx b/docs/how-it-works/policies/schema.mdx index bb87555ab0..c25aeac1df 100644 --- a/docs/how-it-works/policies/schema.mdx +++ b/docs/how-it-works/policies/schema.mdx @@ -160,7 +160,7 @@ the gateway host. |---|---|---|---| | `protocol` | string | None | `rest`, `websocket`, `graphql`, `mcp`, or `json-rpc` for request inspection, or `tcp` for a native TCP connection. `rest`, `graphql`, `mcp`, and `json-rpc` endpoints refuse requests that carry an `Upgrade` header with `403`. Refer to [Connection and Request Checks](/how-it-works/policies/network-rules#connection-and-request-checks). | | `tls` | string | Automatic | `skip` relays traffic without terminating TLS, so OpenShell cannot inspect it. Do not use it with a request protocol. | -| `enforcement` | string | `audit` | `enforce` blocks requests that break the endpoint's rules. `audit` logs them and allows the request. | +| `enforcement` | string | `audit` | `enforce` blocks requests that break the endpoint's rules. `enforce-credential-bound` also requires the selected credential's own rule to allow the request. `audit` logs violations and allows the request. | | `access` | string | None | Access preset: `read-only`, `read-write`, or `full`. Refer to [Access Presets](#access-presets). | | `rules` | list | None | Allow rules. | | `deny_rules` | list | None | Deny rules, which take precedence over allow rules. | @@ -227,7 +227,9 @@ OpenShell rejects an endpoint that breaks these rules: - Endpoints whose hosts can match the same name on the same port, including through wildcards, must use the same `tls` and `allowed_ips` values. Inspected endpoints that can match the same request must also agree on - `protocol`, `enforcement`, and credential settings. + `protocol`, `enforcement`, and credential settings. Exact matching endpoints + can bind different providers when each uses `enforce-credential-bound`. See + [Independent Accounts on One Endpoint](/how-it-works/providers/profiles#independent-accounts-on-one-endpoint). Without `protocol`, `access` and `rules` have no effect. diff --git a/docs/how-it-works/providers/profiles.mdx b/docs/how-it-works/providers/profiles.mdx index 9b083fe05e..38168b7b15 100644 --- a/docs/how-it-works/providers/profiles.mdx +++ b/docs/how-it-works/providers/profiles.mdx @@ -248,13 +248,63 @@ When upgrading from revision-scoped refresh placeholders to stable refresh handles, restart each existing workload once so it receives the new placeholder. Later access-token rotations do not require workload restarts. +### Independent Accounts on One Endpoint + +Use `enforcement: enforce-credential-bound` when two attached providers need +different permissions at the same inspected endpoint. Each provider must use an +endpointless profile and a distinct credential environment key. The caller +chooses an account by sending its placeholder. OpenShell checks that account's +own rule before resolving the placeholder. + +For example, `account-a` can search, while `account-b` can search and send: + +```yaml showLineNumbers={false} +network_policies: + account_a: + binaries: [{path: /usr/bin/python3}] + endpoints: + - host: mcp.example.com + port: 443 + path: /mcp + protocol: mcp + enforcement: enforce-credential-bound + credential_binding: {provider: account-a} + mcp: {allow_all_known_mcp_methods: true} + rules: + - allow: {tool: search} + account_b: + binaries: [{path: /usr/bin/python3}] + endpoints: + - host: mcp.example.com + port: 443 + path: /mcp + protocol: mcp + enforcement: enforce-credential-bound + credential_binding: {provider: account-b} + mcp: {allow_all_known_mcp_methods: true} + rules: + - allow: {tool: {any: [search, send]}} +``` + +An attempt to call `send` with account A's placeholder is rejected before +forwarding. Account B's permission cannot authorize account A's credential. +Explicit deny rules still take precedence across matching endpoints. Keep the +mode on account A if account B is removed. + +This mode requires a supporting Gateway and supervisor. It applies to explicit +REST and MCP bindings in YAML sandbox policy, not provider profile endpoints or +Cedar policy. All endpoints bound to the same provider must use the same mode; +signing, body rewriting, and WebSocket rewriting are unsupported. Overlapping +account bindings must have the same exact destination and compatible inspection +settings; an ordinary credential binding cannot overlap them. + ## Roadmap The following provider profile design items are not part of the current behavior: | Roadmap item | Current behavior | |---|---| -| Binary-scoped credential injection | Static placeholder resolution is endpoint-scoped. Dynamic grants in single-route REST and multi-route inspection also require admission by their owning endpoint's policy, including its binary restrictions. L4-only credential forwarding retains endpoint-selector matching. | +| Binary-scoped credential injection | Ordinary static placeholder resolution is endpoint-scoped. Static `enforce-credential-bound` bindings and dynamic grants in inspected routes also require admission by their owning endpoint's policy, including its binary restrictions. L4-only credential forwarding retains endpoint-selector matching. | | Credential verification on create | `openshell provider create` does not yet probe provider verification endpoints or expose `--no-verify`. | | Automatic credential scope extraction | OpenShell does not yet inspect upstream provider responses to discover credential scopes. | | Policy prover integration | OpenShell does not yet run the policy prover automatically on sandbox startup or block startup based on prover findings. | diff --git a/e2e/rust/tests/kubernetes_shared_supervisor_spiffe.rs b/e2e/rust/tests/kubernetes_shared_supervisor_spiffe.rs index b89f60fd90..bc0357e207 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_request_policy_bound_credentials: true, }); let environment = probe .client diff --git a/proto/openshell.proto b/proto/openshell.proto index e67b74cd6b..caa20aa6c8 100644 --- a/proto/openshell.proto +++ b/proto/openshell.proto @@ -3062,6 +3062,8 @@ message GetSandboxProviderEnvironmentRequest { // metadata. Gateways withhold credentials that require this behavior when // the capability is absent. bool supports_stable_placeholder_environment_keys = 3; + // The supervisor can intersect static credential use with admitted request-policy owners. + bool supports_request_policy_bound_credentials = 4; } // One network endpoint at which a static provider credential may be resolved. @@ -3084,6 +3086,10 @@ message StaticCredentialBinding { // sandbox, provider, credential key, endpoint authorization, or an applicable // refresh authorization epoch changes. string workload_credential_handle = 3; + // Gateway-issued endpoint policy owners permitted to authorize this credential. + repeated string request_policy_owners = 4; + // Concrete attached Provider whose endpoint rules may authorize these owners. + string request_policy_provider = 5; } // Polling projection of ProviderEnvironmentSnapshot. The parallel maps below diff --git a/proto/sandbox.proto b/proto/sandbox.proto index 4699ee244d..79d8ed0981 100644 --- a/proto/sandbox.proto +++ b/proto/sandbox.proto @@ -156,6 +156,10 @@ enum NetworkEnforcementMode { NETWORK_ENFORCEMENT_MODE_ENFORCE = 1; // Log policy violations and allow the traffic. NETWORK_ENFORCEMENT_MODE_AUDIT = 2; + // Enforce request rules and require the selected static credential's own + // explicitly bound endpoint to admit the request. Older runtimes reject + // this value rather than dropping the credential-scoped authorization. + NETWORK_ENFORCEMENT_MODE_ENFORCE_CREDENTIAL_BOUND = 3; } // Shorthand access policy for an inspected network endpoint. diff --git a/tests/suites/conformance/src/credential_gating.rs b/tests/suites/conformance/src/credential_gating.rs index 5230b86428..13c454880c 100644 --- a/tests/suites/conformance/src/credential_gating.rs +++ b/tests/suites/conformance/src/credential_gating.rs @@ -346,6 +346,159 @@ async fn profile_endpoints_bind_static_credentials(cx: &mut Context) -> testkit: Ok(()) } +/// Two accounts at one inspected MCP endpoint keep their own tool rules and +/// bearer values, including after one account is withdrawn. +#[testkit::test] +async fn account_bound_mcp_tool_policies_are_isolated(cx: &mut Context) -> testkit::Result { + const ENV_A: &str = "E2E_MCP_ACCOUNT_A"; + const ENV_B: &str = "E2E_MCP_ACCOUNT_B"; + const SECRET_A: &str = "e2e-mcp-account-a"; + const SECRET_B: &str = "e2e-mcp-account-b"; + + let server = HttpRecorder::serve(|_| { + Response::json(&json!({ + "jsonrpc": "2.0", "id": 1, + "result": {"content": [{"type": "text", "text": "ok"}]}, + })) + }) + .await?; + let mut providers = Vec::new(); + for (suffix, env, secret) in [("accta", ENV_A, SECRET_A), ("acctb", ENV_B, SECRET_B)] { + let name = cx.name(suffix); + let profile = Profile::new(&name) + .display_name("E2E MCP account") + .credential(bearer_credential("token", env)) + .binaries(PYTHON_BINARIES.iter().copied()) + .to_yaml()?; + cx.install_provider(&name, &profile, &[(env, secret)]) + .await?; + providers.push(name); + } + + let binaries: Vec<_> = PYTHON_BINARIES + .iter() + .map(|path| json!({"path": path})) + .collect(); + let account_rule = |name: &str, provider: &str, tools: &[&str]| { + let rules: Vec<_> = tools + .iter() + .map(|tool| json!({"allow": {"method": "tools/call", "tool": tool}})) + .collect(); + json!({ + "name": name, + "endpoints": [{ + "host": TEST_HOST, + "port": server.port, + "path": "/mcp", + "protocol": "mcp", + "enforcement": "enforce-credential-bound", + "mcp": {"versions": ["2025-11-25"]}, + "rules": rules, + "credential_binding": {"provider": provider}, + }], + "binaries": binaries, + }) + }; + let rules = json!({ + "account_a": account_rule("account_a", &providers[0], &["search"]), + "account_b": account_rule("account_b", &providers[1], &["search", "send"]), + }); + let policy = policy::base_with(&format!("network_policies: {rules}\n"))?; + let sandbox = cx + .python_sandbox("multi", policy.clone()) + .providers(providers.iter().map(String::as_str)) + .create_ready() + .await?; + let placeholder_a = sandbox.exec(["printenv", ENV_A]).await?.success()?.stdout; + let placeholder_b = sandbox.exec(["printenv", ENV_B]).await?.success()?.stdout; + let placeholder_a = placeholder_a.trim(); + let placeholder_b = placeholder_b.trim(); + testkit::ensure!( + placeholder_a.starts_with(PLACEHOLDER_PREFIX) + && placeholder_b.starts_with(PLACEHOLDER_PREFIX) + && placeholder_a != placeholder_b, + "each account must receive its own nonsecret placeholder" + ); + + async fn call( + sandbox: &Sandbox, + port: u16, + placeholder: &str, + tool: &str, + ) -> Result { + http( + sandbox, + TEST_HOST, + port, + &clients::Request::new("POST", "/mcp") + .header("Authorization", format!("Bearer {placeholder}")) + .header("Content-Type", "application/json") + .header("MCP-Protocol-Version", "2025-11-25") + .body(json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": tool, "arguments": {}}}).to_string()), + ) + .await + } + + for (placeholder, tool, secret) in [ + (placeholder_a, "search", SECRET_A), + (placeholder_b, "search", SECRET_B), + (placeholder_b, "send", SECRET_B), + ] { + let reply = call(&sandbox, server.port, placeholder, tool).await?; + testkit::ensure!(reply.status() == Some(200), "{tool} should be permitted"); + let requests = server.requests(); + let request = requests + .last() + .ok_or_else(|| Error::msg("allowed call did not reach upstream"))?; + testkit::ensure!( + request.header("authorization").as_deref() == Some(format!("Bearer {secret}").as_str()) + && serde_json::from_str::(&request.body)?["params"]["name"] + == tool, + "the recipient must see the chosen account's bearer and tool" + ); + } + let before_denied = server.requests().len(); + testkit::ensure!( + before_denied == 3, + "exactly three allowed calls must reach upstream" + ); + let reply = call(&sandbox, server.port, placeholder_a, "send").await?; + testkit::ensure!(reply.status() == Some(403), "account A cannot send"); + testkit::ensure!( + server.requests().len() == before_denied, + "account A's disabled tool must not reach upstream" + ); + + let mut withdrawn = policy; + withdrawn.network_policies.remove("account_a"); + policy::set(&sandbox, &withdrawn).await?; + let reply = call(&sandbox, server.port, placeholder_a, "search").await?; + testkit::ensure!( + reply.status() == Some(403), + "withdrawn account A cannot search" + ); + testkit::ensure!( + server.requests().len() == before_denied, + "withdrawn account A must not reach upstream" + ); + let reply = call(&sandbox, server.port, placeholder_b, "send").await?; + testkit::ensure!( + reply.status() == Some(200), + "account B must remain available" + ); + let requests = server.requests(); + testkit::ensure!( + requests.len() == before_denied + 1 + && requests + .last() + .and_then(|request| request.header("authorization")) + .as_deref() + == Some(format!("Bearer {SECRET_B}").as_str()), + "account B must keep its bearer after account A is withdrawn" + ); + Ok(()) +} + /// Run [`scripts::WEBSOCKET_BINARY_CLIENT`] against `server` in a sandbox with `providers`, /// and return whether its binary frame reached `server`. async fn send_binary_frame( From d6f6b88104d30abd86fff41ba1990f6699a100d7 Mon Sep 17 00:00:00 2001 From: stevenlee-oai <213687449+stevenlee-oai@users.noreply.github.com> Date: Thu, 26 Nov 2026 08:02:01 +0000 Subject: [PATCH 2/6] fix(policy): require unique account credentials before forwarding Signed-off-by: stevenlee-oai <213687449+stevenlee-oai@users.noreply.github.com> --- .../src/provider_credentials.rs | 86 +++-- crates/openshell-core/src/secrets.rs | 134 ++++++- .../src/l7/mod.rs | 4 + crates/openshell-policy/src/ambiguity.rs | 91 ++++- crates/openshell-server/src/grpc/policy.rs | 58 ++- .../grpc/policy/token_grant_owners_tests.rs | 51 +++ crates/openshell-server/src/grpc/provider.rs | 135 +++---- .../grpc/provider_refresh_routing_tests.rs | 3 +- .../src/l7/relay.rs | 68 +++- .../openshell-supervisor-network/src/proxy.rs | 27 +- .../src/proxy/relay.rs | 1 + docs/how-it-works/policies/schema.mdx | 12 +- docs/how-it-works/providers/profiles.mdx | 16 +- skills/generate-sandbox-policy/SKILL.md | 15 +- skills/generate-sandbox-policy/examples.md | 42 +++ .../conformance/src/credential_gating.rs | 347 +++++++++++++++--- .../conformance/src/mcp_account_client.mjs | 47 +++ 17 files changed, 901 insertions(+), 236 deletions(-) create mode 100644 tests/suites/conformance/src/mcp_account_client.mjs diff --git a/crates/openshell-core/src/provider_credentials.rs b/crates/openshell-core/src/provider_credentials.rs index 948431c5a2..280ab8166b 100644 --- a/crates/openshell-core/src/provider_credentials.rs +++ b/crates/openshell-core/src/provider_credentials.rs @@ -802,7 +802,7 @@ impl ProviderCredentialState { Option>, u64, ) { - self.resolver_and_body_classifier_for_endpoint_with_owners(host, port, path, None) + self.resolver_and_body_classifier_for_endpoint_with_owners(host, port, path, None, false) } /// Resolve only static credentials whose own request policy admitted the request. @@ -813,6 +813,7 @@ impl ProviderCredentialState { port: u16, path: &str, admitted_owners: Option<&HashSet>, + require_credential_selection: bool, ) -> ( Option>, Option>, @@ -873,37 +874,62 @@ impl ProviderCredentialState { .collect(), )) }); - let resolver = inner.combined_resolver.as_ref().map(|resolver| { - let revision_fallback_allowed_revisions = inner - .static_credential_identity_epochs - .iter() - .filter(|(key, epoch)| { - allowed.contains(*key) - && inner - .static_credential_bindings - .get(*key) - .is_some_and(|binding| binding.credential_identity == epoch.identity) - }) - .map(|(key, epoch)| (key.clone(), epoch.revisions.clone())) - .collect(); - let scoped = resolver - .as_ref() - .clone() - .with_placements( + let resolver = inner + .combined_resolver + .as_ref() + .map(|resolver| { + let revision_fallback_allowed_revisions = inner - .static_credential_bindings + .static_credential_identity_epochs .iter() - .map(|(key, binding)| (key.clone(), binding.placement.clone())) - .collect(), - ) - .scoped_to_env_keys( - &inner.known_static_credential_keys, - &allowed, - revision_fallback_allowed_revisions, - ); - // Attributed to the same snapshot as `revision` above. - Arc::new(self.track_resolver(scoped, &inner)) - }); + .filter(|(key, epoch)| { + allowed.contains(*key) + && inner.static_credential_bindings.get(*key).is_some_and( + |binding| binding.credential_identity == epoch.identity, + ) + }) + .map(|(key, epoch)| (key.clone(), epoch.revisions.clone())) + .collect(); + let scoped = resolver + .as_ref() + .clone() + .with_placements( + inner + .static_credential_bindings + .iter() + .map(|(key, binding)| (key.clone(), binding.placement.clone())) + .collect(), + ) + .scoped_to_env_keys( + &inner.known_static_credential_keys, + &allowed, + revision_fallback_allowed_revisions, + ); + // Attributed to the same snapshot as `revision` above. + let scoped = self.track_resolver(scoped, &inner); + Arc::new(if require_credential_selection { + let admitted_bound_keys = allowed + .iter() + .filter(|key| { + inner + .static_credential_bindings + .get(*key) + .is_some_and(|binding| !binding.request_policy_owners.is_empty()) + }) + .cloned() + .collect(); + scoped.requiring_credential_selection(admitted_bound_keys) + } else { + scoped + }) + }) + .or_else(|| { + require_credential_selection.then(|| { + Arc::new( + SecretResolver::default().requiring_credential_selection(HashSet::new()), + ) + }) + }); (resolver, classifier, revision) } diff --git a/crates/openshell-core/src/secrets.rs b/crates/openshell-core/src/secrets.rs index 38be363a0e..3876298759 100644 --- a/crates/openshell-core/src/secrets.rs +++ b/crates/openshell-core/src/secrets.rs @@ -115,6 +115,7 @@ enum UnresolvedPlaceholderReason { Unavailable, EndpointMismatch, PlacementMismatch, + SelectionRequired, } pub const CREDENTIAL_PLACEMENT_MISMATCH: &str = @@ -131,6 +132,11 @@ impl UnresolvedPlaceholderError { unresolved(location) } + #[must_use] + pub fn is_selection_required(&self) -> bool { + self.reason == UnresolvedPlaceholderReason::SelectionRequired + } + #[must_use] pub fn is_endpoint_mismatch(&self) -> bool { self.reason == UnresolvedPlaceholderReason::EndpointMismatch @@ -148,6 +154,8 @@ impl fmt::Display for UnresolvedPlaceholderError { UnresolvedPlaceholderReason::PlacementMismatch => CREDENTIAL_PLACEMENT_MISMATCH, UnresolvedPlaceholderReason::EndpointMismatch => "credential is not authorized for the request endpoint", + UnresolvedPlaceholderReason::SelectionRequired => + "exactly one authorized account credential must be selected", }, self.location, ) @@ -244,6 +252,14 @@ pub struct SecretResolver { revision_fallback_allowed_revisions: HashMap>>, /// Where to report that this resolver handed out a real secret. use_record: Option, + /// Request-local account selection, when required by an inspected route. + selection: Option>, +} + +#[derive(Debug)] +struct CredentialSelection { + allowed: Arc>, + used: std::sync::Mutex>, } /// Version that never matches a live credential version. @@ -362,6 +378,59 @@ impl fmt::Debug for SecretResolver { } impl SecretResolver { + /// Mark a resolver as requiring one of the admitted account credentials. + #[must_use] + pub fn requiring_credential_selection(mut self, allowed: HashSet) -> Self { + self.selection = Some(Arc::new(CredentialSelection { + allowed: Arc::new(allowed), + used: std::sync::Mutex::new(HashSet::new()), + })); + self + } + + #[must_use] + pub fn requires_credential_selection(&self) -> bool { + self.selection.is_some() + } + + /// Start an independent account-selection record for this HTTP request. + #[must_use] + pub fn for_request_selection(&self) -> Self { + let mut scoped = self.clone(); + scoped.selection = self.selection.as_ref().map(|selection| { + Arc::new(CredentialSelection { + allowed: Arc::clone(&selection.allowed), + used: std::sync::Mutex::new(HashSet::new()), + }) + }); + scoped + } + + /// Clear the requirement after the forward proxy has already validated it. + #[must_use] + pub fn without_credential_selection(mut self) -> Self { + self.selection = None; + self + } + + /// Reject before forwarding if the request did not select exactly one admitted account. + pub fn validate_credential_selection(&self) -> Result<(), UnresolvedPlaceholderError> { + if self.selection.as_ref().is_some_and(|selection| { + selection + .used + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .len() + != 1 + }) { + return Err(UnresolvedPlaceholderError { + location: "request", + reason: UnresolvedPlaceholderReason::SelectionRequired, + }); + } + Ok(()) + } + /// Report every real secret this resolver hands out to `marker`. /// /// `static_versions` is the version of each static credential in the @@ -411,6 +480,16 @@ impl SecretResolver { /// value, records [`STALE_CREDENTIAL_VERSION`]; so does a placeholder with /// no recognisable key, under the placeholder itself. fn note_use(&self, placeholder: &str, served: &str) { + if let Some(selection) = &self.selection + && let Some(key) = placeholder_env_key(placeholder) + && selection.allowed.contains(key) + { + selection + .used + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .insert(key.to_owned()); + } let Some(record) = &self.use_record else { return; }; @@ -521,6 +600,7 @@ impl SecretResolver { identity_bound_env_keys: HashSet::new(), revision_fallback_allowed_revisions: HashMap::new(), use_record: None, + selection: None, }) }; ( @@ -580,6 +660,7 @@ impl SecretResolver { identity_bound_env_keys: HashSet::new(), revision_fallback_allowed_revisions: HashMap::new(), use_record: None, + selection: None, }), ) } @@ -611,6 +692,7 @@ impl SecretResolver { identity_bound_env_keys, revision_fallback_allowed_revisions, use_record: None, + selection: None, }) } } @@ -648,6 +730,7 @@ impl SecretResolver { identity_bound_env_keys: bound_keys.clone(), revision_fallback_allowed_revisions, use_record: self.use_record.clone(), + selection: self.selection.clone(), } } @@ -773,6 +856,8 @@ impl SecretResolver { UnresolvedPlaceholderReason::EndpointMismatch } else if !self.placement_permits(placeholder) { UnresolvedPlaceholderReason::PlacementMismatch + } else if self.selection.is_some() { + UnresolvedPlaceholderReason::SelectionRequired } else { UnresolvedPlaceholderReason::Unavailable }; @@ -1635,7 +1720,10 @@ pub fn rewrite_http_header_block( raw: &[u8], resolver: Option<&SecretResolver>, ) -> Result { - let Some(resolver) = resolver else { + let request_resolver = resolver + .filter(|resolver| resolver.requires_credential_selection()) + .map(SecretResolver::for_request_selection); + let Some(resolver) = request_resolver.as_ref().or(resolver) else { // Fail-closed: with no resolver there is nothing that can rewrite a // credential placeholder, so forwarding the block verbatim would leak // the reserved token to the upstream. Scan the header region (mirroring @@ -1657,6 +1745,7 @@ pub fn rewrite_http_header_block( }; let Some(header_end) = raw.windows(4).position(|w| w == b"\r\n\r\n").map(|p| p + 4) else { + resolver.validate_credential_selection()?; return Ok(RewriteResult { rewritten: raw.to_vec(), redacted_target: None, @@ -1666,6 +1755,7 @@ pub fn rewrite_http_header_block( let header_str = String::from_utf8_lossy(&raw[..header_end]); let mut lines = header_str.split("\r\n"); let Some(request_line) = lines.next() else { + resolver.validate_credential_selection()?; return Ok(RewriteResult { rewritten: raw.to_vec(), redacted_target: None, @@ -1698,6 +1788,7 @@ pub fn rewrite_http_header_block( return Err(unresolved("header")); } + resolver.validate_credential_selection()?; Ok(RewriteResult { rewritten: output, redacted_target: rl_result.redacted_target, @@ -2416,6 +2507,47 @@ mod tests { assert_eq!(err.location, "header"); } + #[test] + fn account_bound_header_rewrite_requires_exactly_one_admitted_credential_per_request() { + let (_, resolver) = SecretResolver::from_provider_env(HashMap::from([ + ("ACCOUNT_A".into(), "token-a".into()), + ("ACCOUNT_B".into(), "token-b".into()), + ])); + let resolver = resolver + .unwrap() + .with_placements(HashMap::from([( + "ACCOUNT_B".into(), + CredentialPlacement::Header("x-account-b".into()), + )])) + .requiring_credential_selection(HashSet::from([ + "ACCOUNT_A".into(), + "ACCOUNT_B".into(), + ])); + let selected = + b"POST /mcp HTTP/1.1\r\nAuthorization: Bearer openshell:resolve:env:ACCOUNT_A\r\n\r\n"; + assert!( + String::from_utf8( + rewrite_http_header_block(selected, Some(&resolver)) + .unwrap() + .rewritten + ) + .unwrap() + .contains("Bearer token-a") + ); + // The previous request must not make a later uncredentialed request look selected. + assert!( + rewrite_http_header_block(b"POST /mcp HTTP/1.1\r\n\r\n", Some(&resolver)) + .unwrap_err() + .is_selection_required() + ); + let ambiguous = b"POST /mcp HTTP/1.1\r\nAuthorization: Bearer openshell:resolve:env:ACCOUNT_A\r\nx-account-b: openshell:resolve:env:ACCOUNT_B\r\n\r\n"; + assert!( + rewrite_http_header_block(ambiguous, Some(&resolver)) + .unwrap_err() + .is_selection_required() + ); + } + #[test] fn rewrites_http_header_blocks_and_preserves_body() { let (_, resolver) = SecretResolver::from_provider_env( diff --git a/crates/openshell-policy-runtime-interface/src/l7/mod.rs b/crates/openshell-policy-runtime-interface/src/l7/mod.rs index bf7735559e..c7337d709f 100644 --- a/crates/openshell-policy-runtime-interface/src/l7/mod.rs +++ b/crates/openshell-policy-runtime-interface/src/l7/mod.rs @@ -81,6 +81,8 @@ pub struct L7EndpointConfig { pub path: String, pub tls: TlsMode, pub enforcement: EnforcementMode, + /// Require exactly one admitted account credential on every request. + pub require_credential_selection: bool, /// Maximum GraphQL request body bytes to buffer for inspection. pub graphql_max_body_bytes: usize, /// Maximum JSON-RPC request body bytes to buffer for inspection. @@ -234,6 +236,8 @@ pub fn parse_l7_config(config: &EndpointConfig) -> Option { path: config.path.clone(), tls, enforcement, + require_credential_selection: config.enforcement + == EnforcementSetting::EnforceCredentialBound, graphql_max_body_bytes, json_rpc_max_body_bytes, mcp_strict_tool_names, diff --git a/crates/openshell-policy/src/ambiguity.rs b/crates/openshell-policy/src/ambiguity.rs index 48f39fc1ce..620bd63374 100644 --- a/crates/openshell-policy/src/ambiguity.rs +++ b/crates/openshell-policy/src/ambiguity.rs @@ -4,7 +4,7 @@ //! Validation for endpoint selectors whose policy-derived behavior conflicts. use openshell_core::proto::{ - NetworkEndpoint, NetworkEnforcementMode, NetworkTlsMode, SandboxPolicy, + NetworkBinary, NetworkEndpoint, NetworkEnforcementMode, NetworkTlsMode, SandboxPolicy, }; use std::collections::{BTreeSet, HashSet, VecDeque}; use std::fmt; @@ -49,6 +49,7 @@ struct EndpointRef<'a> { provider_rule: bool, index: usize, endpoint: &'a NetworkEndpoint, + binaries: &'a [NetworkBinary], } /// Reject endpoint metadata ambiguity before a policy generation is activated. @@ -76,6 +77,7 @@ pub fn find_endpoint_ambiguities(policy: &SandboxPolicy) -> Vec>(); @@ -93,7 +95,12 @@ pub fn find_endpoint_ambiguities(policy: &SandboxPolicy) -> Vec bool { endpoint.enforcement == NetworkEnforcementMode::EnforceCredentialBound as i32 } +fn is_l4(endpoint: &NetworkEndpoint) -> bool { + endpoint.protocol.is_empty() || is_explicit_tcp(&endpoint.protocol) +} + fn credential_endpoint(endpoint: &EndpointRef<'_>) -> bool { endpoint.endpoint.credential_binding.is_some() || (endpoint.provider_rule && endpoint.endpoint.provider_credentialed) @@ -412,6 +423,23 @@ fn credential_bound_overlap_conflicts( && !compatible_credential_bound_selectors(left.endpoint, right.endpoint) { vec!["overlapping credential routes must both use enforce-credential-bound with the same exact host, ports, and path".to_string()] + } else if credential_bound(left.endpoint) != credential_bound(right.endpoint) { + // A broad L4 route or more-specific inspected route would otherwise + // authorize requests without selecting an account on the protected route. + vec!["an ordinary route cannot overlap an enforce-credential-bound route".to_string()] + } else if compatible_credential_bound_selectors(left.endpoint, right.endpoint) + && left.endpoint.credential_binding == right.endpoint.credential_binding + && (left.endpoint.access != right.endpoint.access + || left.endpoint.rules != right.endpoint.rules + || left.endpoint.deny_rules != right.endpoint.deny_rules + || normalized_mcp_allow_all_known_methods(left.endpoint) + != normalized_mcp_allow_all_known_methods(right.endpoint) + || left.binaries != right.binaries) + { + vec![ + "one credential cannot have conflicting request policies for the same endpoint" + .to_string(), + ] } else { Vec::new() } @@ -440,6 +468,14 @@ fn is_json_rpc_family(protocol: &str) -> bool { protocol.eq_ignore_ascii_case("json-rpc") || protocol.eq_ignore_ascii_case("mcp") } +fn normalized_mcp_allow_all_known_methods(endpoint: &NetworkEndpoint) -> bool { + endpoint + .mcp + .as_ref() + .and_then(|options| options.allow_all_known_mcp_methods) + .unwrap_or(false) +} + fn normalized_mcp_strict_tool_names(endpoint: &NetworkEndpoint) -> bool { endpoint .mcp @@ -873,6 +909,34 @@ mod tests { let mut right = left.clone(); right.credential_binding.as_mut().unwrap().provider = "account-b".into(); assert!(find_endpoint_ambiguities(&policy_with(left.clone(), right.clone())).is_empty()); + right.access = NetworkAccessPreset::ReadWrite as i32; + assert!(find_endpoint_ambiguities(&policy_with(left.clone(), right.clone())).is_empty()); + right.credential_binding.as_mut().unwrap().provider = "account-a".into(); + assert!( + find_endpoint_ambiguities(&policy_with(left.clone(), right.clone())) + .iter() + .any(|ambiguity| ambiguity + .conflicts + .iter() + .any(|conflict| conflict.contains("one credential cannot have conflicting"))) + ); + right.access = left.access; + right.mcp = Some(openshell_core::proto::McpOptions { + allow_all_known_mcp_methods: Some(false), + ..Default::default() + }); + assert!(find_endpoint_ambiguities(&policy_with(left.clone(), right.clone())).is_empty()); + right.mcp.as_mut().unwrap().allow_all_known_mcp_methods = Some(true); + assert!( + find_endpoint_ambiguities(&policy_with(left.clone(), right.clone())) + .iter() + .any(|ambiguity| ambiguity + .conflicts + .iter() + .any(|conflict| conflict.contains("one credential cannot have conflicting"))) + ); + right.credential_binding.as_mut().unwrap().provider = "account-b".into(); + assert!(find_endpoint_ambiguities(&policy_with(left.clone(), right.clone())).is_empty()); right.path = "/**".into(); let partial = find_endpoint_ambiguities(&policy_with(left.clone(), right.clone())); @@ -899,7 +963,7 @@ mod tests { } #[test] - fn covered_unbound_sibling_does_not_become_an_independent_credential_source() { + fn ordinary_overlapping_routes_cannot_bypass_account_selection() { let mut bound = endpoint("api.example.com", 443); bound.path = "/api/**".into(); bound.protocol = "rest".into(); @@ -911,9 +975,26 @@ mod tests { sibling.path = "/api/admin".into(); sibling.protocol = "rest".into(); sibling.enforcement = NetworkEnforcementMode::Enforce as i32; - // The Gateway stamps coverage on ordinary rules as well as the source's - // own route. That marker alone must not create a second source. + // Coverage markers do not make ordinary rules account-bound. sibling.provider_credentialed = true; + for ordinary in [ + sibling.clone(), + NetworkEndpoint { + protocol: String::new(), + path: "/other".into(), + ..sibling.clone() + }, + ] { + assert!( + find_endpoint_ambiguities(&policy_with(bound.clone(), ordinary)) + .iter() + .any(|ambiguity| ambiguity + .conflicts + .iter() + .any(|conflict| conflict.contains("ordinary route cannot overlap"))) + ); + } + sibling.path = "/other".into(); assert!(find_endpoint_ambiguities(&policy_with(bound, sibling)).is_empty()); } diff --git a/crates/openshell-server/src/grpc/policy.rs b/crates/openshell-server/src/grpc/policy.rs index 0012855a87..2e1149139f 100644 --- a/crates/openshell-server/src/grpc/policy.rs +++ b/crates/openshell-server/src/grpc/policy.rs @@ -4090,6 +4090,29 @@ pub async fn build_provider_environment_snapshot_from_inputs( let provider_names = &spec.providers; let provider_profile_catalog = &inputs.catalog; let provider_records = &inputs.provider_records; + let mut request_policy_owners = HashMap::>::new(); + for endpoint in effective_policy + .network_policies + .values() + .flat_map(|rule| &rule.endpoints) + { + if endpoint.enforcement + != openshell_core::proto::NetworkEnforcementMode::EnforceCredentialBound as i32 + || endpoint.token_grant_owner.is_empty() + { + continue; + } + if let Some(binding) = &endpoint.credential_binding { + request_policy_owners + .entry(binding.provider.clone()) + .or_default() + .push(endpoint.token_grant_owner.clone()); + } + } + for owners in request_policy_owners.values_mut() { + owners.sort(); + owners.dedup(); + } let mut provider_environment = super::provider::resolve_provider_environment_from_records_with_policy_bindings_and_credentials( provider_profile_catalog, @@ -4097,6 +4120,7 @@ pub async fn build_provider_environment_snapshot_from_inputs( &policy_credential_bindings, &state.credentials, Some(&sandbox_id), + &request_policy_owners, ) .await?; @@ -4199,40 +4223,6 @@ pub async fn build_provider_environment_snapshot_from_inputs( .dynamic_credentials .extend(static_request_metadata); - for record in provider_records { - let mut owners: Vec<_> = effective_policy - .network_policies - .values() - .flat_map(|rule| &rule.endpoints) - .filter(|endpoint| { - endpoint.enforcement - == openshell_core::proto::NetworkEnforcementMode::EnforceCredentialBound as i32 - && endpoint - .credential_binding - .as_ref() - .is_some_and(|binding| binding.provider == record.name) - }) - .map(|endpoint| endpoint.token_grant_owner.clone()) - .filter(|owner| !owner.is_empty()) - .collect(); - owners.sort(); - owners.dedup(); - if owners.is_empty() { - continue; - } - for key in record - .provider - .credentials - .keys() - .chain(record.provider.credential_handles.keys()) - { - if let Some(binding) = provider_environment.static_credential_bindings.get_mut(key) { - binding.request_policy_owners.clone_from(&owners); - binding.request_policy_provider.clone_from(&record.name); - } - } - } - info!( sandbox_id = %sandbox_id, provider_count = provider_names.len(), 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 08499d7896..aabda50c12 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 @@ -385,6 +385,32 @@ async fn two_static_provider_bindings_activate_with_distinct_policy_owners() { }, ); } + // A single account cannot gain the union of two conflicting policies on the same route. + let mut conflicting = policy.clone(); + let mut same_account = conflicting.network_policies["static-a"].clone(); + same_account.name = "static-a-expanded".into(); + same_account.endpoints[0].rules = conflicting.network_policies["static-b"].endpoints[0] + .rules + .clone(); + conflicting + .network_policies + .insert(same_account.name.clone(), same_account); + let err = handle_update_config( + &state, + authed_request(UpdateConfigRequest { + sandbox: "static-accounts".into(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), + policy: Some(conflicting), + ..Default::default() + }), + ) + .await + .unwrap_err(); + assert!( + err.message() + .contains("one credential cannot have conflicting request policies") + ); + handle_update_config( &state, authed_request(UpdateConfigRequest { @@ -486,6 +512,31 @@ async fn two_static_provider_bindings_activate_with_distinct_policy_owners() { .is_err(), "stripped metadata must not activate" ); + // Previously admitted state can contain an expired provider sharing A's key. Refuse + // the whole snapshot before either credential can inherit the other's policy owner. + let original_b = state + .store + .get_message_by_name::("default", "static-b") + .await + .unwrap() + .unwrap(); + let mut expired_b = original_b.clone(); + expired_b.r#type = "static-a-profile".into(); + expired_b.credentials = HashMap::from([("ACCOUNT_A".into(), "expired-token-b".into())]); + expired_b.credential_expiration_times = HashMap::from([( + "ACCOUNT_A".into(), + openshell_core::time::timestamp_from_millis(1).unwrap(), + )]); + state.store.put_message(&expired_b).await.unwrap(); + let collision = build_provider_environment_snapshot(&state, &sandbox, true, true) + .await + .unwrap_err(); + assert_eq!(collision.code(), tonic::Code::FailedPrecondition); + assert!(collision.message().contains("ACCOUNT_A")); + assert!(collision.message().contains("static-a")); + assert!(collision.message().contains("static-b")); + state.store.put_message(&original_b).await.unwrap(); + let mut remaining = policy.clone(); remaining .network_policies diff --git a/crates/openshell-server/src/grpc/provider.rs b/crates/openshell-server/src/grpc/provider.rs index 776d5cd2cd..5f32955b37 100644 --- a/crates/openshell-server/src/grpc/provider.rs +++ b/crates/openshell-server/src/grpc/provider.rs @@ -1254,6 +1254,7 @@ pub(super) async fn resolve_provider_environment_from_records( &HashMap::new(), &credentials, None, + &HashMap::new(), ) .await } @@ -1270,6 +1271,7 @@ pub(super) async fn resolve_provider_environment_from_records_with_credentials( &HashMap::new(), credentials, None, + &HashMap::new(), ) .await } @@ -1290,6 +1292,7 @@ pub(super) async fn resolve_provider_environment_from_records_with_policy_bindin policy_bindings, &credentials, None, + &HashMap::new(), ) .await } @@ -1300,6 +1303,7 @@ pub(super) async fn resolve_provider_environment_from_records_with_policy_bindin policy_bindings: &HashMap>, credentials: &crate::credentials::CredentialRuntime, sandbox_id: Option<&str>, + request_policy_owners: &HashMap>, ) -> Result { if records.is_empty() { return Ok(ProviderEnvironment::default()); @@ -1315,7 +1319,7 @@ pub(super) async fn resolve_provider_environment_from_records_with_policy_bindin let mut readiness_reason = openshell_core::proto::ProviderReadinessReason::Unspecified; let mut expired_static_keys = HashSet::new(); let now_ms = crate::persistence::current_time_ms(); - validate_provider_environment_records_unique_at(catalog, records, now_ms)?; + validate_provider_environment_records_unique(catalog, records)?; let registry = openshell_providers::ProviderRegistry::new(); for record in records { @@ -1487,6 +1491,10 @@ pub(super) async fn resolve_provider_environment_from_records_with_policy_bindin endpoints, refresh_epochs.get(key).map(String::as_str), profile_stable_placeholder_keys.contains(key), + request_policy_owners + .get(name) + .map(Vec::as_slice) + .unwrap_or_default(), ), ); } @@ -1566,6 +1574,10 @@ pub(super) async fn resolve_provider_environment_from_records_with_policy_bindin endpoints, refresh_epochs.get(&key).map(String::as_str), profile_stable_placeholder_keys.contains(&key), + request_policy_owners + .get(name) + .map(Vec::as_slice) + .unwrap_or_default(), ), ); } @@ -1727,6 +1739,7 @@ pub(super) fn static_credential_request_metadata( &baseline.endpoints, refresh_epochs.get(key).map(String::as_str), credential.stable_placeholder, + &baseline.request_policy_owners, ); if expected != *baseline { continue; @@ -1789,6 +1802,7 @@ fn static_credential_binding( endpoints: &[StaticCredentialEndpointBinding], authorization_epoch: Option<&str>, stable_external_placeholder: bool, + request_policy_owners: &[String], ) -> StaticCredentialBinding { // External stable placeholders do not have a refresh authorization epoch. // A fixed domain value keeps their handle stable across value updates while @@ -1807,8 +1821,12 @@ fn static_credential_binding( format!("refresh:{workload_credential_handle}") }; StaticCredentialBinding { - request_policy_provider: String::new(), - request_policy_owners: Vec::new(), + request_policy_provider: if request_policy_owners.is_empty() { + String::new() + } else { + record.name.clone() + }, + request_policy_owners: request_policy_owners.to_vec(), endpoints: endpoints.to_vec(), credential_identity, workload_credential_handle, @@ -2228,14 +2246,13 @@ pub async fn validate_provider_environment_keys_unique_with_catalog( workspace: &str, provider_names: &[String], ) -> Result<(), Status> { - validate_provider_environment_keys_unique_at( + validate_provider_environment_keys_unique_for_candidate( store, refresh, catalog, workspace, provider_names, None, - crate::persistence::current_time_ms(), ) .await } @@ -2288,14 +2305,13 @@ pub async fn validate_provider_update_against_attached_sandboxes_with_catalog( let Some(spec) = sandbox.spec.as_ref() else { continue; }; - validate_provider_environment_keys_unique_at( + validate_provider_environment_keys_unique_for_candidate( store, refresh, catalog, workspace, &spec.providers, Some(provider), - crate::persistence::current_time_ms(), ) .await .map_err(|err| { @@ -2308,14 +2324,13 @@ pub async fn validate_provider_update_against_attached_sandboxes_with_catalog( Ok(()) } -async fn validate_provider_environment_keys_unique_at( +async fn validate_provider_environment_keys_unique_for_candidate( store: &Store, refresh: RefreshStateReader<'_>, catalog: &EffectiveProviderProfileCatalog, workspace: &str, provider_names: &[String], candidate_provider: Option<&Provider>, - now_ms: i64, ) -> Result<(), Status> { let mut seen_credentials = HashMap::::new(); let mut seen_plugin_config = HashMap::::new(); @@ -2336,7 +2351,7 @@ async fn validate_provider_environment_keys_unique_at( &mut seen_credentials, &mut seen_plugin_config, &provider_name, - active_provider_environment_keys(refresh, catalog, &provider, now_ms).await?, + reserved_provider_environment_keys(refresh, catalog, &provider).await?, provider_plugin_environment_keys(catalog, &provider), )?; dynamic_bindings.extend(dynamic_token_grant_bindings_for_provider_with_catalog( @@ -2347,10 +2362,9 @@ async fn validate_provider_environment_keys_unique_at( Ok(()) } -fn validate_provider_environment_records_unique_at( +fn validate_provider_environment_records_unique( catalog: &EffectiveProviderProfileCatalog, records: &[ProviderEnvironmentRecord], - now_ms: i64, ) -> Result<(), Status> { let mut seen_credentials = HashMap::::new(); let mut seen_plugin_config = HashMap::::new(); @@ -2361,7 +2375,7 @@ fn validate_provider_environment_records_unique_at( &mut seen_credentials, &mut seen_plugin_config, &record.name, - active_keys_with_refresh_states(catalog, provider, &record.refresh_states, now_ms), + reserved_keys_with_refresh_states(catalog, provider, &record.refresh_states), provider_plugin_environment_keys(catalog, provider), )?; dynamic_bindings.extend(dynamic_token_grant_bindings_for_provider_with_catalog( @@ -2613,54 +2627,42 @@ fn validate_dynamic_token_grant_bindings_unambiguous( Ok(()) } -async fn active_provider_environment_keys( +async fn reserved_provider_environment_keys( refresh: RefreshStateReader<'_>, catalog: &EffectiveProviderProfileCatalog, provider: &Provider, - now_ms: i64, ) -> Result, Status> { - active_provider_environment_keys_for_identity( - refresh, - catalog, - provider, - provider.object_id(), - now_ms, - ) - .await -} - -async fn active_provider_environment_keys_for_identity( - refresh: RefreshStateReader<'_>, - catalog: &EffectiveProviderProfileCatalog, - provider: &Provider, - provider_identity: &str, - now_ms: i64, -) -> Result, Status> { - let refresh_states = if provider_identity.is_empty() { + let refresh_states = if provider.object_id().is_empty() { Vec::new() } else { - refresh.list(provider_identity).await? + refresh.list(provider.object_id()).await? }; - Ok(active_keys_with_refresh_states( + Ok(reserved_keys_with_refresh_states( catalog, provider, &refresh_states, - now_ms, )) } -fn active_keys_with_refresh_states( +fn reserved_keys_with_refresh_states( catalog: &EffectiveProviderProfileCatalog, provider: &Provider, refresh_states: &[StoredProviderCredentialRefreshState], - now_ms: i64, ) -> Vec { let broker_only_credential_keys = broker_only_provider_credential_keys_for_provider(catalog, provider); - let mut keys = active_provider_credential_keys(provider, now_ms, &broker_only_credential_keys); + // A stored credential retains its environment-name ownership after expiry: + // a later refresh must not collide with another provider's placeholder. + let mut keys: Vec<_> = provider + .credentials + .keys() + .chain(provider.credential_handles.keys()) + .filter(|key| !is_non_injectable_provider_credential(provider, key)) + .filter(|key| !broker_only_credential_keys.contains(*key)) + .filter(|key| is_valid_env_key(key)) + .cloned() + .collect(); for state in refresh_states { - // The primary key plus every co-minted output key this refresh owns, - // so a configured-but-not-yet-minted refresh reserves all of them. keys.extend( std::iter::once(state.credential_key.clone()) .chain(state.additional_output_keys.values().cloned()) @@ -2673,33 +2675,6 @@ fn active_keys_with_refresh_states( keys } -fn active_provider_credential_keys( - provider: &Provider, - now_ms: i64, - broker_only_credential_keys: &HashSet, -) -> Vec { - let mut keys: Vec = provider - .credentials - .keys() - .filter(|key| !is_non_injectable_provider_credential(provider, key)) - .filter(|key| !broker_only_credential_keys.contains(*key)) - .filter(|key| is_valid_env_key(key)) - .filter(|key| provider_credential_not_expired(provider, key, now_ms)) - .cloned() - .collect(); - keys.extend( - provider - .credential_handles - .keys() - .filter(|key| !is_non_injectable_provider_credential(provider, key)) - .filter(|key| !broker_only_credential_keys.contains(*key)) - .filter(|key| is_valid_env_key(key)) - .filter(|key| provider_credential_not_expired(provider, key, now_ms)) - .cloned(), - ); - keys -} - fn broker_only_provider_credential_keys_for_provider( catalog: &EffectiveProviderProfileCatalog, provider: &Provider, @@ -2730,14 +2705,6 @@ pub(super) fn broker_only_provider_credential_keys(profile: &ProviderProfile) -> .collect() } -fn provider_credential_not_expired(provider: &Provider, key: &str, now_ms: i64) -> bool { - provider - .credential_expiration_times - .get(key) - .and_then(|value| openshell_core::time::timestamp_to_millis(value).ok()) - .is_none_or(|expiration_ms| expiration_ms > now_ms) -} - pub(super) fn is_non_injectable_provider_credential(provider: &Provider, key: &str) -> bool { normalize_profile_id(&provider.r#type).as_deref() == Some("google-vertex-ai") && key == "GOOGLE_SERVICE_ACCOUNT_KEY" @@ -14169,6 +14136,7 @@ pub(super) mod tests { &endpoints, None, false, + &[], ); let mut environment = ProviderEnvironment { environment: HashMap::from([("TOKEN".into(), "synthetic-sensitive-token".into())]), @@ -14271,7 +14239,7 @@ pub(super) mod tests { }]; let external_binding = |sandbox, record: &ProviderEnvironmentRecord, key, endpoints: &[_]| { - static_credential_binding(Some(sandbox), record, key, endpoints, None, true) + static_credential_binding(Some(sandbox), record, key, endpoints, None, true, &[]) }; let initial = external_binding("sandbox-a", &record, "API_KEY", &endpoints); assert!(!initial.workload_credential_handle.is_empty()); @@ -14308,7 +14276,7 @@ pub(super) mod tests { "recreating the same provider name must revoke the original handle" ); assert!( - static_credential_binding(None, &record, "API_KEY", &endpoints, None, true) + static_credential_binding(None, &record, "API_KEY", &endpoints, None, true, &[]) .workload_credential_handle .is_empty(), "an external handle requires an authenticated sandbox binding" @@ -14493,6 +14461,7 @@ pub(super) mod tests { &HashMap::new(), &state.credentials, Some("sandbox-id"), + &HashMap::new(), ) .await .unwrap(); @@ -14564,6 +14533,7 @@ pub(super) mod tests { &HashMap::new(), &state.credentials, Some("sandbox-id"), + &HashMap::new(), ) .await .unwrap(); @@ -14623,6 +14593,7 @@ pub(super) mod tests { &HashMap::new(), &state.credentials, Some("sandbox-id"), + &HashMap::new(), ) .await .unwrap(); @@ -14697,6 +14668,7 @@ pub(super) mod tests { &HashMap::new(), &state.credentials, Some("sandbox-id"), + &HashMap::new(), ) .await .unwrap(); @@ -14890,6 +14862,7 @@ pub(super) mod tests { &HashMap::new(), &credentials, None, + &HashMap::new(), ) .await .unwrap(); @@ -15067,6 +15040,7 @@ pub(super) mod tests { &policy_bindings, &credentials, Some("sandbox-id"), + &HashMap::new(), ) .await .expect("provider environment"); @@ -15148,6 +15122,7 @@ pub(super) mod tests { &HashMap::new(), &credentials, None, + &HashMap::new(), ) .await .unwrap(); @@ -15172,6 +15147,7 @@ pub(super) mod tests { &policy_bindings, &credentials, None, + &HashMap::new(), ) .await .unwrap(); @@ -17556,11 +17532,10 @@ pub(super) mod tests { .snapshot_catalog(state.store.as_ref(), "default") .await .unwrap(); - let keys = active_provider_environment_keys( + let keys = reserved_provider_environment_keys( RefreshStateReader::Runtime(&state.refresh), &catalog, &provider, - 0, ) .await .unwrap(); diff --git a/crates/openshell-server/src/grpc/provider_refresh_routing_tests.rs b/crates/openshell-server/src/grpc/provider_refresh_routing_tests.rs index ea49ed4c66..e70a3fcfa4 100644 --- a/crates/openshell-server/src/grpc/provider_refresh_routing_tests.rs +++ b/crates/openshell-server/src/grpc/provider_refresh_routing_tests.rs @@ -132,11 +132,10 @@ async fn provider_snapshot_and_validation_use_injected_refresh_reads() { .snapshot_catalog(&store, "default") .await .unwrap(); - let keys = active_provider_environment_keys( + let keys = reserved_provider_environment_keys( RefreshStateReader::Runtime(&refresh), &catalog, &provider, - 0, ) .await .unwrap(); diff --git a/crates/openshell-supervisor-network/src/l7/relay.rs b/crates/openshell-supervisor-network/src/l7/relay.rs index 28d949052d..fa8ed740e2 100644 --- a/crates/openshell-supervisor-network/src/l7/relay.rs +++ b/crates/openshell-supervisor-network/src/l7/relay.rs @@ -141,13 +141,14 @@ fn scoped_context_for_request( ctx: &L7EvalContext, request: &crate::l7::provider::L7Request, ) -> Option { - scoped_context_for_request_with_owners(ctx, request, None) + scoped_context_for_request_with_owners(ctx, request, None, false) } fn scoped_context_for_request_with_owners( ctx: &L7EvalContext, request: &crate::l7::provider::L7Request, admitted_owners: Option<&HashSet>, + require_credential_selection: bool, ) -> Option { let mut scoped = ctx.clone(); if matches!( @@ -174,6 +175,7 @@ fn scoped_context_for_request_with_owners( ctx.port, &request.target, admitted_owners, + require_credential_selection, ); scoped.secret_resolver = resolver; scoped.body_classifier = classifier; @@ -224,7 +226,8 @@ pub(crate) async fn prepare_inspected_request( .values() .any(|credential| credential.token_grant.is_some()) }); - let needs_owners = grant_snapshot.is_some() + let needs_owners = config.require_credential_selection + || grant_snapshot.is_some() || scoped .provider_credentials .as_ref() @@ -296,8 +299,18 @@ pub(crate) async fn prepare_inspected_request( if let Some(guard) = credential_generation_guard(&scoped) { guard.ensure_current()?; } - let scoped = - scoped_context_for_request_with_owners(&scoped, &req, owners.as_ref()).unwrap_or(scoped); + let mut scoped = scoped_context_for_request_with_owners( + &scoped, + &req, + owners.as_ref(), + config.require_credential_selection, + ) + .unwrap_or(scoped); + if config.require_credential_selection && scoped.secret_resolver.is_none() { + scoped.secret_resolver = Some(Arc::new( + SecretResolver::default().requiring_credential_selection(HashSet::new()), + )); + } Ok((req, scoped, injected)) } @@ -728,12 +741,15 @@ where { let endpoint_mismatch = error.is_endpoint_mismatch(); let placement_mismatch = error.is_placement_mismatch(); - let status = if endpoint_mismatch || placement_mismatch { + let selection_required = error.is_selection_required(); + let status = if endpoint_mismatch || placement_mismatch || selection_required { "403 Forbidden" } else { "500 Internal Server Error" }; - let body = if placement_mismatch { + let body = if selection_required { + serde_json::json!({"error": "credential_selection_required", "message": "Select exactly one authorized account credential placeholder"}) + } else if placement_mismatch { serde_json::json!({ "error": "credential_placement_mismatch", "message": "Credential is not authorized for this request location", @@ -750,15 +766,17 @@ where }) }; if let Some(correlation) = correlation { - let (response_code, outcome) = if endpoint_mismatch || placement_mismatch { - (403, HttpOutcome::Denied) - } else { - (500, HttpOutcome::PlatformError) - }; + let (response_code, outcome) = + if endpoint_mismatch || placement_mismatch || selection_required { + (403, HttpOutcome::Denied) + } else { + (500, HttpOutcome::PlatformError) + }; correlation.record_rejection( response_code, outcome, - (!endpoint_mismatch && !placement_mismatch).then_some("credential_resolution_failed"), + (!endpoint_mismatch && !placement_mismatch && !selection_required) + .then_some("credential_resolution_failed"), ); crate::l7::rest::send_json_response_with_request_id( &ctx.policy_name, @@ -771,7 +789,23 @@ where } else { crate::l7::rest::send_json_response(&ctx.policy_name, body, client, status).await?; } - let mut events = if placement_mismatch { + let mut events = if selection_required { + vec![ + HttpActivityBuilder::new(openshell_ocsf::ctx::ctx()) + .activity(ActivityId::for_http_method(method)) + .http_request(method_only_request(method)) + .http_response(openshell_ocsf::HttpResponse { code: 403 }) + .action(ActionId::Denied) + .disposition(DispositionId::Blocked) + .severity(SeverityId::High) + .status(StatusId::Failure) + .dst_endpoint(Endpoint::from_domain(&ctx.host, ctx.port)) + .firewall_rule(&ctx.policy_name, "credential-binding") + .message("Account credential selection required; request denied") + .status_detail("credential_selection_required") + .build(), + ] + } else if placement_mismatch { vec![ HttpActivityBuilder::new(openshell_ocsf::ctx::ctx()) .activity(ActivityId::for_http_method(method)) @@ -1199,7 +1233,9 @@ where } else if let Some(error) = report.downcast_ref::() { if let Some(observer) = observer { - observer.observe_credential_failure(error.is_endpoint_mismatch()); + observer.observe_credential_failure( + error.is_endpoint_mismatch() || error.is_selection_required(), + ); } reject_credential_resolution(client, ctx, &request.action, error, correlation) .await?; @@ -11352,6 +11388,7 @@ network_policies: path: path.into(), tls: crate::l7::TlsMode::Auto, enforcement: EnforcementMode::Enforce, + require_credential_selection: false, graphql_max_body_bytes: 0, json_rpc_max_body_bytes: crate::l7::jsonrpc::DEFAULT_MAX_BODY_BYTES, mcp_strict_tool_names: true, @@ -11831,6 +11868,7 @@ network_policies: path: "/ws".into(), tls: crate::l7::TlsMode::Auto, enforcement: EnforcementMode::Enforce, + require_credential_selection: false, graphql_max_body_bytes: 0, json_rpc_max_body_bytes: crate::l7::jsonrpc::DEFAULT_MAX_BODY_BYTES, mcp_strict_tool_names: true, @@ -12038,6 +12076,7 @@ network_policies: path: "/ws".into(), tls: crate::l7::TlsMode::Auto, enforcement: EnforcementMode::Enforce, + require_credential_selection: false, graphql_max_body_bytes: 0, json_rpc_max_body_bytes: crate::l7::jsonrpc::DEFAULT_MAX_BODY_BYTES, mcp_strict_tool_names: true, @@ -12167,6 +12206,7 @@ network_policies: path: "/graphql".into(), tls: crate::l7::TlsMode::Auto, enforcement: EnforcementMode::Enforce, + require_credential_selection: false, graphql_max_body_bytes: 0, json_rpc_max_body_bytes: crate::l7::jsonrpc::DEFAULT_MAX_BODY_BYTES, mcp_strict_tool_names: true, diff --git a/crates/openshell-supervisor-network/src/proxy.rs b/crates/openshell-supervisor-network/src/proxy.rs index 20727d275f..eeaf908ccc 100644 --- a/crates/openshell-supervisor-network/src/proxy.rs +++ b/crates/openshell-supervisor-network/src/proxy.rs @@ -5399,6 +5399,10 @@ fn rewrite_forward_request( canonical_authority: &str, secret_resolver: Option<&SecretResolver>, ) -> Result, secrets::UnresolvedPlaceholderError> { + let selection_resolver = secret_resolver + .filter(|resolver| resolver.requires_credential_selection()) + .map(SecretResolver::for_request_selection); + let secret_resolver = selection_resolver.as_ref().or(secret_resolver); let header_end = raw[..used] .windows(4) .position(|w| w == b"\r\n\r\n") @@ -5526,6 +5530,9 @@ fn rewrite_forward_request( return Err(secrets::UnresolvedPlaceholderError::unavailable("header")); } + if let Some(resolver) = secret_resolver { + resolver.validate_credential_selection()?; + } Ok(output) } @@ -7119,7 +7126,12 @@ async fn handle_forward_proxy_inner( .end(openshell_core::proto::MiddlewareSessionEndReason::Cancellation) .await; } - if e.is_placement_mismatch() { + if e.is_placement_mismatch() || e.is_selection_required() { + if e.is_selection_required() + && let Some(observer) = endpoint_observer.as_ref() + { + observer.observe(openshell_core::endpoint_status::EndpointResult::PolicyDenied); + } crate::l7::relay::reject_credential_resolution( client, &l7_ctx, @@ -7358,6 +7370,14 @@ async fn handle_forward_proxy_inner( let signing_region = forward_upgrade_config .as_ref() .map_or("", |config| config.signing_region.as_str()); + // Header credentials have already been selected and validated before dialing. + let post_selection_resolver = secret_resolver + .as_ref() + .filter(|resolver| resolver.requires_credential_selection()) + .map(|resolver| resolver.as_ref().clone().without_credential_selection()); + let relay_resolver = post_selection_resolver + .as_ref() + .or(secret_resolver.as_deref()); let outcome_result = relay_rewritten_forward_request( method, &upstream_target, @@ -7368,7 +7388,7 @@ async fn handle_forward_proxy_inner( generation_guard: &forward_generation_guard, credential_generation, websocket_extensions, - secret_resolver: secret_resolver.as_deref(), + secret_resolver: relay_resolver, body_classifier: endpoint_credentials.body_classifier.as_deref(), request_body_credential_rewrite, deny_uninspected_credentials, @@ -13597,6 +13617,7 @@ network_policies: path: "/**".to_string(), tls: crate::l7::TlsMode::Auto, enforcement: crate::l7::EnforcementMode::Enforce, + require_credential_selection: false, graphql_max_body_bytes: crate::l7::graphql::DEFAULT_MAX_BODY_BYTES, json_rpc_max_body_bytes: crate::l7::jsonrpc::DEFAULT_MAX_BODY_BYTES, mcp_strict_tool_names: true, @@ -15076,6 +15097,7 @@ network_policies: path: "/**".to_string(), tls: crate::l7::TlsMode::Auto, enforcement: crate::l7::EnforcementMode::Enforce, + require_credential_selection: false, graphql_max_body_bytes: crate::l7::graphql::DEFAULT_MAX_BODY_BYTES, json_rpc_max_body_bytes: crate::l7::jsonrpc::DEFAULT_MAX_BODY_BYTES, mcp_strict_tool_names: true, @@ -15099,6 +15121,7 @@ network_policies: path: "/graphql".to_string(), tls: crate::l7::TlsMode::Auto, enforcement: crate::l7::EnforcementMode::Enforce, + require_credential_selection: false, graphql_max_body_bytes: crate::l7::graphql::DEFAULT_MAX_BODY_BYTES, json_rpc_max_body_bytes: crate::l7::jsonrpc::DEFAULT_MAX_BODY_BYTES, mcp_strict_tool_names: true, diff --git a/crates/openshell-supervisor-network/src/proxy/relay.rs b/crates/openshell-supervisor-network/src/proxy/relay.rs index 32e7941321..d37ec71881 100644 --- a/crates/openshell-supervisor-network/src/proxy/relay.rs +++ b/crates/openshell-supervisor-network/src/proxy/relay.rs @@ -647,6 +647,7 @@ mod tests { path: "/**".to_string(), tls: crate::l7::TlsMode::Auto, enforcement: crate::l7::EnforcementMode::Enforce, + require_credential_selection: false, graphql_max_body_bytes: crate::l7::graphql::DEFAULT_MAX_BODY_BYTES, json_rpc_max_body_bytes: crate::l7::jsonrpc::DEFAULT_MAX_BODY_BYTES, mcp_strict_tool_names: true, diff --git a/docs/how-it-works/policies/schema.mdx b/docs/how-it-works/policies/schema.mdx index c25aeac1df..2409ae9fc3 100644 --- a/docs/how-it-works/policies/schema.mdx +++ b/docs/how-it-works/policies/schema.mdx @@ -228,7 +228,10 @@ OpenShell rejects an endpoint that breaks these rules: through wildcards, must use the same `tls` and `allowed_ips` values. Inspected endpoints that can match the same request must also agree on `protocol`, `enforcement`, and credential settings. Exact matching endpoints - can bind different providers when each uses `enforce-credential-bound`. See + can bind different providers when each uses `enforce-credential-bound` and + the providers have distinct credential environment keys. Such requests must + select exactly one authorized placeholder. Conflicting request policies for + the same provider and endpoint are rejected. See [Independent Accounts on One Endpoint](/how-it-works/providers/profiles#independent-accounts-on-one-endpoint). Without `protocol`, `access` and `rules` have no effect. @@ -359,7 +362,10 @@ matcher fields in one rule. Method globs and `mcp.allow_all_known_mcp_methods` do not. An extension method is one that no supported MCP revision defines. -Under the 2025 revisions, a client sends `initialize` and `notifications/initialized` before calling tools. When `mcp.allow_all_known_mcp_methods` is omitted or `false`, allow both explicitly: +Under the 2025 revisions, a client sends `initialize` and +`notifications/initialized` before discovering tools with `tools/list` or +calling them with `tools/call`. When `mcp.allow_all_known_mcp_methods` is +omitted or `false`, allow each required method explicitly: ```yaml showLineNumbers={false} rules: @@ -367,6 +373,8 @@ rules: method: initialize - allow: method: notifications/initialized + - allow: + method: tools/list - allow: method: tools/call tool: diff --git a/docs/how-it-works/providers/profiles.mdx b/docs/how-it-works/providers/profiles.mdx index 38168b7b15..f7ec0f6c84 100644 --- a/docs/how-it-works/providers/profiles.mdx +++ b/docs/how-it-works/providers/profiles.mdx @@ -252,9 +252,13 @@ Later access-token rotations do not require workload restarts. Use `enforcement: enforce-credential-bound` when two attached providers need different permissions at the same inspected endpoint. Each provider must use an -endpointless profile and a distinct credential environment key. The caller -chooses an account by sending its placeholder. OpenShell checks that account's -own rule before resolving the placeholder. +endpointless profile and a distinct credential environment key, such as +`ACCOUNT_A_TOKEN` and `ACCOUNT_B_TOKEN`. Do not reuse an environment key across +providers, even if one credential has expired or is temporarily unavailable. +The client must send exactly one authorized account placeholder in the +credential's declared location. OpenShell rejects requests with no selected +account, multiple account placeholders, or a placeholder that is not authorized +for the endpoint before forwarding them. For example, `account-a` can search, while `account-b` can search and send: @@ -288,6 +292,10 @@ network_policies: An attempt to call `send` with account A's placeholder is rejected before forwarding. Account B's permission cannot authorize account A's credential. +`allow_all_known_mcp_methods` permits the ordinary MCP lifecycle, including +`initialize`, `notifications/initialized`, and `tools/list`; the explicit tool +rules still limit `tools/call`. Without that option, add allow rules for those +lifecycle methods as well as each permitted `tools/call`. Explicit deny rules still take precedence across matching endpoints. Keep the mode on account A if account B is removed. @@ -297,6 +305,8 @@ Cedar policy. All endpoints bound to the same provider must use the same mode; signing, body rewriting, and WebSocket rewriting are unsupported. Overlapping account bindings must have the same exact destination and compatible inspection settings; an ordinary credential binding cannot overlap them. +Two rules for the same provider and exact endpoint cannot disagree on allowed +operations, deny rules, or binaries. ## Roadmap diff --git a/skills/generate-sandbox-policy/SKILL.md b/skills/generate-sandbox-policy/SKILL.md index c36b244f71..5befed8e85 100644 --- a/skills/generate-sandbox-policy/SKILL.md +++ b/skills/generate-sandbox-policy/SKILL.md @@ -482,9 +482,18 @@ The policy needs to go somewhere. Determine which mode applies: 2. **Check for conflicts**: - Does a policy with the same key already exist? If so, ask the user whether to **replace** it, **merge** new endpoints/binaries into it, or use a different key. - Does an existing endpoint selector overlap the new selector? Compatible overlaps are allowed and can intentionally aggregate allow and deny rules. Reject or revise equally specific overlaps that disagree on connection or request-processing metadata, including TLS, destination constraints, protocol/parser behavior, enforcement, or credential handling. A more-specific path selector may override broader request-processing metadata. Its selected protocol limits which matching endpoints contribute allow rules; same-protocol allows combine, and matching denies retain precedence. A broader REST allow does not authorize a request routed to JSON-RPC inspection. Preserve the documented restrictions on mixing MCP with other protocols. - - If the sandbox uses an attached provider credential, confirm the provider - profile also declares the intended host, port, and path. A sandbox policy - allow cannot expand the profile's static credential binding. + - If the sandbox uses an attached provider credential, either confirm the + profile covers the intended host, port, and path, or bind the endpointless + profile with `credential_binding.provider` naming the attached provider. + A sandbox policy cannot expand an endpoint-bearing profile's binding. + - If different accounts share an inspected endpoint, give each provider a + distinct credential environment key and use `enforce-credential-bound` + with an exact matching destination and per-account rules. Each request + must contain exactly one authorized account placeholder. Reject a second + conflicting rule for the same provider and endpoint. For ordinary MCP + clients, allow `initialize`, `notifications/initialized`, `tools/list`, and + permitted `tools/call` names; `mcp.allow_all_known_mcp_methods: true` + supplies the lifecycle methods while tool-specific rules restrict calls. - For `credential_signing`, confirm an attached endpoint-bearing profile declares `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY` and covers the signed endpoint. For an endpointless AWS profile, add diff --git a/skills/generate-sandbox-policy/examples.md b/skills/generate-sandbox-policy/examples.md index 17b7ca4646..42c90a384d 100644 --- a/skills/generate-sandbox-policy/examples.md +++ b/skills/generate-sandbox-policy/examples.md @@ -615,6 +615,48 @@ network_policies: --- +## Example 7: Independent MCP Accounts at One Endpoint + +Two attached endpointless providers use distinct credential keys: +`ACCOUNT_A_TOKEN` and `ACCOUNT_B_TOKEN`. Account A can search; account B can +search and send. Each request must carry exactly one authorized placeholder. + +```yaml +network_policies: + account_a: + binaries: [{path: /usr/bin/python3}] + endpoints: + - host: mcp.example.com + port: 443 + path: /mcp + protocol: mcp + enforcement: enforce-credential-bound + credential_binding: {provider: account-a} + mcp: {allow_all_known_mcp_methods: true} + rules: + - allow: {tool: search} + account_b: + binaries: [{path: /usr/bin/python3}] + endpoints: + - host: mcp.example.com + port: 443 + path: /mcp + protocol: mcp + enforcement: enforce-credential-bound + credential_binding: {provider: account-b} + mcp: {allow_all_known_mcp_methods: true} + rules: + - allow: {tool: {any: [search, send]}} +``` + +`allow_all_known_mcp_methods` permits `initialize`, +`notifications/initialized`, and `tools/list` for an ordinary MCP client. The +tool rules restrict `tools/call`: account A cannot call `send`, and account B's +rule cannot authorize account A's placeholder. To avoid permitting other core +methods, omit the option and explicitly allow the required lifecycle methods +and `tools/call` names. Do not reuse credential keys, even for expired +credentials, or define conflicting rules for the same provider and endpoint. + ## File Operation Examples (update existing / create new) ## Private IP Access Examples (allowed_ips) diff --git a/tests/suites/conformance/src/credential_gating.rs b/tests/suites/conformance/src/credential_gating.rs index 13c454880c..913d921eec 100644 --- a/tests/suites/conformance/src/credential_gating.rs +++ b/tests/suites/conformance/src/credential_gating.rs @@ -27,6 +27,13 @@ const BASH: &str = "/usr/bin/bash"; const TOKEN_ENV: &str = "E2E_GATING_TOKEN"; const TEST_SECRET: &str = "e2e-gating-secret-value"; const PLACEHOLDER_PREFIX: &str = "openshell:resolve:env:"; +const MCP_ACCOUNT_A: &str = "E2E_MCP_ACCOUNT_A"; +const MCP_ACCOUNT_B: &str = "E2E_MCP_ACCOUNT_B"; +const MCP_SECRET_A: &str = "e2e-mcp-account-a"; +const MCP_SECRET_B: &str = "e2e-mcp-account-b"; +const MCP_CLIENT_IMAGE: &str = "openshell-mcp-conformance-client:local"; +const MCP_NODE_BINARIES: &[&str] = &["/usr/local/bin/node", "/usr/bin/node"]; +const MCP_ACCOUNT_CLIENT: &str = include_str!("mcp_account_client.mjs"); const TOKEN_PRESENCE: &str = r#"if [ "${E2E_GATING_TOKEN+x}" != x ]; then echo TOKEN_ABSENT @@ -350,67 +357,23 @@ async fn profile_endpoints_bind_static_credentials(cx: &mut Context) -> testkit: /// bearer values, including after one account is withdrawn. #[testkit::test] async fn account_bound_mcp_tool_policies_are_isolated(cx: &mut Context) -> testkit::Result { - const ENV_A: &str = "E2E_MCP_ACCOUNT_A"; - const ENV_B: &str = "E2E_MCP_ACCOUNT_B"; - const SECRET_A: &str = "e2e-mcp-account-a"; - const SECRET_B: &str = "e2e-mcp-account-b"; - - let server = HttpRecorder::serve(|_| { - Response::json(&json!({ - "jsonrpc": "2.0", "id": 1, - "result": {"content": [{"type": "text", "text": "ok"}]}, - })) - }) - .await?; - let mut providers = Vec::new(); - for (suffix, env, secret) in [("accta", ENV_A, SECRET_A), ("acctb", ENV_B, SECRET_B)] { - let name = cx.name(suffix); - let profile = Profile::new(&name) - .display_name("E2E MCP account") - .credential(bearer_credential("token", env)) - .binaries(PYTHON_BINARIES.iter().copied()) - .to_yaml()?; - cx.install_provider(&name, &profile, &[(env, secret)]) - .await?; - providers.push(name); - } - - let binaries: Vec<_> = PYTHON_BINARIES - .iter() - .map(|path| json!({"path": path})) - .collect(); - let account_rule = |name: &str, provider: &str, tools: &[&str]| { - let rules: Vec<_> = tools - .iter() - .map(|tool| json!({"allow": {"method": "tools/call", "tool": tool}})) - .collect(); - json!({ - "name": name, - "endpoints": [{ - "host": TEST_HOST, - "port": server.port, - "path": "/mcp", - "protocol": "mcp", - "enforcement": "enforce-credential-bound", - "mcp": {"versions": ["2025-11-25"]}, - "rules": rules, - "credential_binding": {"provider": provider}, - }], - "binaries": binaries, - }) - }; - let rules = json!({ - "account_a": account_rule("account_a", &providers[0], &["search"]), - "account_b": account_rule("account_b", &providers[1], &["search", "send"]), - }); - let policy = policy::base_with(&format!("network_policies: {rules}\n"))?; + let server = HttpRecorder::serve(mcp_account_fixture).await?; + let (providers, policy) = mcp_accounts(cx, server.port, PYTHON_BINARIES).await?; let sandbox = cx .python_sandbox("multi", policy.clone()) .providers(providers.iter().map(String::as_str)) .create_ready() .await?; - let placeholder_a = sandbox.exec(["printenv", ENV_A]).await?.success()?.stdout; - let placeholder_b = sandbox.exec(["printenv", ENV_B]).await?.success()?.stdout; + let placeholder_a = sandbox + .exec(["printenv", MCP_ACCOUNT_A]) + .await? + .success()? + .stdout; + let placeholder_b = sandbox + .exec(["printenv", MCP_ACCOUNT_B]) + .await? + .success()? + .stdout; let placeholder_a = placeholder_a.trim(); let placeholder_b = placeholder_b.trim(); testkit::ensure!( @@ -440,9 +403,9 @@ async fn account_bound_mcp_tool_policies_are_isolated(cx: &mut Context) -> testk } for (placeholder, tool, secret) in [ - (placeholder_a, "search", SECRET_A), - (placeholder_b, "search", SECRET_B), - (placeholder_b, "send", SECRET_B), + (placeholder_a, "search", MCP_SECRET_A), + (placeholder_b, "search", MCP_SECRET_B), + (placeholder_b, "send", MCP_SECRET_B), ] { let reply = call(&sandbox, server.port, placeholder, tool).await?; testkit::ensure!(reply.status() == Some(200), "{tool} should be permitted"); @@ -469,6 +432,32 @@ async fn account_bound_mcp_tool_policies_are_isolated(cx: &mut Context) -> testk "account A's disabled tool must not reach upstream" ); + let missing = http( + &sandbox, + TEST_HOST, + server.port, + &clients::Request::new("POST", "/mcp") + .header("Content-Type", "application/json") + .header("MCP-Protocol-Version", "2025-11-25") + .body(json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "search", "arguments": {}}}).to_string()), + ) + .await?; + let unknown = call( + &sandbox, + server.port, + "openshell:resolve:env:E2E_MCP_UNKNOWN", + "search", + ) + .await?; + testkit::ensure!( + missing.status() == Some(403) && unknown.status() == Some(403), + "missing and unknown accounts must be denied" + ); + testkit::ensure!( + server.requests().len() == before_denied, + "an unselected account reached upstream" + ); + let mut withdrawn = policy; withdrawn.network_policies.remove("account_a"); policy::set(&sandbox, &withdrawn).await?; @@ -493,12 +482,250 @@ async fn account_bound_mcp_tool_policies_are_isolated(cx: &mut Context) -> testk .last() .and_then(|request| request.header("authorization")) .as_deref() - == Some(format!("Bearer {SECRET_B}").as_str()), + == Some(format!("Bearer {MCP_SECRET_B}").as_str()), "account B must keep its bearer after account A is withdrawn" ); Ok(()) } +/// The upstream conformance image contains the official MCP SDK. This focused +/// case is opt-in because the ordinary conformance images do not contain it. +#[testkit::test] +#[ignore = "requires the pinned upstream MCP conformance client image; see e2e/mcp-conformance.sh"] +async fn account_bound_mcp_sdk_client_isolates_accounts(cx: &mut Context) -> testkit::Result { + let server = HttpRecorder::serve(mcp_account_fixture).await?; + let (providers, mut policy) = mcp_accounts(cx, server.port, MCP_NODE_BINARIES).await?; + policy + .filesystem + .as_mut() + .ok_or_else(|| Error::msg("base policy lacks a filesystem policy"))? + .read_only + .push("/opt".into()); + let image = std::env::var("OPENSHELL_MCP_CONFORMANCE_CLIENT_IMAGE") + .unwrap_or_else(|_| MCP_CLIENT_IMAGE.to_string()); + let sandbox = cx + .sandbox("sdk") + .image(image) + .command(["sleep", "infinity"]) + .policy(policy.clone()) + .providers(providers.iter().map(String::as_str)) + .create_ready() + .await?; + let placeholder_a = sandbox + .exec(["printenv", MCP_ACCOUNT_A]) + .await? + .success()? + .stdout; + let placeholder_b = sandbox + .exec(["printenv", MCP_ACCOUNT_B]) + .await? + .success()? + .stdout; + testkit::ensure!( + placeholder_a.trim().starts_with(PLACEHOLDER_PREFIX) + && placeholder_b.trim().starts_with(PLACEHOLDER_PREFIX) + && placeholder_a.trim() != placeholder_b.trim(), + "each account must receive a unique placeholder, not a bearer" + ); + + run_mcp_sdk( + &sandbox, + server.port, + MCP_ACCOUNT_A, + &[("search", true), ("send", false)], + false, + ) + .await?; + run_mcp_sdk( + &sandbox, + server.port, + MCP_ACCOUNT_B, + &[("search", true), ("send", true)], + false, + ) + .await?; + let requests = server.requests(); + for secret in [MCP_SECRET_A, MCP_SECRET_B] { + let methods: Vec<_> = requests + .iter() + .filter(|request| { + request.header("authorization").as_deref() + == Some(format!("Bearer {secret}").as_str()) + }) + .filter_map(|request| serde_json::from_str::(&request.body).ok()) + .map(|request| request["method"].as_str().unwrap_or_default().to_owned()) + .collect(); + testkit::ensure!( + methods.starts_with(&[ + "initialize".into(), + "notifications/initialized".into(), + "tools/list".into() + ]), + "account {secret} did not initialize and discover through its own credential: {methods:?}" + ); + } + let calls: Vec<_> = requests + .iter() + .filter_map(|request| { + let body = serde_json::from_str::(&request.body).ok()?; + (body["method"] == "tools/call").then(|| { + ( + request.header("authorization"), + body["params"]["name"].clone(), + ) + }) + }) + .collect(); + testkit::ensure!( + calls + == vec![ + (Some(format!("Bearer {MCP_SECRET_A}")), json!("search")), + (Some(format!("Bearer {MCP_SECRET_B}")), json!("search")), + (Some(format!("Bearer {MCP_SECRET_B}")), json!("send")), + ], + "disabled tool reached upstream or a credential was mixed: {calls:?}" + ); + let before_denied = requests.len(); + for account in ["missing", "unknown"] { + run_mcp_sdk(&sandbox, server.port, account, &[], true).await?; + testkit::ensure!( + server.requests().len() == before_denied, + "{account} account reached upstream" + ); + } + + policy.network_policies.remove("account_a"); + policy::set(&sandbox, &policy).await?; + run_mcp_sdk(&sandbox, server.port, MCP_ACCOUNT_A, &[], true).await?; + testkit::ensure!( + server.requests().len() == before_denied, + "withdrawn account reached upstream" + ); + run_mcp_sdk( + &sandbox, + server.port, + MCP_ACCOUNT_B, + &[("send", true)], + false, + ) + .await?; + let after = server.requests(); + testkit::ensure!( + after.len() == before_denied + 4 + && after[before_denied..] + .iter() + .all(|request| request.header("authorization").as_deref() + == Some(format!("Bearer {MCP_SECRET_B}").as_str())), + "remaining account changed after withdrawal" + ); + Ok(()) +} + +async fn run_mcp_sdk( + sandbox: &Sandbox, + port: u16, + account: &str, + tools: &[(&str, bool)], + expect_denied: bool, +) -> Result { + // Exec prohibits control characters in command arguments. Drop comment + // lines and join the readable fixture before passing it to Node. + let script = MCP_ACCOUNT_CLIENT + .lines() + .filter(|line| !line.trim_start().starts_with("//")) + .collect::>() + .join(" "); + let url = format!("http://{TEST_HOST}:{port}/mcp"); + let tools = serde_json::to_string(tools)?; + let expected = if expect_denied { "denied" } else { "allowed" }; + let result = sandbox.exec([ + "sh", "-c", "cd /opt/mcp-conformance && exec node --input-type=module -e \"$1\" \"$2\" \"$3\" \"$4\" \"$5\"", "sh", &script, &url, account, &tools, expected, + ]).await?.success()?; + let marker = if expect_denied { + "SDK_CONNECT_DENIED" + } else { + "SDK_CALLS_OK" + }; + testkit::ensure!( + result.stdout.lines().any(|line| line == marker), + "MCP SDK client did not report {marker}: {}", + result.stdout + ); + Ok(()) +} + +async fn mcp_accounts( + cx: &Context, + port: u16, + binary_paths: &[&str], +) -> Result<([String; 2], proto::SandboxPolicy)> { + let providers = [cx.name("accta"), cx.name("acctb")]; + for (name, env, secret) in [ + (&providers[0], MCP_ACCOUNT_A, MCP_SECRET_A), + (&providers[1], MCP_ACCOUNT_B, MCP_SECRET_B), + ] { + let profile = Profile::new(name) + .display_name("E2E MCP account") + .credential(bearer_credential("token", env)) + .binaries(binary_paths.iter().copied()) + .to_yaml()?; + cx.install_provider(name, &profile, &[(env, secret)]) + .await?; + } + let binaries: Vec<_> = binary_paths + .iter() + .map(|path| json!({"path": path})) + .collect(); + let account_rule = |name: &str, provider: &str, tools: &[&str]| { + let mut rules = vec![ + json!({"allow": {"method": "initialize"}}), + json!({"allow": {"method": "notifications/initialized"}}), + json!({"allow": {"method": "tools/list"}}), + ]; + rules.extend( + tools + .iter() + .map(|tool| json!({"allow": {"method": "tools/call", "tool": tool}})), + ); + json!({"name": name, "endpoints": [{ + "host": TEST_HOST, "port": port, "path": "/mcp", "protocol": "mcp", + "enforcement": "enforce-credential-bound", "mcp": {"versions": ["2025-11-25"]}, + "rules": rules, "credential_binding": {"provider": provider} + }], "binaries": binaries}) + }; + let rules = json!({ + "account_a": account_rule("account_a", &providers[0], &["search"]), + "account_b": account_rule("account_b", &providers[1], &["search", "send"]), + }); + Ok(( + providers, + policy::base_with(&format!("network_policies: {rules}\n"))?, + )) +} + +fn mcp_account_fixture(request: &Request) -> Response { + let Ok(message) = serde_json::from_str::(&request.body) else { + return Response::new(400); + }; + let result = match message["method"].as_str() { + Some("initialize") => { + json!({"protocolVersion": "2025-11-25", "capabilities": {"tools": {}}, "serverInfo": {"name": "openshell-account-test", "version": "1"}}) + } + Some("notifications/initialized") => return Response::new(202), + Some("tools/list") => { + let tools = ["search", "send"].map( + |name| json!({"name": name, "inputSchema": {"type": "object", "properties": {}}}), + ); + json!({"tools": tools}) + } + Some("tools/call") => { + json!({"content": [{"type": "text", "text": message["params"]["name"]}]}) + } + _ => return Response::new(400), + }; + Response::json(&json!({"jsonrpc": "2.0", "id": message["id"], "result": result})) +} + /// Run [`scripts::WEBSOCKET_BINARY_CLIENT`] against `server` in a sandbox with `providers`, /// and return whether its binary frame reached `server`. async fn send_binary_frame( diff --git a/tests/suites/conformance/src/mcp_account_client.mjs b/tests/suites/conformance/src/mcp_account_client.mjs new file mode 100644 index 0000000000..4fdbc0acba --- /dev/null +++ b/tests/suites/conformance/src/mcp_account_client.mjs @@ -0,0 +1,47 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import assert from 'node:assert/strict'; +import { Client } from '@modelcontextprotocol/sdk/client/index.js'; +import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js'; + +const [url, account, toolsJson, expectConnection] = process.argv.slice(1); +let value; +if (account === 'unknown') { + value = 'openshell:resolve:env:E2E_MCP_UNKNOWN'; +} else if (account !== 'missing') { + value = process.env[account]; + assert(value, 'the selected account has no credential placeholder'); +} + +const transport = new StreamableHTTPClientTransport(new URL(url), { + requestInit: { headers: value ? { Authorization: `Bearer ${value}` } : {} } +}); +const client = new Client( + { name: 'openshell-account-policy-test', version: '1' }, + { capabilities: {} } +); +const denied = async (action) => { + await assert.rejects(action, (err) => err.code === 403 || String(err).includes('403')); +}; +try { + if (expectConnection === 'denied') { + await denied(() => client.connect(transport)); + console.log('SDK_CONNECT_DENIED'); + } else { + await client.connect(transport); + const tools = await client.listTools(); + assert.deepEqual(tools.tools.map(({ name }) => name), ['search', 'send']); + for (const [name, allowed] of JSON.parse(toolsJson)) { + if (allowed) { + const result = await client.callTool({ name, arguments: {} }); + assert.equal(result.content[0].text, name); + } else { + await denied(() => client.callTool({ name, arguments: {} })); + } + } + console.log('SDK_CALLS_OK'); + } +} finally { + await transport.close(); +} From c11bb7f83ffa669ff37b3ff4438b5d1e2b226d52 Mon Sep 17 00:00:00 2001 From: stevenlee-oai <213687449+stevenlee-oai@users.noreply.github.com> Date: Thu, 26 Nov 2026 08:36:21 +0000 Subject: [PATCH 3/6] test: qualify credential-bound MCP client lifecycle Signed-off-by: stevenlee-oai <213687449+stevenlee-oai@users.noreply.github.com> --- crates/openshell-server/src/grpc/policy.rs | 2 +- .../conformance/src/credential_gating.rs | 19 ++++++++++++++++--- .../conformance/src/mcp_account_client.mjs | 12 +++++++++++- 3 files changed, 28 insertions(+), 5 deletions(-) diff --git a/crates/openshell-server/src/grpc/policy.rs b/crates/openshell-server/src/grpc/policy.rs index 2e1149139f..cf7d90066c 100644 --- a/crates/openshell-server/src/grpc/policy.rs +++ b/crates/openshell-server/src/grpc/policy.rs @@ -11006,7 +11006,7 @@ mod tests { extend_credentialed_scopes_from_policy_bindings( &mut scopes, &bindings, - &HashSet::from(["bound".to_string()]), + &HashMap::from([("bound".to_string(), "bound-provider-id".to_string())]), ); assert_eq!( diff --git a/tests/suites/conformance/src/credential_gating.rs b/tests/suites/conformance/src/credential_gating.rs index 913d921eec..5c004bba39 100644 --- a/tests/suites/conformance/src/credential_gating.rs +++ b/tests/suites/conformance/src/credential_gating.rs @@ -546,11 +546,11 @@ async fn account_bound_mcp_sdk_client_isolates_accounts(cx: &mut Context) -> tes .await?; let requests = server.requests(); for secret in [MCP_SECRET_A, MCP_SECRET_B] { + let authorization = format!("Bearer {secret}"); let methods: Vec<_> = requests .iter() .filter(|request| { - request.header("authorization").as_deref() - == Some(format!("Bearer {secret}").as_str()) + request.header("authorization").as_deref() == Some(authorization.as_str()) }) .filter_map(|request| serde_json::from_str::(&request.body).ok()) .map(|request| request["method"].as_str().unwrap_or_default().to_owned()) @@ -563,6 +563,15 @@ async fn account_bound_mcp_sdk_client_isolates_accounts(cx: &mut Context) -> tes ]), "account {secret} did not initialize and discover through its own credential: {methods:?}" ); + testkit::ensure!( + requests + .iter() + .filter(|request| request.method() == "GET" + && request.header("authorization").as_deref() == Some(authorization.as_str())) + .count() + == 1, + "account {secret} did not open its own optional MCP event stream" + ); } let calls: Vec<_> = requests .iter() @@ -611,7 +620,7 @@ async fn account_bound_mcp_sdk_client_isolates_accounts(cx: &mut Context) -> tes .await?; let after = server.requests(); testkit::ensure!( - after.len() == before_denied + 4 + after.len() == before_denied + 5 && after[before_denied..] .iter() .all(|request| request.header("authorization").as_deref() @@ -704,6 +713,10 @@ async fn mcp_accounts( } fn mcp_account_fixture(request: &Request) -> Response { + if request.method() == "GET" { + // Streamable HTTP permits a server to decline the optional SSE stream. + return Response::new(405); + } let Ok(message) = serde_json::from_str::(&request.body) else { return Response::new(400); }; diff --git a/tests/suites/conformance/src/mcp_account_client.mjs b/tests/suites/conformance/src/mcp_account_client.mjs index 4fdbc0acba..ad5b89a350 100644 --- a/tests/suites/conformance/src/mcp_account_client.mjs +++ b/tests/suites/conformance/src/mcp_account_client.mjs @@ -14,8 +14,17 @@ if (account === 'unknown') { assert(value, 'the selected account has no credential placeholder'); } +let finishEventStream; +const eventStream = new Promise((resolve) => { finishEventStream = resolve; }); const transport = new StreamableHTTPClientTransport(new URL(url), { - requestInit: { headers: value ? { Authorization: `Bearer ${value}` } : {} } + requestInit: { headers: value ? { Authorization: `Bearer ${value}` } : {} }, + fetch: (input, init) => { + const response = fetch(input, init); + if (init?.method === 'GET') { + response.then((reply) => finishEventStream(reply.status), () => finishEventStream(-1)); + } + return response; + } }); const client = new Client( { name: 'openshell-account-policy-test', version: '1' }, @@ -30,6 +39,7 @@ try { console.log('SDK_CONNECT_DENIED'); } else { await client.connect(transport); + assert.equal(await eventStream, 405); const tools = await client.listTools(); assert.deepEqual(tools.tools.map(({ name }) => name), ['search', 'send']); for (const [name, allowed] of JSON.parse(toolsJson)) { From 92b0774f0fc1ee4d77d5cdb71a842a23028f90f1 Mon Sep 17 00:00:00 2001 From: stevenlee-oai <213687449+stevenlee-oai@users.noreply.github.com> Date: Thu, 26 Nov 2026 08:38:01 +0000 Subject: [PATCH 4/6] fix: revalidate credential-bound sandbox admission Signed-off-by: stevenlee-oai <213687449+stevenlee-oai@users.noreply.github.com> --- crates/openshell-server/src/grpc/policy.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/openshell-server/src/grpc/policy.rs b/crates/openshell-server/src/grpc/policy.rs index cf7d90066c..f71a9f645e 100644 --- a/crates/openshell-server/src/grpc/policy.rs +++ b/crates/openshell-server/src/grpc/policy.rs @@ -5315,6 +5315,7 @@ pub(super) async fn handle_report_sandbox_configuration( let mut config_request = Request::new(GetSandboxConfigRequest { supported_capabilities: vec![ openshell_core::extension_protocol::POLICY_CEDAR_V1.to_string(), + openshell_core::extension_protocol::POLICY_REQUEST_BOUND_CREDENTIALS_V1.to_string(), ], name: sandbox_name.clone(), workspace_scope: Some(openshell_core::proto::workspace_selector(workspace.clone())), @@ -5336,6 +5337,7 @@ pub(super) async fn handle_report_sandbox_configuration( let mut config_request = Request::new(GetSandboxConfigRequest { supported_capabilities: vec![ openshell_core::extension_protocol::POLICY_CEDAR_V1.to_string(), + openshell_core::extension_protocol::POLICY_REQUEST_BOUND_CREDENTIALS_V1.to_string(), ], workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), name: sandbox_name, From ee7791b59d2a5365a10b8091c76cbafd73f82f7a Mon Sep 17 00:00:00 2001 From: stevenlee-oai <213687449+stevenlee-oai@users.noreply.github.com> Date: Thu, 26 Nov 2026 08:39:24 +0000 Subject: [PATCH 5/6] fix: preserve credential-bound capabilities on token refresh Signed-off-by: stevenlee-oai <213687449+stevenlee-oai@users.noreply.github.com> --- crates/openshell-server/src/grpc/auth_rpc.rs | 4 +--- crates/openshell-server/src/grpc/policy.rs | 23 +++++++++++++------- 2 files changed, 16 insertions(+), 11 deletions(-) diff --git a/crates/openshell-server/src/grpc/auth_rpc.rs b/crates/openshell-server/src/grpc/auth_rpc.rs index 1f56bd708b..a5bcd3e49d 100644 --- a/crates/openshell-server/src/grpc/auth_rpc.rs +++ b/crates/openshell-server/src/grpc/auth_rpc.rs @@ -348,9 +348,7 @@ pub async fn handle_refresh_sandbox_token( )); } else { let mut config_request = Request::new(GetSandboxConfigRequest { - supported_capabilities: vec![ - openshell_core::extension_protocol::POLICY_CEDAR_V1.to_string(), - ], + supported_capabilities: super::policy::gateway_policy_capabilities(), name: sandbox_record .metadata .as_ref() diff --git a/crates/openshell-server/src/grpc/policy.rs b/crates/openshell-server/src/grpc/policy.rs index f71a9f645e..388bb7118e 100644 --- a/crates/openshell-server/src/grpc/policy.rs +++ b/crates/openshell-server/src/grpc/policy.rs @@ -2903,6 +2903,19 @@ async fn handle_get_sandbox_config_inner( const CEDAR_SUPPORT_REQUIRED: &str = "Cedar policy requires a supervisor with Cedar support"; +/// Capabilities used when the Gateway revalidates its own configuration snapshot. +/// Supervisor requests must still report their actual supported capabilities. +pub(super) fn gateway_policy_capabilities() -> Vec { + use openshell_core::extension_protocol::{ + POLICY_CEDAR_V1, POLICY_REQUEST_BOUND_CREDENTIALS_V1, + }; + + vec![ + POLICY_CEDAR_V1.to_string(), + POLICY_REQUEST_BOUND_CREDENTIALS_V1.to_string(), + ] +} + /// Refuses a Cedar policy to a supervisor that did not report Cedar support. /// /// Callers must not answer with an empty compatibility configuration @@ -5313,10 +5326,7 @@ pub(super) async fn handle_report_sandbox_configuration( } if reported == ConfigurationAdmissionState::Accepted { let mut config_request = Request::new(GetSandboxConfigRequest { - supported_capabilities: vec![ - openshell_core::extension_protocol::POLICY_CEDAR_V1.to_string(), - openshell_core::extension_protocol::POLICY_REQUEST_BOUND_CREDENTIALS_V1.to_string(), - ], + supported_capabilities: gateway_policy_capabilities(), name: sandbox_name.clone(), workspace_scope: Some(openshell_core::proto::workspace_selector(workspace.clone())), }); @@ -5335,10 +5345,7 @@ pub(super) async fn handle_report_sandbox_configuration( // 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(), - openshell_core::extension_protocol::POLICY_REQUEST_BOUND_CREDENTIALS_V1.to_string(), - ], + supported_capabilities: gateway_policy_capabilities(), workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), name: sandbox_name, }); From 1235beeefc1f4b7692806fdb320e7912bfa31fde Mon Sep 17 00:00:00 2001 From: stevenlee-oai <213687449+stevenlee-oai@users.noreply.github.com> Date: Thu, 26 Nov 2026 08:45:32 +0000 Subject: [PATCH 6/6] test: reject cached placeholder after account withdrawal Signed-off-by: stevenlee-oai <213687449+stevenlee-oai@users.noreply.github.com> --- tests/suites/conformance/src/credential_gating.rs | 3 ++- tests/suites/conformance/src/mcp_account_client.mjs | 2 ++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/tests/suites/conformance/src/credential_gating.rs b/tests/suites/conformance/src/credential_gating.rs index 5c004bba39..4c383e46de 100644 --- a/tests/suites/conformance/src/credential_gating.rs +++ b/tests/suites/conformance/src/credential_gating.rs @@ -605,7 +605,8 @@ async fn account_bound_mcp_sdk_client_isolates_accounts(cx: &mut Context) -> tes policy.network_policies.remove("account_a"); policy::set(&sandbox, &policy).await?; - run_mcp_sdk(&sandbox, server.port, MCP_ACCOUNT_A, &[], true).await?; + // A process may retain A's old placeholder after its environment entry is removed. + run_mcp_sdk(&sandbox, server.port, placeholder_a.trim(), &[], true).await?; testkit::ensure!( server.requests().len() == before_denied, "withdrawn account reached upstream" diff --git a/tests/suites/conformance/src/mcp_account_client.mjs b/tests/suites/conformance/src/mcp_account_client.mjs index ad5b89a350..2a5e7e2ae8 100644 --- a/tests/suites/conformance/src/mcp_account_client.mjs +++ b/tests/suites/conformance/src/mcp_account_client.mjs @@ -9,6 +9,8 @@ const [url, account, toolsJson, expectConnection] = process.argv.slice(1); let value; if (account === 'unknown') { value = 'openshell:resolve:env:E2E_MCP_UNKNOWN'; +} else if (account.startsWith('openshell:resolve:env:')) { + value = account; } else if (account !== 'missing') { value = process.env[account]; assert(value, 'the selected account has no credential placeholder');