From 5bfddf399bbe2f12a71fae27966cead9897f9852 Mon Sep 17 00:00:00 2001 From: Free Wortley Date: Tue, 1 Dec 2026 10:37:40 -0800 Subject: [PATCH 01/11] feat(policy): let inspected endpoints specify allowed transports Separate connection transport from request protocol. Resolve TLS defaults per destination port and credential scope, enforce them for CONNECT and forward HTTP, and negotiate supervisor support before delivering the policy. Signed-off-by: Free Wortley --- .../openshell-core/src/extension_protocol.rs | 11 + crates/openshell-core/src/policy_l7.rs | 188 ++++++++- .../openshell-policy-cedar-adapter/src/lib.rs | 13 + .../src/cedar_only/routes.rs | 22 +- .../src/cedar_only/tests.rs | 27 ++ .../src/policy_data.rs | 11 + .../src/policy_types.rs | 60 ++- crates/openshell-policy-schema/src/lib.rs | 37 ++ crates/openshell-policy/src/ambiguity.rs | 36 ++ crates/openshell-policy/src/lib.rs | 196 ++++++++- crates/openshell-policy/src/merge.rs | 233 +++++++++-- crates/openshell-prover/src/containment.rs | 25 ++ crates/openshell-providers/src/profiles.rs | 88 ++++- .../src/config_delivery/mod.rs | 27 +- .../src/config_delivery/session.rs | 69 +++- crates/openshell-server/src/grpc/auth_rpc.rs | 4 +- crates/openshell-server/src/grpc/mod.rs | 22 +- crates/openshell-server/src/grpc/policy.rs | 214 ++++++++-- crates/openshell-server/src/storage_proto.rs | 26 +- .../data/sandbox-policy.rego | 4 + .../src/opa/raw_schema.rs | 23 +- .../src/policy_local.rs | 1 + .../openshell-supervisor-network/src/proxy.rs | 310 ++++++++++++--- .../src/proxy/transport_tests.rs | 371 ++++++++++++++++++ crates/openshell-supervisor/src/lib.rs | 5 +- crates/openshell-supervisor/src/main.rs | 7 +- docs/how-it-works/policies/network-rules.mdx | 44 ++- docs/how-it-works/policies/schema.mdx | 2 + e2e/python/test_sandbox_providers.py | 1 + .../tests/kubernetes_shared_supervisor.rs | 3 +- .../kubernetes_shared_supervisor_spiffe.rs | 1 + e2e/rust/tests/provider_token_exchange.rs | 2 + .../tests/support/provider_refresh_handles.rs | 4 + proto/sandbox.proto | 14 + .../conformance/src/credential_gating.rs | 29 +- 35 files changed, 1942 insertions(+), 188 deletions(-) create mode 100644 crates/openshell-supervisor-network/src/proxy/transport_tests.rs diff --git a/crates/openshell-core/src/extension_protocol.rs b/crates/openshell-core/src/extension_protocol.rs index 1d6d57960b..bc9cfef118 100644 --- a/crates/openshell-core/src/extension_protocol.rs +++ b/crates/openshell-core/src/extension_protocol.rs @@ -15,6 +15,17 @@ pub const PROTOCOL_MINOR: u32 = 0; /// Policy format implemented by a peer's registered Cedar backend. pub const POLICY_CEDAR_V1: &str = "openshell.policy.cedar.v1"; +/// Peer enforces endpoint transport allowlists and transport defaults. +pub const POLICY_ENDPOINT_TRANSPORTS_V1: &str = "openshell.policy.endpoint-transports.v1"; + +/// Policy capabilities advertised by a supervisor build. +#[must_use] +pub fn policy_capabilities(cedar: bool) -> Vec { + let mut capabilities = capabilities_if(POLICY_CEDAR_V1, cedar); + capabilities.push(POLICY_ENDPOINT_TRANSPORTS_V1.to_string()); + capabilities +} + /// Whether a peer advertises the required versioned capability. #[must_use] pub fn has_capability(capabilities: &[String], required: &str) -> bool { diff --git a/crates/openshell-core/src/policy_l7.rs b/crates/openshell-core/src/policy_l7.rs index 26be9fee57..722b69b10b 100644 --- a/crates/openshell-core/src/policy_l7.rs +++ b/crates/openshell-core/src/policy_l7.rs @@ -9,7 +9,9 @@ //! L7 endpoint field combinations, preventing drift between lint-time //! and runtime checks. -use crate::proto::{NetworkAccessPreset, NetworkEnforcementMode, NetworkTlsMode}; +use crate::proto::{ + NetworkAccessPreset, NetworkEndpoint, NetworkEnforcementMode, NetworkTlsMode, NetworkTransport, +}; #[allow(deprecated)] pub fn network_tls_mode_from_str(value: &str) -> Option { @@ -32,6 +34,122 @@ pub fn network_tls_mode_to_str(value: i32) -> Option<&'static str> { } } +/// The permitted transports for an inspected HTTP connection, after defaults. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum AllowedTransports { + Tls, + Plaintext, + Both, +} + +pub fn network_transport_from_str(value: &str) -> Option { + match value { + "tls" => Some(NetworkTransport::Tls), + "plaintext" => Some(NetworkTransport::Plaintext), + _ => None, + } +} + +pub fn network_transport_to_str(value: i32) -> Option<&'static str> { + match NetworkTransport::try_from(value).ok()? { + NetworkTransport::Tls => Some("tls"), + NetworkTransport::Plaintext => Some("plaintext"), + NetworkTransport::Unspecified => None, + } +} + +/// Validate the authored set without assigning defaults to an omitted field. +pub fn validate_allowed_transports( + explicit: &[i32], + protocol: &str, + tls: i32, +) -> Option<&'static str> { + parse_allowed_transports(explicit, inspected_protocol(protocol, tls)).err() +} + +fn inspected_protocol(protocol: &str, tls: i32) -> Option { + if tls == NetworkTlsMode::Unspecified as i32 { + L7Protocol::parse(protocol) + } else { + None + } +} + +fn parse_allowed_transports( + explicit: &[i32], + protocol: Option, +) -> Result, &'static str> { + if explicit.is_empty() { + return Ok(None); + } + if !protocol.is_some_and(L7Protocol::is_http) { + return Err( + "allowed_transports requires an inspected HTTP protocol and cannot be combined with tls: skip", + ); + } + let mut tls = false; + let mut plaintext = false; + for value in explicit { + let seen = match NetworkTransport::try_from(*value) { + Ok(NetworkTransport::Tls) => &mut tls, + Ok(NetworkTransport::Plaintext) => &mut plaintext, + _ => return Err("allowed_transports accepts only tls and plaintext"), + }; + if *seen { + return Err("allowed_transports must not contain duplicates"); + } + *seen = true; + } + Ok(Some(match (tls, plaintext) { + (true, true) => AllowedTransports::Both, + (true, false) => AllowedTransports::Tls, + (false, true) => AllowedTransports::Plaintext, + (false, false) => unreachable!("nonempty transport list"), + })) +} + +/// Resolve once for the destination port. An opaque connection has no HTTP +/// transport policy. Invalid lists are errors, never permission to relay raw TCP. +pub fn effective_allowed_transports( + explicit: &[i32], + protocol: Option, + credentialed: bool, + port: u32, +) -> Result, &'static str> { + if let Some(transports) = parse_allowed_transports(explicit, protocol)? { + return Ok(Some(transports)); + } + Ok(protocol.filter(|p| p.is_http()).map(|_| { + if port == 443 || credentialed { + AllowedTransports::Tls + } else { + AllowedTransports::Both + } + })) +} + +/// Token-grant owner IDs alone are not credential provenance: the gateway +/// stamps them on global policy endpoints even when no credential is attached. +pub fn endpoint_is_credentialed(endpoint: &NetworkEndpoint) -> bool { + endpoint.provider_credentialed + || endpoint.credential_binding.is_some() + || !endpoint.credential_signing.is_empty() +} + +pub fn endpoint_allowed_transports( + endpoint: &NetworkEndpoint, + port: u32, +) -> Option { + effective_allowed_transports( + &endpoint.allowed_transports, + inspected_protocol(&endpoint.protocol, endpoint.tls), + endpoint_is_credentialed(endpoint), + port, + ) + .ok() + .flatten() +} + pub fn network_enforcement_mode_from_str(value: &str) -> Option { match value { "" => Some(NetworkEnforcementMode::Unspecified), @@ -114,6 +232,13 @@ impl L7Protocol { } } + fn is_http(self) -> bool { + matches!( + self, + Self::Rest | Self::Websocket | Self::Graphql | Self::JsonRpc | Self::Mcp + ) + } + /// Returns `true` for protocols in the JSON-RPC family (`json-rpc`, /// `mcp`). pub fn is_jsonrpc_family(self) -> bool { @@ -169,6 +294,63 @@ pub fn validate_explicit_tcp_additional_fields( )] } +#[cfg(test)] +mod transport_tests { + use super::*; + + #[test] + fn defaults_follow_the_actual_port_and_credential_provenance() { + let mut endpoint = NetworkEndpoint { + protocol: "rest".into(), + ports: vec![443, 8443], + token_grant_owner: "global-owner".into(), + ..Default::default() + }; + assert_eq!( + endpoint_allowed_transports(&endpoint, 443), + Some(AllowedTransports::Tls) + ); + assert_eq!( + endpoint_allowed_transports(&endpoint, 8443), + Some(AllowedTransports::Both) + ); + endpoint.provider_credentialed = true; + assert_eq!( + endpoint_allowed_transports(&endpoint, 8443), + Some(AllowedTransports::Tls) + ); + endpoint.allowed_transports = vec![ + NetworkTransport::Plaintext as i32, + NetworkTransport::Tls as i32, + ]; + assert_eq!( + endpoint_allowed_transports(&endpoint, 443), + Some(AllowedTransports::Both) + ); + endpoint.allowed_transports.pop(); + assert_eq!( + endpoint_allowed_transports(&endpoint, 443), + Some(AllowedTransports::Plaintext) + ); + } + + #[test] + fn invalid_transport_sets_and_opaque_protocols_are_rejected() { + let tls = NetworkTransport::Tls as i32; + for invalid in [&[0][..], &[99], &[tls, tls]] { + assert!(validate_allowed_transports(invalid, "rest", 0).is_some()); + } + for protocol in ["", "tcp", "sql", "ssh"] { + assert!(validate_allowed_transports(&[tls], protocol, 0).is_some()); + assert_eq!( + effective_allowed_transports(&[], inspected_protocol(protocol, 0), false, 443), + Ok(None) + ); + } + assert!(validate_allowed_transports(&[tls], "rest", NetworkTlsMode::Skip as i32).is_some()); + } +} + #[cfg(test)] mod agent_transport_tests { use super::agent_authored_transport_rejection; @@ -756,7 +938,7 @@ pub struct EffectiveFilesystem { /// Returns the ports an endpoint selector lists, as written: `ports`, or else /// the singular `port`, even when it is unset (0). #[must_use] -pub fn selector_ports(endpoint: &crate::proto::NetworkEndpoint) -> &[u32] { +pub fn selector_ports(endpoint: &NetworkEndpoint) -> &[u32] { if endpoint.ports.is_empty() { std::slice::from_ref(&endpoint.port) } else { @@ -767,7 +949,7 @@ pub fn selector_ports(endpoint: &crate::proto::NetworkEndpoint) -> &[u32] { /// Returns the ports an endpoint selector covers: [`selector_ports`] /// without an unset singular `port`. #[must_use] -pub fn effective_endpoint_ports(endpoint: &crate::proto::NetworkEndpoint) -> Vec { +pub fn effective_endpoint_ports(endpoint: &NetworkEndpoint) -> Vec { if endpoint.ports.is_empty() { (endpoint.port != 0) .then_some(endpoint.port) diff --git a/crates/openshell-policy-cedar-adapter/src/lib.rs b/crates/openshell-policy-cedar-adapter/src/lib.rs index 71878d7f10..efbfb652e8 100644 --- a/crates/openshell-policy-cedar-adapter/src/lib.rs +++ b/crates/openshell-policy-cedar-adapter/src/lib.rs @@ -54,6 +54,19 @@ pub fn effective_filesystem(source: &str) -> Result { Ok(engine_filesystem(&engine)) } +/// Derive the host and port selectors of a policy's inspected HTTP endpoints. +/// +/// # Errors +/// Returns an error if the policy cannot be loaded. +pub fn http_endpoint_selectors(source: &str) -> Result> { + let engine = + CedarEngine::from_policy_str(source).map_err(|error| miette::miette!("{error}"))?; + Ok(engine + .configured_l7_endpoints() + .map(|(host, port, _, _)| (host, port)) + .collect()) +} + /// Returns the first inspected `host:port` that `endpoint` selects when it /// sets `tls: skip`. /// diff --git a/crates/openshell-policy-cedar-runtime/src/cedar_only/routes.rs b/crates/openshell-policy-cedar-runtime/src/cedar_only/routes.rs index 407f341486..614762a486 100644 --- a/crates/openshell-policy-cedar-runtime/src/cedar_only/routes.rs +++ b/crates/openshell-policy-cedar-runtime/src/cedar_only/routes.rs @@ -11,7 +11,9 @@ use std::sync::Arc; use miette::Result; use openshell_core::endpoint_path::path_specificity; use openshell_core::policy_identity::deterministic_policy_hash; -use openshell_core::proto::{NetworkPolicyRule, SandboxPolicy as ProtoSandboxPolicy}; +use openshell_core::proto::{ + NetworkPolicyRule, NetworkTransport, SandboxPolicy as ProtoSandboxPolicy, +}; use openshell_ocsf::{ConfigStateChangeBuilder, SeverityId, StateId, StatusId, ocsf_emit}; use openshell_policy_cedar::{ AuthorizedNetworkEndpoint, CedarEngine, IpNet, L7Endpoint, L7Protocol, TokenGrantRules, @@ -223,7 +225,21 @@ impl LoadedPolicy { /// effect, so a config carrying it is added when no other config exists. pub(super) fn endpoint_configs(&self, host: &str, port: u16) -> Vec { let plan = self.route_plan(host, port); - plan.routes.iter().map(|route| plan.build(route)).collect() + let mut configs: Vec<_> = plan.routes.iter().map(|route| plan.build(route)).collect(); + // Cedar derives separate request configs for paths on one connection. + // An inspected credentialed path makes TLS the default at its + // authority, while explicit transport selections still have to agree. + if configs + .iter() + .any(|config| config.protocol.l7().is_some() && config.is_credentialed()) + { + for config in &mut configs { + if config.protocol.l7().is_some() && config.allowed_transports.is_empty() { + config.allowed_transports.push(NetworkTransport::Tls as i32); + } + } + } + configs } /// Plans the endpoint configs for `host:port`, in the order @@ -979,6 +995,8 @@ fn provider_config(endpoint: &openshell_core::proto::NetworkEndpoint) -> Endpoin .collect(), path: endpoint.path.clone(), tls: TlsSetting::from_proto(endpoint.tls), + allowed_transports: endpoint.allowed_transports.clone(), + has_credential_binding: endpoint.credential_binding.is_some(), allow_encoded_slash: endpoint.allow_encoded_slash, websocket_credential_rewrite: endpoint.websocket_credential_rewrite, request_body_credential_rewrite: endpoint.request_body_credential_rewrite, diff --git a/crates/openshell-policy-cedar-runtime/src/cedar_only/tests.rs b/crates/openshell-policy-cedar-runtime/src/cedar_only/tests.rs index 73bc919c0e..04149d783f 100644 --- a/crates/openshell-policy-cedar-runtime/src/cedar_only/tests.rs +++ b/crates/openshell-policy-cedar-runtime/src/cedar_only/tests.rs @@ -1843,6 +1843,33 @@ fn ctx_for(host: &str) -> L7EvalContext { } } +#[test] +fn credentialed_cedar_path_sets_tls_default_for_its_authority() { + use openshell_core::policy_l7::AllowedTransports; + + let mut provider = credentialed_endpoint(); + provider.path = "/ws".to_string(); + provider.port = 8443; + let cedar = PATHS_POLICY.replace(":443", ":8443"); + let engine = CedarOnlyEngine::from_proto(&provider_policy(&cedar, vec![provider])) + .expect("policy loads"); + let configs = engine + .credential_guards("api.example.com", 8443) + .expect("configs build"); + + assert_eq!(configs.len(), 3); + assert!(configs.iter().all(|config| { + config.allowed_transports_for_port(8443).unwrap() == Some(AllowedTransports::Tls) + })); + assert_eq!( + configs + .iter() + .filter(|config| config.is_credentialed()) + .count(), + 1 + ); +} + #[test] fn provider_endpoints_take_the_inspection_of_their_path() { let mut ws = credentialed_endpoint(); diff --git a/crates/openshell-policy-runtime-interface/src/policy_data.rs b/crates/openshell-policy-runtime-interface/src/policy_data.rs index 80e45db0ba..8ecc61c5a6 100644 --- a/crates/openshell-policy-runtime-interface/src/policy_data.rs +++ b/crates/openshell-policy-runtime-interface/src/policy_data.rs @@ -59,6 +59,17 @@ pub fn endpoint_policy_value( .map_or_else(|| format!("unknown({})", e.tls), str::to_owned) .into(); } + if !e.allowed_transports.is_empty() { + let labels: Vec<_> = e + .allowed_transports + .iter() + .map(|value| { + openshell_core::policy_l7::network_transport_to_str(*value) + .map_or_else(|| format!("unknown({value})"), str::to_owned) + }) + .collect(); + ep["allowed_transports"] = labels.into(); + } if e.enforcement != 0 { ep["enforcement"] = openshell_core::policy_l7::network_enforcement_mode_to_str(e.enforcement) diff --git a/crates/openshell-policy-runtime-interface/src/policy_types.rs b/crates/openshell-policy-runtime-interface/src/policy_types.rs index 11d9156ebb..65fb0b4e80 100644 --- a/crates/openshell-policy-runtime-interface/src/policy_types.rs +++ b/crates/openshell-policy-runtime-interface/src/policy_types.rs @@ -12,8 +12,10 @@ use std::sync::Arc; use std::sync::atomic::{AtomicU64, Ordering}; use miette::Result; -use openshell_core::policy_l7::L7Protocol; -use serde::Deserialize; +use openshell_core::policy_l7::{ + AllowedTransports, L7Protocol, effective_allowed_transports, network_transport_from_str, +}; +use serde::{Deserialize, Deserializer}; use tokio::sync::watch; /// The `protocol` of a policy endpoint. @@ -236,6 +238,9 @@ pub struct EndpointConfig { pub path: String, pub protocol: EndpointProtocol, pub tls: TlsSetting, + /// Authored transport selectors. Empty means the endpoint uses the port and credential defaults. + #[serde(deserialize_with = "deserialize_allowed_transports")] + pub allowed_transports: Vec, pub enforcement: EnforcementSetting, pub access: AccessSetting, pub rules: Vec, @@ -247,6 +252,11 @@ pub struct EndpointConfig { pub request_body_credential_rewrite: bool, pub allow_uninspected_credentials: bool, pub provider_credentialed: bool, + #[serde( + rename = "credential_binding", + deserialize_with = "deserialize_credential_binding" + )] + pub has_credential_binding: bool, /// Set by the Cedar engine for a `websocket-graphql` endpoint; a YAML /// endpoint opts in through its GraphQL rules instead. pub websocket_graphql_policy: bool, @@ -274,6 +284,52 @@ pub struct EndpointConfig { pub mcp_strict_tool_names: Option, } +impl EndpointConfig { + /// Whether this endpoint can supply credentials to an inspected request. + pub fn is_credentialed(&self) -> bool { + self.provider_credentialed + || self.has_credential_binding + || !self.credential_signing.is_empty() + } + + /// Resolve the inspected transport set for the actual destination port. + pub fn allowed_transports_for_port( + &self, + port: u16, + ) -> std::result::Result, &'static str> { + let protocol = match self.tls { + TlsSetting::Auto => self.protocol.l7(), + TlsSetting::Skip => None, + TlsSetting::Unknown => return Err("unknown endpoint TLS setting"), + }; + effective_allowed_transports( + &self.allowed_transports, + protocol, + self.is_credentialed(), + u32::from(port), + ) + } +} + +fn deserialize_allowed_transports<'de, D: Deserializer<'de>>( + deserializer: D, +) -> std::result::Result, D::Error> { + Vec::::deserialize(deserializer)? + .iter() + .map(|value| { + network_transport_from_str(value) + .map(|transport| transport as i32) + .ok_or_else(|| serde::de::Error::custom("invalid endpoint transport")) + }) + .collect() +} + +fn deserialize_credential_binding<'de, D: Deserializer<'de>>( + deserializer: D, +) -> std::result::Result { + Ok(Option::>::deserialize(deserializer)?.is_some()) +} + /// One policy endpoint as policy DNS reads it: its host selector, ports, /// transport, and resolution allowlist. #[derive(Debug, Clone, PartialEq, Eq, Default, Deserialize)] diff --git a/crates/openshell-policy-schema/src/lib.rs b/crates/openshell-policy-schema/src/lib.rs index 89290be888..e6bce8d01e 100644 --- a/crates/openshell-policy-schema/src/lib.rs +++ b/crates/openshell-policy-schema/src/lib.rs @@ -275,6 +275,13 @@ pub struct NetworkEndpoint { pub protocol: String, #[serde(default, skip_serializing_if = "String::is_empty")] pub tls: String, + /// Explicit transports for an inspected HTTP-family endpoint. + #[serde( + default, + deserialize_with = "deserialize_allowed_transports", + skip_serializing_if = "Vec::is_empty" + )] + pub allowed_transports: Vec, #[serde(default, skip_serializing_if = "String::is_empty")] pub enforcement: String, #[serde(default, skip_serializing_if = "String::is_empty")] @@ -531,6 +538,35 @@ where .ok_or_else(|| serde::de::Error::custom("null is not allowed for this field")) } +/// Parse a present transport allowlist shared by sandbox policies and profiles. +pub fn deserialize_allowed_transports<'de, D>( + deserializer: D, +) -> std::result::Result, D::Error> +where + D: Deserializer<'de>, +{ + let transports = Vec::::deserialize(deserializer)?; + if transports.is_empty() { + return Err(serde::de::Error::custom( + "allowed_transports must contain at least one transport when present", + )); + } + let mut seen = BTreeSet::new(); + for transport in &transports { + if !matches!(transport.as_str(), "tls" | "plaintext") { + return Err(serde::de::Error::custom(format!( + "unknown allowed_transports value '{transport}'. Expected tls or plaintext" + ))); + } + if !seen.insert(transport) { + return Err(serde::de::Error::custom(format!( + "duplicate allowed_transports value '{transport}'" + ))); + } + } + Ok(transports) +} + const MAX_UNKNOWN_FIELD_PATH_BYTES: usize = 1_024; // Unknown fields are inspected only to produce fail-closed diagnostics. @@ -835,6 +871,7 @@ fn inspect_endpoint(value: &serde_yml::Value, path: &str) -> InspectionResult { "ports", "protocol", "tls", + "allowed_transports", "enforcement", "access", "rules", diff --git a/crates/openshell-policy/src/ambiguity.rs b/crates/openshell-policy/src/ambiguity.rs index efb846a9a1..3c4c1e94f7 100644 --- a/crates/openshell-policy/src/ambiguity.rs +++ b/crates/openshell-policy/src/ambiguity.rs @@ -3,6 +3,7 @@ //! Validation for endpoint selectors whose policy-derived behavior conflicts. +use openshell_core::policy_l7::endpoint_allowed_transports; use openshell_core::proto::{ NetworkEndpoint, NetworkEnforcementMode, NetworkTlsMode, SandboxPolicy, }; @@ -91,6 +92,21 @@ pub fn find_endpoint_ambiguities(policy: &SandboxPolicy) -> Vec NetworkEndpoint { ports: normalized_ports, protocol: protocol.clone(), tls: network_tls_mode_from_str(&e.tls).expect("endpoint modes validated above") as i32, + allowed_transports: e + .allowed_transports + .iter() + .map(|transport| { + network_transport_from_str(transport) + .expect("authored transports validated by policy schema") as i32 + }) + .collect(), enforcement: network_enforcement_mode_from_str(&e.enforcement) .expect("endpoint modes validated above") as i32, access: network_access_preset_from_str(&e.access).expect("endpoint modes validated above") @@ -588,26 +603,40 @@ fn to_proto(raw: PolicyFile) -> Result { .network_policies .into_iter() .map(|(key, rule)| { + let endpoints = rule + .endpoints + .into_iter() + .map(endpoint_def_to_proto) + .enumerate() + .map(|(index, endpoint)| { + if let Some(reason) = validate_allowed_transports( + &endpoint.allowed_transports, + &endpoint.protocol, + endpoint.tls, + ) { + return Err(miette::miette!( + "network policy '{key}': endpoint {index}: {reason}" + )); + } + Ok(endpoint) + }) + .collect::>>()?; let proto_rule = NetworkPolicyRule { name: if rule.name.is_empty() { key.clone() } else { rule.name }, - endpoints: rule - .endpoints - .into_iter() - .map(endpoint_def_to_proto) - .collect(), + endpoints, binaries: rule .binaries .into_iter() .map(|b| NetworkBinary { path: b.path }) .collect(), }; - (key, proto_rule) + Ok((key, proto_rule)) }) - .collect(); + .collect::>>()?; Ok(SandboxPolicy { version: raw.version, @@ -646,6 +675,10 @@ fn endpoint_setting_def_to_proto( index: usize, setting: NetworkEndpointDef, ) -> Result { + if !setting.allowed_transports.is_empty() { + let reason = RejectedSettingField::Access.reason("allowed_transports"); + miette::bail!("endpoint_settings[{index}]: {reason}"); + } let errors = validate_endpoint_modes(&setting.tls, &setting.enforcement, &setting.access); if !errors.is_empty() { return Err(miette::miette!( @@ -771,6 +804,15 @@ fn endpoint_proto_to_def(e: &NetworkEndpoint) -> Result { tls: network_tls_mode_to_str(e.tls) .expect("policy enum values validated before serialization") .to_string(), + allowed_transports: e + .allowed_transports + .iter() + .map(|&transport| { + network_transport_to_str(transport) + .map(str::to_owned) + .ok_or_else(|| miette::miette!("invalid allowed_transports value {transport}")) + }) + .collect::>()?, enforcement: network_enforcement_mode_to_str(e.enforcement) .expect("policy enum values validated before serialization") .to_string(), @@ -1185,10 +1227,22 @@ fn validate_proto_version_for_authored_serialization(policy: &SandboxPolicy) -> } fn validate_policy_enum_values(policy: &SandboxPolicy) -> Result<()> { - for (policy_name, rule) in &policy.network_policies { + for (policy_name, rule) in policy + .network_policies + .iter() + .chain(&policy.provider_credential_rules) + { for (endpoint_index, endpoint) in rule.endpoints.iter().enumerate() { - let errors = + let mut errors = validate_endpoint_mode_values(endpoint.tls, endpoint.enforcement, endpoint.access); + errors.extend( + validate_allowed_transports( + &endpoint.allowed_transports, + &endpoint.protocol, + endpoint.tls, + ) + .map(str::to_owned), + ); if !errors.is_empty() { return Err(miette::miette!( "network policy '{policy_name}': endpoint {endpoint_index}: {}", @@ -1198,8 +1252,11 @@ fn validate_policy_enum_values(policy: &SandboxPolicy) -> Result<()> { } } for (index, setting) in policy.endpoint_settings.iter().enumerate() { - let errors = + let mut errors = validate_endpoint_mode_values(setting.tls, setting.enforcement, setting.access); + if !setting.allowed_transports.is_empty() { + errors.push(RejectedSettingField::Access.reason("allowed_transports")); + } if !errors.is_empty() { return Err(miette::miette!( "endpoint_settings[{index}]: {}", @@ -1983,6 +2040,10 @@ fn validate_sandbox_policy_with_mcp_presence( ep.enforcement, ep.access, )); + l7_errors.extend( + validate_allowed_transports(&ep.allowed_transports, &ep.protocol, ep.tls) + .map(str::to_owned), + ); let mut explicit_tcp_fields = Vec::new(); if ep.enforcement != 0 { explicit_tcp_fields.push("enforcement"); @@ -2145,6 +2206,7 @@ fn endpoint_setting_rejected_fields( mcp, // Access and inspection, which the Cedar policy decides. protocol, + allowed_transports, enforcement, access, rules, @@ -2179,6 +2241,11 @@ fn endpoint_setting_rejected_fields( !protocol.is_empty(), RejectedSettingField::Access, ), + ( + "allowed_transports", + !allowed_transports.is_empty(), + RejectedSettingField::Access, + ), ( "enforcement", *enforcement != 0, @@ -3122,6 +3189,7 @@ when { context.binary_path == "/usr/bin/curl" }; fn endpoint_settings_reject_access_and_credential_fields() { for (field, yaml) in [ ("protocol", "protocol: rest"), + ("allowed_transports", "allowed_transports: [tls]"), ("enforcement", "enforcement: enforce"), ("access", "access: read-only"), ("rules", "rules: [{ allow: { method: GET } }]"), @@ -3643,6 +3711,114 @@ network_policies: assert_eq!(ep1.allowed_ips, vec!["10.0.5.0/24", "10.0.6.0/24"]); } + fn transport_endpoint_yaml(fields: &str) -> String { + format!( + "version: 1\nnetwork_policies:\n api:\n endpoints: [{{ host: api.example.com, port: 8443, {fields} }}]\n" + ) + } + + #[test] + fn allowed_transports_round_trip_in_policy_yaml_and_json() { + use openshell_core::proto::NetworkTransport; + + for protocol in ["rest", "graphql", "websocket", "mcp", "json-rpc"] { + let policy = parse_sandbox_policy(&transport_endpoint_yaml(&format!( + "protocol: {protocol}, access: full, allowed_transports: [plaintext, tls]" + ))) + .expect("inspected policy"); + assert_eq!( + policy.network_policies["api"].endpoints[0].allowed_transports, + [ + NetworkTransport::Plaintext as i32, + NetworkTransport::Tls as i32 + ], + ); + let yaml = serialize_sandbox_policy(&policy).expect("serialize"); + assert_eq!(parse_sandbox_policy(&yaml).expect("reparse"), policy); + let json = sandbox_policy_to_json_value(&policy).expect("serialize"); + assert_eq!( + json["network_policies"]["api"]["endpoints"][0]["allowed_transports"], + serde_json::json!(["plaintext", "tls"]), + ); + } + + let policy = parse_sandbox_policy(&transport_endpoint_yaml("protocol: rest, access: full")) + .expect("omitted allowlist"); + assert!( + policy.network_policies["api"].endpoints[0] + .allowed_transports + .is_empty() + ); + let yaml = serialize_sandbox_policy(&policy).expect("serialize omitted allowlist"); + assert!(!yaml.contains("allowed_transports")); + } + + #[test] + fn authored_transports_reject_invalid_lists_and_unsupported_endpoints() { + for transports in [ + "[]", + "[tls, tls]", + "[https]", + "[null]", + "null", + "tls", + "[1]", + ] { + let source = transport_endpoint_yaml(&format!( + "protocol: rest, access: full, allowed_transports: {transports}" + )); + let error = parse_sandbox_policy(&source).expect_err(transports); + assert!( + error_chain(&error).contains("allowed_transports"), + "{error:?}" + ); + } + for fields in [ + "protocol: rest, tls: skip, access: full", + "protocol: sql, access: full", + "protocol: tcp", + "protocol: ''", + ] { + let source = transport_endpoint_yaml(&format!("{fields}, allowed_transports: [tls]")); + let error = parse_sandbox_policy(&source).expect_err(fields); + assert!( + error_chain(&error).contains("allowed_transports"), + "{error:?}" + ); + } + } + + #[test] + fn wire_policy_rejects_invalid_allowed_transports() { + use openshell_core::proto::{NetworkTlsMode, NetworkTransport}; + + let tls = NetworkTransport::Tls as i32; + for (transports, protocol, tls_mode) in [ + (vec![NetworkTransport::Unspecified as i32], "rest", 0), + (vec![99], "rest", 0), + (vec![tls, tls], "rest", 0), + (vec![tls], "rest", NetworkTlsMode::Skip as i32), + (vec![tls], "sql", 0), + (vec![tls], "tcp", 0), + (vec![tls], "", 0), + ] { + let mut policy = + parse_sandbox_policy(&transport_endpoint_yaml("protocol: rest, access: full")) + .expect("base policy"); + let endpoint = &mut policy.network_policies.get_mut("api").unwrap().endpoints[0]; + endpoint.allowed_transports = transports; + endpoint.protocol = protocol.to_owned(); + endpoint.tls = tls_mode; + let errors = validate_sandbox_policy(&policy).expect_err("wire allowlist is invalid"); + assert!( + errors + .iter() + .any(|error| error.to_string().contains("allowed_transports")) + ); + assert!(serialize_sandbox_policy(&policy).is_err()); + } + } + /// Verify that the network policy `name` field survives the round-trip. #[test] fn round_trip_preserves_policy_name() { diff --git a/crates/openshell-policy/src/merge.rs b/crates/openshell-policy/src/merge.rs index c010e6a723..7840605f59 100644 --- a/crates/openshell-policy/src/merge.rs +++ b/crates/openshell-policy/src/merge.rs @@ -3,9 +3,10 @@ use std::collections::{BTreeMap, HashMap, HashSet}; +use openshell_core::policy_l7::{AllowedTransports, endpoint_allowed_transports}; use openshell_core::proto::{ L7Allow, L7DenyRule, L7Rule, NetworkAccessPreset, NetworkBinary, NetworkEndpoint, - NetworkEnforcementMode, NetworkPolicyRule, NetworkTlsMode, SandboxPolicy, + NetworkEnforcementMode, NetworkPolicyRule, NetworkTlsMode, NetworkTransport, SandboxPolicy, }; use crate::{ @@ -39,7 +40,10 @@ pub fn canonicalize_advisor_add_rule( let incoming_endpoint = &incoming_rule.endpoints[0]; let incoming_ports = canonical_ports(incoming_endpoint); - if incoming_endpoint.host.trim().is_empty() || incoming_ports.len() != 1 { + if incoming_endpoint.host.trim().is_empty() + || incoming_ports.len() != 1 + || !incoming_endpoint.allowed_transports.is_empty() + { return Ok((requested_rule_name.to_string(), incoming_rule.clone())); } let port = incoming_ports[0]; @@ -53,18 +57,19 @@ pub fn canonicalize_advisor_add_rule( }) .cloned() .map(|mut endpoint| { - // Provenance does not change the endpoint contract. The gateway - // derives credential markers and token owners; the advisor marker - // records where a persisted endpoint came from. - endpoint.provider_credentialed = false; - endpoint.advisor_proposed = false; - endpoint.token_grant_owner.clear(); - // A denial observes one binary-to-port authorization. Preserve the - // existing inspection contract, but never copy sibling ports from - // a multi-port endpoint into the proposal. + let transports = endpoint_allowed_transports(&endpoint, port); + // A denial observes one binary-to-port authorization. Never copy + // sibling ports from a multi-port endpoint into the proposal. endpoint.port = port; endpoint.ports = vec![port]; - normalize_endpoint(&mut endpoint); + normalize_advisor_contract(&mut endpoint); + // Preserve the credential-derived TLS default if removing the + // provider provenance would broaden the mirrored authorization. + if transports == Some(AllowedTransports::Tls) + && endpoint_allowed_transports(&endpoint, port) != transports + { + endpoint.allowed_transports = vec![NetworkTransport::Tls as i32]; + } endpoint }) .collect::>(); @@ -92,10 +97,7 @@ pub fn canonicalize_advisor_add_rule( .filter_map(|(name, rule)| { (rule.endpoints.iter().any(|endpoint| { let mut normalized = endpoint.clone(); - normalized.provider_credentialed = false; - normalized.advisor_proposed = false; - normalized.token_grant_owner.clear(); - normalize_endpoint(&mut normalized); + normalize_advisor_contract(&mut normalized); normalized == contract }) && incoming_rule .binaries @@ -114,10 +116,7 @@ pub fn canonicalize_advisor_add_rule( .iter() .find(|endpoint| { let mut normalized = (*endpoint).clone(); - normalized.provider_credentialed = false; - normalized.advisor_proposed = false; - normalized.token_grant_owner.clear(); - normalize_endpoint(&mut normalized); + normalize_advisor_contract(&mut normalized); normalized == contract }) { @@ -144,6 +143,14 @@ pub fn canonicalize_advisor_add_rule( Ok((target_name, canonical)) } +fn normalize_advisor_contract(endpoint: &mut NetworkEndpoint) { + endpoint.provider_credentialed = false; + endpoint.advisor_proposed = false; + endpoint.token_grant_owner.clear(); + normalize_endpoint(endpoint); + endpoint.allowed_transports.sort_unstable(); +} + /// Binary authorization affected by an incremental L7 rule append. #[derive(Debug, Clone, PartialEq, Eq)] pub enum L7BinaryScope { @@ -407,6 +414,12 @@ pub enum PolicyMergeError { /// Rendered effective contract the operation asked for. incoming: String, }, + /// Folding would change an existing or incoming transport contract. + TransportContractConflict { + operation_index: usize, + host: String, + port: u32, + }, /// Newly added binary scope would inherit an existing endpoint /// authorization that the incoming rule did not declare. NewBinaryWouldInheritAuthorization { @@ -550,6 +563,14 @@ impl std::fmt::Display for PolicyMergeError { f, "merge operation {operation_index} cannot combine MCP contracts at {host}:{port}: existing {existing}, incoming {incoming}" ), + Self::TransportContractConflict { + operation_index, + host, + port, + } => write!( + f, + "merge operation {operation_index} cannot combine allowed_transports at {host}:{port} without changing an endpoint transport contract" + ), Self::NewBinaryWouldInheritAuthorization { operation_index, rule_name, @@ -839,6 +860,11 @@ fn endpoint_attributes_cover(loaded: &NetworkEndpoint, proposed: &NetworkEndpoin if proposed.tls != NetworkTlsMode::Unspecified as i32 && loaded.tls != proposed.tls { return false; } + if !proposed.allowed_transports.is_empty() + && !transport_lists_match(&loaded.allowed_transports, &proposed.allowed_transports) + { + return false; + } if proposed.enforcement != NetworkEnforcementMode::Unspecified as i32 && effective_enforcement(loaded.enforcement) != effective_enforcement(proposed.enforcement) { @@ -1459,10 +1485,10 @@ fn is_authorization_inheritance_conflict(error: &PolicyMergeError) -> bool { | PolicyMergeError::ExistingBinariesWouldInheritAuthorization { .. } | PolicyMergeError::UndeclaredPortWouldChange { .. } => true, - // Separating the rules does not help. The supervisor establishes one MCP - // inspection contract per host and port rather than per rule, so two - // contracts stay ambiguous however they are split. + // Splitting rules can leave a shared host and port with conflicting + // inspection or transport contracts. PolicyMergeError::McpContractConflict { .. } + | PolicyMergeError::TransportContractConflict { .. } | PolicyMergeError::ConflictingInspectionContracts { .. } => false, // Reports an unsupported or missing state in the policy the fold @@ -1579,13 +1605,28 @@ fn merge_endpoint( let existing_ports = canonical_ports(existing); let incoming_ports = canonical_ports(incoming); let port = existing_ports - .into_iter() + .iter() + .copied() .find(|port| incoming_ports.contains(port)) .or_else(|| incoming_ports.first().copied()) .unwrap_or(0); let promotes_l4_to_mcp = promotes_l4_endpoint_to_mcp(existing, incoming); ensure_mcp_contract_compatible(existing, incoming, operation_index, &host, port)?; + if let Some(conflict_port) = + transport_conflict_port(existing, incoming, &existing_ports, &incoming_ports, port) + { + return Err(PolicyMergeError::TransportContractConflict { + operation_index, + host, + port: conflict_port, + }); + } + if existing.allowed_transports.is_empty() { + existing + .allowed_transports + .clone_from(&incoming.allowed_transports); + } if existing.host.is_empty() { existing.host.clone_from(&incoming.host); @@ -1681,6 +1722,48 @@ fn merge_endpoint( Ok(()) } +fn transport_lists_match(left: &[i32], right: &[i32]) -> bool { + left.len() == right.len() && contains_all(left, right) && contains_all(right, left) +} + +fn transport_conflict_port( + existing: &NetworkEndpoint, + incoming: &NetworkEndpoint, + existing_ports: &[u32], + incoming_ports: &[u32], + overlapping_port: u32, +) -> Option { + match ( + existing.allowed_transports.is_empty(), + incoming.allowed_transports.is_empty(), + ) { + (true, true) => None, + (false, false) => { + (!transport_lists_match(&existing.allowed_transports, &incoming.allowed_transports)) + .then_some(overlapping_port) + } + // Taking on an explicit allowlist cannot change the transport on any + // existing port, even a sibling port the incoming rule did not name. + (true, false) => existing_ports.iter().copied().find(|&port| { + endpoint_allowed_transports(existing, port) + != endpoint_allowed_transports(incoming, port) + }), + // The existing allowlist is retained. On newly added ports, it must + // agree with any transport default selected by the incoming rule. + (false, true) => { + if incoming.tls == NetworkTlsMode::Skip as i32 { + return Some(overlapping_port); + } + incoming_ports.iter().copied().find(|&port| { + !existing_ports.contains(&port) + && endpoint_allowed_transports(incoming, port).is_some_and(|transports| { + endpoint_allowed_transports(existing, port) != Some(transports) + }) + }) + } + } +} + fn ensure_mcp_contract_compatible( existing: &NetworkEndpoint, incoming: &NetworkEndpoint, @@ -1874,7 +1957,8 @@ fn operation_declares( /// judged against. /// /// A carry-over field is one the merge never widens: it either retains the -/// existing value (`protocol`, `tls`, `enforcement`, `access`) or ignores the +/// existing value (`protocol`, `tls`, `allowed_transports`, `enforcement`, +/// `access`) or ignores the /// incoming value entirely (the signing and GraphQL fields). Either way the new /// binary receives whatever the endpoint already carried, and the operation /// cannot change it, so a declaration that leaves the field unset expresses no @@ -1903,6 +1987,11 @@ fn adopt_unset_retained_fields( if adopted.tls == NetworkTlsMode::Unspecified as i32 { adopted.tls = merged.tls; } + if adopted.allowed_transports.is_empty() { + adopted + .allowed_transports + .clone_from(&merged.allowed_transports); + } if adopted.enforcement == NetworkEnforcementMode::Unspecified as i32 { adopted.enforcement = merged.enforcement; } @@ -2420,7 +2509,7 @@ mod tests { proto::{ L7Allow, L7DenyRule, L7QueryMatcher, L7Rule, McpOptions, NetworkAccessPreset, NetworkBinary, NetworkEndpoint, NetworkEnforcementMode, NetworkPolicyRule, - NetworkTlsMode, SandboxPolicy, + NetworkTlsMode, NetworkTransport, SandboxPolicy, }, }; @@ -2647,7 +2736,7 @@ mod tests { #[test] fn canonicalize_advisor_mirrors_provider_contract_into_sandbox_overlay() { let base = SandboxPolicy::default(); - let mut provider_endpoint = endpoint("api.example.com", 443); + let mut provider_endpoint = endpoint("api.example.com", 8443); provider_endpoint.protocol = "rest".to_string(); provider_endpoint.enforcement = NetworkEnforcementMode::Enforce as i32; provider_endpoint.access = NetworkAccessPreset::ReadOnly as i32; @@ -2666,7 +2755,7 @@ mod tests { name: "advisor_example".to_string(), endpoints: vec![NetworkEndpoint { host: "api.example.com".to_string(), - port: 443, + port: 8443, advisor_proposed: true, ..Default::default() }], @@ -2683,6 +2772,10 @@ mod tests { NetworkAccessPreset::ReadOnly as i32 ); assert!(!canonical.endpoints[0].provider_credentialed); + assert_eq!( + canonical.endpoints[0].allowed_transports, + [NetworkTransport::Tls as i32] + ); assert!(canonical.endpoints[0].advisor_proposed); assert!(canonical.endpoints[0].token_grant_owner.is_empty()); assert_eq!( @@ -2881,6 +2974,90 @@ mod tests { policy } + fn transport_rule(ports: &[u32], transports: &[NetworkTransport]) -> NetworkPolicyRule { + rule_with_authorizations( + "api", + vec![NetworkEndpoint { + ports: ports.to_vec(), + protocol: "rest".to_owned(), + access: NetworkAccessPreset::Full as i32, + allowed_transports: transports + .iter() + .map(|transport| *transport as i32) + .collect(), + ..endpoint("api.example.com", ports[0]) + }], + &["/usr/bin/client"], + ) + } + + #[test] + fn merge_keeps_explicit_transport_sets_and_coverage() { + let tls = NetworkTransport::Tls; + let plaintext = NetworkTransport::Plaintext; + let default_tls = policy_with_rule("api", transport_rule(&[443], &[])); + let explicit_tls = transport_rule(&[443], &[tls]); + assert!(!policy_covers_rule(&default_tls, &explicit_tls)); + let adopted = merge_policy( + default_tls, + &[PolicyMergeOp::AddRule { + rule_name: "api".to_owned(), + rule: explicit_tls.clone(), + }], + ) + .expect("the explicit TLS list preserves the existing port's behavior"); + assert!(policy_covers_rule(&adopted.policy, &explicit_tls)); + + let loaded = policy_with_rule("api", transport_rule(&[8443], &[tls, plaintext])); + let reversed = transport_rule(&[8443], &[plaintext, tls]); + assert!(policy_covers_rule(&loaded, &reversed)); + let merged = merge_policy( + loaded, + &[PolicyMergeOp::AddRule { + rule_name: "api".to_owned(), + rule: reversed, + }], + ) + .expect("transport list order does not change authorization"); + assert!(!merged.changed); + } + + #[test] + fn merge_rejects_transport_changes_across_overlapping_ports() { + let tls = NetworkTransport::Tls; + let plaintext = NetworkTransport::Plaintext; + for (loaded, incoming, conflict_port) in [ + ( + transport_rule(&[443], &[tls]), + transport_rule(&[443], &[plaintext]), + 443, + ), + ( + transport_rule(&[443, 8443], &[]), + transport_rule(&[443], &[tls]), + 8443, + ), + ( + transport_rule(&[8443], &[tls, plaintext]), + transport_rule(&[443, 8443], &[]), + 443, + ), + ] { + let result = merge_policy( + policy_with_rule("api", loaded), + &[PolicyMergeOp::AddRule { + rule_name: "api".to_owned(), + rule: incoming, + }], + ); + assert!( + matches!(result, Err(PolicyMergeError::TransportContractConflict { port, .. }) + if port == conflict_port), + "{result:?}" + ); + } + } + fn mcp_endpoint_with_versions(versions: &[&str]) -> NetworkEndpoint { let mut endpoint = mcp_endpoint( "mcp.example.com", diff --git a/crates/openshell-prover/src/containment.rs b/crates/openshell-prover/src/containment.rs index a5f795c426..8dbedccfad 100644 --- a/crates/openshell-prover/src/containment.rs +++ b/crates/openshell-prover/src/containment.rs @@ -1627,6 +1627,11 @@ fn validate_supported_endpoint_extensions( context: &str, endpoint: &Endpoint, ) -> Result<(), UnsupportedFeature> { + if !endpoint.allowed_transports.is_empty() { + return Err(UnsupportedFeature::policy_shape(format!( + "{context} uses allowed_transports outside the containment model" + ))); + } if !endpoint.tls.is_empty() || endpoint.allow_encoded_slash || endpoint.websocket_credential_rewrite @@ -2715,6 +2720,26 @@ mod tests { } } + #[test] + fn transport_allowlists_fail_closed_in_both_containment_inputs() { + let restricted = parse( + "version: 1\nnetwork_policies:\n n:\n endpoints: [{ host: api.example.com, port: 8443, protocol: rest, enforcement: enforce, access: full, allowed_transports: [tls] }]\n binaries: [{ path: /usr/bin/curl }]\n", + ); + let empty = parse("version: 1\n"); + for (boundary, candidate) in [(&restricted, &empty), (&empty, &restricted)] { + let result = check_within_boundary(boundary, candidate, options()); + assert!( + matches!( + result, + CheckResult::Unsupported(ref evidence) + if evidence.reason_code() == ReasonCode::UnsupportedPolicyShape + && evidence.reason().contains("allowed_transports") + ), + "{result:?}" + ); + } + } + #[test] fn exact_binary_under_a_boundary_glob_requires_image_resolution() { for pattern in ["/usr/bin/*3", "/usr/bin/py**", "/usr/bin/**3"] { diff --git a/crates/openshell-providers/src/profiles.rs b/crates/openshell-providers/src/profiles.rs index 84e982c372..e7d2b703b4 100644 --- a/crates/openshell-providers/src/profiles.rs +++ b/crates/openshell-providers/src/profiles.rs @@ -7,6 +7,9 @@ use openshell_core::mcp::{ DEFAULT_MCP_PROTOCOL_VERSION, McpProtocolVersion, ParseMcpVersionsError, canonicalize_mcp_versions, parse_mcp_versions, }; +use openshell_core::policy_l7::{ + network_transport_from_str, network_transport_to_str, validate_allowed_transports, +}; use openshell_core::proto::{ GraphqlOperation, L7Allow, L7DenyRule, L7QueryMatcher, L7Rule, McpOptions, NetworkBinary, NetworkEndpoint, NetworkPolicyRule, ProviderCredentialRefresh, @@ -17,9 +20,10 @@ use openshell_core::proto::{ }; use openshell_core::secrets::uses_reserved_revision_namespace; use openshell_policy::{ - L7EndpointFields, L7Protocol, network_access_preset_from_str, network_access_preset_to_str, - network_enforcement_mode_from_str, network_enforcement_mode_to_str, network_tls_mode_from_str, - network_tls_mode_to_str, validate_endpoint_modes, validate_explicit_tcp_additional_fields, + L7EndpointFields, L7Protocol, deserialize_allowed_transports, network_access_preset_from_str, + network_access_preset_to_str, network_enforcement_mode_from_str, + network_enforcement_mode_to_str, network_tls_mode_from_str, network_tls_mode_to_str, + validate_endpoint_modes, validate_explicit_tcp_additional_fields, validate_l7_endpoint_semantics, }; use serde::{Deserialize, Deserializer, Serialize, Serializer, de}; @@ -339,6 +343,7 @@ pub struct EndpointProfile { pub port: u32, pub protocol: String, pub tls: String, + pub allowed_transports: Vec, pub access: String, pub enforcement: String, pub rules: Option>, @@ -384,6 +389,12 @@ struct EndpointProfileSerde { protocol: String, #[serde(default, skip_serializing_if = "String::is_empty")] tls: String, + #[serde( + default, + deserialize_with = "deserialize_allowed_transports", + skip_serializing_if = "Vec::is_empty" + )] + allowed_transports: Vec, #[serde(default, skip_serializing_if = "String::is_empty")] access: String, #[serde(default, skip_serializing_if = "String::is_empty")] @@ -1657,6 +1668,7 @@ fn endpoint_to_proto(endpoint: &EndpointProfile) -> NetworkEndpoint { port: endpoint.port, protocol: endpoint.protocol.clone(), tls: network_tls_mode_from_str(&endpoint.tls).map_or(-1, |value| value as i32), + allowed_transports: endpoint_transport_values(endpoint), enforcement: network_enforcement_mode_from_str(&endpoint.enforcement) .map_or(-1, |value| value as i32), access: network_access_preset_from_str(&endpoint.access).map_or(-1, |value| value as i32), @@ -1702,6 +1714,14 @@ fn endpoint_to_proto(endpoint: &EndpointProfile) -> NetworkEndpoint { } } +fn endpoint_transport_values(endpoint: &EndpointProfile) -> Vec { + endpoint + .allowed_transports + .iter() + .map(|transport| network_transport_from_str(transport).map_or(-1, |value| value as i32)) + .collect() +} + fn endpoint_from_proto(endpoint: &NetworkEndpoint) -> EndpointProfile { let mut profile = EndpointProfile { host: endpoint.host.clone(), @@ -1709,6 +1729,14 @@ fn endpoint_from_proto(endpoint: &NetworkEndpoint) -> EndpointProfile { protocol: endpoint.protocol.clone(), tls: network_tls_mode_to_str(endpoint.tls) .map_or_else(|| format!("unknown({})", endpoint.tls), str::to_owned), + allowed_transports: endpoint + .allowed_transports + .iter() + .map(|&transport| { + network_transport_to_str(transport) + .map_or_else(|| format!("unknown({transport})"), str::to_owned) + }) + .collect(), access: network_access_preset_to_str(endpoint.access) .map_or_else(|| format!("unknown({})", endpoint.access), str::to_owned), enforcement: network_enforcement_mode_to_str(endpoint.enforcement).map_or_else( @@ -2819,6 +2847,18 @@ pub fn validate_catalog_profiles( )); } collect_mcp_profile_diagnostics(source, profile_id, index, endpoint, &mut diagnostics); + if let Some(message) = validate_allowed_transports( + &endpoint_transport_values(endpoint), + &endpoint.protocol, + network_tls_mode_from_str(&endpoint.tls).map_or(-1, |value| value as i32), + ) { + diagnostics.push(ProfileValidationDiagnostic::error( + source, + profile_id, + format!("endpoints[{index}].allowed_transports"), + message, + )); + } if endpoint.rules.as_ref().is_some_and(Vec::is_empty) { diagnostics.push(ProfileValidationDiagnostic::error( @@ -7058,6 +7098,48 @@ credentials: // -- L7 endpoint semantic validation (shared with runtime) ---------------- + #[test] + fn profile_allowed_transports_round_trip_through_proto() { + use openshell_core::proto::NetworkTransport; + + let source = r" +id: restricted +display_name: Restricted +endpoints: + - host: api.example.com + port: 8443 + protocol: rest + access: full + allowed_transports: [tls] +"; + let profile = parse_profile_yaml(source).expect("profile should parse"); + let proto = profile.to_proto(); + assert_eq!( + proto.endpoints[0].allowed_transports, + [NetworkTransport::Tls as i32] + ); + let exported = profile_to_yaml(&ProviderTypeProfile::from_proto(&proto)) + .expect("profile should serialize"); + let reparsed = parse_profile_yaml(&exported).expect("exported profile should parse"); + assert_eq!(reparsed.endpoints[0].allowed_transports, ["tls"]); + + for entry in ["[]", "null", "[tls, tls]", "[https]"] { + assert!( + parse_profile_yaml(&source.replace("[tls]", entry)).is_err(), + "{entry}" + ); + } + let skipped_tls = + parse_profile_yaml(&source.replace("access: full", "access: full\n tls: skip")) + .expect("profile shape should parse"); + let diagnostics = validate_profile_set(&[("restricted.yaml".to_owned(), skipped_tls)]); + assert!( + diagnostics + .iter() + .any(|diagnostic| diagnostic.field == "endpoints[0].allowed_transports") + ); + } + #[test] fn validate_rejects_unknown_security_sensitive_endpoint_values() { let profile = parse_profile_yaml( diff --git a/crates/openshell-server/src/config_delivery/mod.rs b/crates/openshell-server/src/config_delivery/mod.rs index 335c1a0b09..27be802548 100644 --- a/crates/openshell-server/src/config_delivery/mod.rs +++ b/crates/openshell-server/src/config_delivery/mod.rs @@ -29,7 +29,8 @@ use crate::gateway_members::{GatewayMember, GatewayMemberIndex, MEMBER_TTL}; use crate::grpc::policy::{ SandboxConfigInputs, build_provider_environment_snapshot_from_inputs, build_sandbox_config_snapshot_from_inputs, is_configuration_rejection, - load_sandbox_config_inputs, require_policy_capabilities, unadmitted_sandbox_config, + load_sandbox_config_inputs, reject_unsupported_endpoint_transport, require_policy_capabilities, + unadmitted_sandbox_config, }; use crate::supervisor_owner::{OWNER_TTL, SupervisorOwnerIndex, dialable_peer_endpoint}; @@ -443,23 +444,31 @@ async fn build_sandbox_config( Ok::<_, Status>((inputs, snapshot)) } .await; - let rejected = |error: Status| BuiltSandboxConfig::Rejected { - sandbox_config: unadmitted_sandbox_config(state, &sandbox, &error), + let rejected = |sandbox_config, error_code| BuiltSandboxConfig::Rejected { + sandbox_config, providers: sandbox .spec .as_ref() .map(|spec| spec.providers.iter().cloned().collect()) .unwrap_or_default(), - error_code: error.code(), + error_code, }; match built { - Ok((inputs, snapshot)) => Ok(Some( - match require_policy_capabilities(supported_capabilities, snapshot.policy.as_ref()) { + Ok((inputs, mut snapshot)) => Ok(Some( + match require_policy_capabilities(&supported_capabilities, snapshot.policy.as_ref()) { Ok(()) => BuiltSandboxConfig::Built(Box::new(inputs), snapshot), - Err(error) => rejected(error), + Err(error) => { + if !reject_unsupported_endpoint_transport(&mut snapshot, &error) { + snapshot = unadmitted_sandbox_config(state, &sandbox, &error); + } + rejected(snapshot, error.code()) + } }, )), - Err(error) if is_configuration_rejection(&error) => Ok(Some(rejected(error))), + Err(error) if is_configuration_rejection(&error) => Ok(Some(rejected( + unadmitted_sandbox_config(state, &sandbox, &error), + error.code(), + ))), Err(error) => Err(error), } } @@ -846,7 +855,7 @@ pub fn register_test_apply_session( sandbox, session_id, captured_seq, - vec![openshell_core::extension_protocol::POLICY_CEDAR_V1.to_string()], + openshell_core::extension_protocol::policy_capabilities(true), ) } diff --git a/crates/openshell-server/src/config_delivery/session.rs b/crates/openshell-server/src/config_delivery/session.rs index 3441fdfac4..3ab9fcd25e 100644 --- a/crates/openshell-server/src/config_delivery/session.rs +++ b/crates/openshell-server/src/config_delivery/session.rs @@ -27,8 +27,8 @@ use super::{DeliveryDisposition, MAX_SUPERVISOR_CONFIG_MESSAGE_BYTES, Supervisor use crate::ServerState; use crate::grpc::policy::{ build_provider_environment_snapshot_from_inputs, build_sandbox_config_snapshot_from_inputs, - is_configuration_rejection, load_sandbox_config_inputs, require_policy_capabilities, - unadmitted_sandbox_config, + is_configuration_rejection, load_sandbox_config_inputs, reject_unsupported_endpoint_transport, + require_policy_capabilities, unadmitted_sandbox_config, }; use crate::persistence::ObjectId; use crate::supervisor_session::{AcceptedSession, SupervisorSessionRegistry}; @@ -899,9 +899,7 @@ pub async fn build_session_bootstrap( /// Build both parts of a session's configuration from one load of their /// inputs. Only a failure to read the stored configuration refuses the -/// session; anything the supervisor can act on is delivered. A Cedar policy -/// a supervisor without Cedar support cannot enforce is delivered not -/// admitted, as an invalid stored configuration is. +/// session. Unsupported and invalid policies are delivered as unadmitted. async fn build_config_bootstrap( state: &Arc, sandbox: &Sandbox, @@ -914,25 +912,27 @@ async fn build_config_bootstrap( Ok::<_, Status>((inputs, sandbox_config)) } .await; - let rejected = |error: Status| { - let sandbox_config = unadmitted_sandbox_config(state, sandbox, &error); - SessionBootstrap { - config: SupervisorConfig { - provider_environment: super::unresolved_provider_environment(&sandbox_config), - sandbox_config, - }, - outcome: BootstrapOutcome::Rejected, - } + let rejected = |sandbox_config| SessionBootstrap { + config: SupervisorConfig { + provider_environment: super::unresolved_provider_environment(&sandbox_config), + sandbox_config, + }, + outcome: BootstrapOutcome::Rejected, }; - let (inputs, sandbox_config) = match built { + let (inputs, mut sandbox_config) = match built { Ok(built) => built, - Err(error) if is_configuration_rejection(&error) => return Ok(rejected(error)), + Err(error) if is_configuration_rejection(&error) => { + return Ok(rejected(unadmitted_sandbox_config(state, sandbox, &error))); + } Err(error) => return Err(error), }; if let Err(error) = - require_policy_capabilities(supported_capabilities, sandbox_config.policy.as_ref()) + require_policy_capabilities(&supported_capabilities, sandbox_config.policy.as_ref()) { - return Ok(rejected(error)); + if !reject_unsupported_endpoint_transport(&mut sandbox_config, &error) { + sandbox_config = unadmitted_sandbox_config(state, sandbox, &error); + } + return Ok(rejected(sandbox_config)); } let provider_environment = tokio::time::timeout( super::PROVIDER_ENVIRONMENT_BUILD_TIMEOUT, @@ -2637,6 +2637,39 @@ BEGIN SELECT RAISE(ABORT, 'database unavailable'); END; assert!(bootstrap.policy.is_some()); } + #[tokio::test] + async fn endpoint_transport_push_bootstrap_requires_a_capable_supervisor() { + let policy = openshell_policy::parse_sandbox_policy( + "version: 1\nnetwork_policies:\n api:\n endpoints:\n - host: api.example.com\n port: 443\n protocol: rest\n access: full\n binaries:\n - path: /usr/bin/curl\n", + ) + .unwrap(); + let sandbox_id = "sb-push-transports"; + let state = push_state_with_policy(sandbox_id, policy.clone()).await; + let capable = accepted_bootstrap(&state, sandbox_id, StreamFeatures::Apply).await; + assert!(capable.configuration_admitted, "{capable:?}"); + assert!(capable.policy.is_some()); + + let state = push_state_with_policy(sandbox_id, policy).await; + let incapable = accepted_bootstrap( + &state, + sandbox_id, + StreamFeatures::ApplyWithoutEndpointTransports, + ) + .await; + assert!(!incapable.configuration_admitted, "{incapable:?}"); + assert!(incapable.policy.is_none()); + assert!( + incapable + .configuration_error + .contains("endpoint transport support") + ); + assert_eq!( + incapable.policy_validation_failure_mode, + openshell_core::PolicyValidationFailureMode::FailClosed.as_str() + ); + assert_eq!(incapable.config_revision, capable.config_revision); + } + #[test] fn unrecorded_policy_loads_keep_success_and_coalesce_newer_results() { let mut pending = UnrecordedPolicyLoads::default(); diff --git a/crates/openshell-server/src/grpc/auth_rpc.rs b/crates/openshell-server/src/grpc/auth_rpc.rs index 1f56bd708b..42b58fcd25 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: openshell_core::extension_protocol::policy_capabilities(true), name: sandbox_record .metadata .as_ref() diff --git a/crates/openshell-server/src/grpc/mod.rs b/crates/openshell-server/src/grpc/mod.rs index 5bfb592196..39d1cbe507 100644 --- a/crates/openshell-server/src/grpc/mod.rs +++ b/crates/openshell-server/src/grpc/mod.rs @@ -1491,6 +1491,8 @@ pub mod test_support { Apply, /// Applies streamed configuration but cannot enforce Cedar policies. ApplyWithoutCedar, + /// Applies streamed configuration but cannot enforce endpoint transports. + ApplyWithoutEndpointTransports, } /// Serve `state` on loopback and open a supervisor stream whose hello @@ -1548,24 +1550,28 @@ pub mod test_support { openshell_core::grpc_client::MAX_SUPERVISOR_STREAM_MESSAGE_BYTES, ); let (outbound, rx) = mpsc::channel(4); + let supported_capabilities = match features { + StreamFeatures::Legacy => Vec::new(), + StreamFeatures::Apply => openshell_core::extension_protocol::policy_capabilities(true), + StreamFeatures::ApplyWithoutCedar => { + openshell_core::extension_protocol::policy_capabilities(false) + } + StreamFeatures::ApplyWithoutEndpointTransports => { + vec![openshell_core::extension_protocol::POLICY_CEDAR_V1.to_string()] + } + }; outbound .send(SupervisorMessage { payload: Some(supervisor_message::Payload::Hello(SupervisorHello { supports_service_advertisements: false, sandbox_id: sandbox_id.into(), instance_id: "instance".into(), - supports_config_push: matches!( - features, - StreamFeatures::Apply | StreamFeatures::ApplyWithoutCedar - ), + supports_config_push: features != StreamFeatures::Legacy, connection_epoch, supports_provider_readiness: false, redirected: false, supports_session_redirect: false, - supported_capabilities: openshell_core::extension_protocol::capabilities_if( - openshell_core::extension_protocol::POLICY_CEDAR_V1, - features == StreamFeatures::Apply, - ), + supported_capabilities, })), }) .await diff --git a/crates/openshell-server/src/grpc/policy.rs b/crates/openshell-server/src/grpc/policy.rs index b9d5fa8fff..c6ecea675e 100644 --- a/crates/openshell-server/src/grpc/policy.rs +++ b/crates/openshell-server/src/grpc/policy.rs @@ -48,9 +48,13 @@ use crate::storage_proto::StoredProviderCredentialRefreshState; #[cfg(test)] use crate::storage_proto::StoredProviderProfile; use metrics::counter; +use openshell_core::extension_protocol::{ + POLICY_CEDAR_V1, POLICY_ENDPOINT_TRANSPORTS_V1, has_capability, policy_capabilities, +}; use openshell_core::net::{is_always_blocked_ip, is_internal_ip}; use openshell_core::policy_identity::canonical_rule_bytes; pub use openshell_core::policy_identity::deterministic_policy_hash; +use openshell_core::policy_l7::{AllowedTransports, endpoint_allowed_transports, selector_ports}; #[cfg(test)] use openshell_core::proto::StaticCredentialBinding; use openshell_core::proto::policy_merge_operation; @@ -2893,35 +2897,106 @@ async fn handle_get_sandbox_config_inner( MinWorkspaceRole::User, ) .await?; - let config = load_sandbox_config(state, &sandbox).await?; - if matches!(principal, Principal::Sandbox(_)) { - require_policy_capabilities(req.supported_capabilities, config.policy.as_ref())?; + let mut snapshot = build_sandbox_config_snapshot(state, &sandbox).await?; + if matches!(principal, Principal::Sandbox(_)) + && let Err(error) = + require_policy_capabilities(&req.supported_capabilities, snapshot.policy.as_ref()) + && !reject_unsupported_endpoint_transport(&mut snapshot, &error) + { + return Err(error); } - Ok(Response::new(config)) + Ok(Response::new(sandbox_config_response(snapshot))) } const CEDAR_SUPPORT_REQUIRED: &str = "Cedar policy requires a supervisor with Cedar support"; +const ENDPOINT_TRANSPORT_SUPPORT_REQUIRED: &str = + "Effective policy requires a supervisor with endpoint transport support"; -/// Refuses a Cedar policy to a supervisor that did not report Cedar support. -/// -/// Callers must not answer with an empty compatibility configuration -/// instead: an older supervisor might treat it as a usable YAML -/// configuration. Pushed configuration delivers the refusal as a -/// configuration that is not admitted. +/// Refuse policies the supervisor cannot enforce. pub fn require_policy_capabilities( - supported_capabilities: Vec, + supported_capabilities: &[String], policy: Option<&ProtoSandboxPolicy>, ) -> Result<(), Status> { - if !openshell_core::extension_protocol::has_capability( - &supported_capabilities, - openshell_core::extension_protocol::POLICY_CEDAR_V1, - ) && policy.is_some_and(ProtoSandboxPolicy::is_cedar) - { + let Some(policy) = policy else { + return Ok(()); + }; + if policy.is_cedar() && !has_capability(supported_capabilities, POLICY_CEDAR_V1) { return Err(Status::unimplemented(CEDAR_SUPPORT_REQUIRED)); } + if !has_capability(supported_capabilities, POLICY_ENDPOINT_TRANSPORTS_V1) + && requires_endpoint_transport_support(policy)? + { + return Err(Status::unimplemented(ENDPOINT_TRANSPORT_SUPPORT_REQUIRED)); + } Ok(()) } +/// A transport refusal is a fail-closed snapshot so polling supervisors apply +/// it to the running proxy. An RPC error leaves their old policy active. +/// Keep the desired generation's identity for configuration admission reports. +pub fn reject_unsupported_endpoint_transport( + snapshot: &mut SandboxConfigSnapshot, + error: &Status, +) -> bool { + if error.code() != Code::Unimplemented || error.message() != ENDPOINT_TRANSPORT_SUPPORT_REQUIRED + { + return false; + } + *snapshot = SandboxConfigSnapshot { + configuration_instance_id: std::mem::take(&mut snapshot.configuration_instance_id), + configuration_error: ENDPOINT_TRANSPORT_SUPPORT_REQUIRED.to_string(), + policy_validation_failure_mode: openshell_core::PolicyValidationFailureMode::FailClosed + .as_str() + .to_string(), + policy_hash: std::mem::take(&mut snapshot.policy_hash), + workspace: std::mem::take(&mut snapshot.workspace), + version: snapshot.version, + config_revision: snapshot.config_revision, + provider_env_revision: snapshot.provider_env_revision, + ..Default::default() + }; + true +} + +fn requires_endpoint_transport_support(policy: &ProtoSandboxPolicy) -> Result { + let endpoint_requires_transport_support = |endpoint: &NetworkEndpoint| { + !endpoint.allowed_transports.is_empty() + || selector_ports(endpoint).iter().any(|&port| { + endpoint_allowed_transports(endpoint, port) == Some(AllowedTransports::Tls) + }) + }; + if policy + .network_policies + .values() + .chain(policy.provider_credential_rules.values()) + .flat_map(|rule| &rule.endpoints) + .chain(&policy.endpoint_settings) + .any(endpoint_requires_transport_support) + { + return Ok(true); + } + #[cfg(feature = "experimental")] + if policy.is_cedar() { + // Cedar derives HTTP inspection from its source, including on a + // provider endpoint whose own protocol need not be HTTP. + let inspections = openshell_policy::cedar_http_endpoint_selectors(policy.cedar_source()) + .map_err(|_| Status::failed_precondition("stored Cedar policy is invalid"))?; + return Ok(inspections.into_iter().any(|(host, port)| { + port == 443 + || policy + .provider_credential_rules + .values() + .flat_map(|rule| &rule.endpoints) + .any(|endpoint| { + openshell_core::policy_l7::endpoint_is_credentialed(endpoint) + && selector_ports(endpoint).contains(&u32::from(port)) + && host_patterns_overlap(&endpoint.host, &host).unwrap_or(false) + }) + })); + } + Ok(false) +} + /// 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( @@ -3083,6 +3158,9 @@ async fn build_sandbox_config_snapshot_with_sources( } if let Err(error) = validate_uninspected_credentialed_endpoints(effective_policy) { configuration_error = bounded_configuration_diagnostic(error.message()); + } else if let Err(error) = validate_endpoint_ambiguities(effective_policy) { + // Credential provenance can change a route's transport default. + configuration_error = bounded_configuration_diagnostic(error.message()); } policy_hash = deterministic_policy_hash(effective_policy); } @@ -5216,9 +5294,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(), - ], + supported_capabilities: policy_capabilities(true), name: sandbox_name.clone(), workspace_scope: Some(openshell_core::proto::workspace_selector(workspace.clone())), }); @@ -5237,9 +5313,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(), - ], + supported_capabilities: policy_capabilities(true), workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), name: sandbox_name, }); @@ -7689,6 +7763,7 @@ fn map_policy_merge_error(error: openshell_policy::PolicyMergeError) -> Status { } openshell_policy::PolicyMergeError::InvalidInputPolicy { .. } | openshell_policy::PolicyMergeError::McpContractConflict { .. } + | openshell_policy::PolicyMergeError::TransportContractConflict { .. } | openshell_policy::PolicyMergeError::NewBinaryWouldInheritAuthorization { .. } | openshell_policy::PolicyMergeError::ExistingBinariesWouldInheritAuthorization { .. @@ -13515,6 +13590,101 @@ mod tests { assert!(legacy_yaml.policy.unwrap().cedar_source().is_empty()); } + #[tokio::test] + async fn endpoint_transport_poll_requires_a_capable_supervisor() { + use openshell_core::proto::{NetworkAccessPreset, NetworkTransport}; + + let state = test_server_state().await; + for (port, explicit, requires_support) in [ + (443, Vec::new(), true), + (8443, vec![NetworkTransport::Plaintext as i32], true), + (8443, Vec::new(), false), + ] { + let mut policy = test_policy_with_rule("base", "api.example.com"); + let endpoint = &mut policy.network_policies.get_mut("base").unwrap().endpoints[0]; + endpoint.protocol = "rest".to_string(); + endpoint.access = NetworkAccessPreset::Full as i32; + endpoint.port = port; + endpoint.allowed_transports = explicit; + state + .store + .put_message(&test_sandbox("sb-transport", "transport", policy, vec![])) + .await + .unwrap(); + + let fetch = |supported_capabilities| { + handle_get_sandbox_config( + &state, + with_sandbox( + Request::new(GetSandboxConfigRequest { + name: "transport".to_string(), + supported_capabilities, + ..Default::default() + }), + "sb-transport", + ), + ) + }; + let current = fetch(policy_capabilities(false)) + .await + .unwrap() + .into_inner(); + assert!(current.configuration_admitted, "{current:?}"); + let legacy = fetch(Vec::new()).await.unwrap().into_inner(); + if requires_support { + assert!(!legacy.configuration_admitted, "{legacy:?}"); + assert!(legacy.policy.is_none(), "{legacy:?}"); + assert_eq!( + legacy.configuration_error, + ENDPOINT_TRANSPORT_SUPPORT_REQUIRED + ); + assert_eq!( + legacy.policy_validation_failure_mode, + openshell_core::PolicyValidationFailureMode::FailClosed.as_str() + ); + assert_eq!(legacy.config_revision, current.config_revision); + } else { + assert_eq!(legacy, current); + } + } + } + + #[cfg(feature = "experimental")] + #[test] + fn cedar_endpoint_transport_detection_uses_derived_inspection() { + for (port, credentialed, requires_support) in + [(443, false, true), (8443, true, true), (8443, false, false)] + { + let mut policy = ProtoSandboxPolicy { + cedar_policy: Some(openshell_core::proto::CedarPolicy { + source: format!( + r#"permit (principal, action == Sandbox::Action::"NetworkConnect", + resource == Sandbox::NetworkEndpoint::"api.example.com:{port}"); +permit (principal, action == Sandbox::Action::"HttpRequest", + resource == Sandbox::NetworkEndpoint::"api.example.com:{port}") +when {{ context.method == "GET" }};"# + ), + }), + ..Default::default() + }; + if credentialed { + let mut provider = test_policy_with_rule("provider", "**.example.com"); + let endpoint = &mut provider + .network_policies + .get_mut("provider") + .unwrap() + .endpoints[0]; + endpoint.port = port; + endpoint.provider_credentialed = true; + policy.provider_credential_rules = provider.network_policies; + } + assert_eq!( + requires_endpoint_transport_support(&policy).unwrap(), + requires_support + ); + } + } + #[cfg(feature = "experimental")] #[tokio::test] async fn sandbox_config_delivers_provider_rules_separately_for_a_cedar_policy() { diff --git a/crates/openshell-server/src/storage_proto.rs b/crates/openshell-server/src/storage_proto.rs index 4c452c7cf3..c58cdc07ff 100644 --- a/crates/openshell-server/src/storage_proto.rs +++ b/crates/openshell-server/src/storage_proto.rs @@ -251,14 +251,16 @@ mod tests { // and the public/durable overlap remain unchanged. // The service backend HTTP version is part of both schemas. Legacy // endpoint records omit it and continue to use HTTP/1.1. + // NetworkEndpoint adds a repeated enum to both schemas. Legacy endpoint + // records decode with an empty list and select the endpoint default. const PUBLIC_RPC_SCHEMA_SHA256: &str = - "edfc80ad192e77e1a9d1e1d6e3342280e4438f8bf7cb49969f580060df9a056a"; + "ae9342a1400d16120c814654f55f5048e0eefac9fdfc28afbd58ac6fc77b4301"; // The storage.v2 refresh root adds retired handles and the first mint's // provider revision. All fields from the prior root retain their wire tags. const DURABLE_SCHEMA_SHA256: &str = - "ca31950286327bc385fae933bbb9e34d3c9191214f9b549c558bba40957fcc65"; + "70b94ef48e2d388afcc609ebc70f934da6d5533bd37a37b436b0d46a3c65bf55"; const PUBLIC_DURABLE_OVERLAP_SHA256: &str = - "d0eead2cd403f6f52ecd9b7df73ca7db15e84dd847e11bc9d50469970204e589"; + "97abfec3c823db17b2904317f7da01c6d68a5db35398f788f2d9460ccdd1673a"; // Encoded with the schema that omitted stable_placeholder. Keep these // bytes fixed so the current encoder cannot hide a compatibility change. const LEGACY_STATIC_PROFILE: &str = "0a240a116c65676163792d70726f66696c652d6964120d6c65676163792d737461746963280712510a0d6c65676163792d73746174696312184c6567616379207374617469632063726564656e7469616c2a260a076170695f6b65791a1153594e5448455449435f4150495f4b455920012a06626561726572"; @@ -817,9 +819,9 @@ mod tests { overlap_hash.as_str(), ), ( - (369, 32), - (104, 23), - (88, 23), + (369, 33), + (104, 24), + (88, 24), PUBLIC_RPC_SCHEMA_SHA256, DURABLE_SCHEMA_SHA256, PUBLIC_DURABLE_OVERLAP_SHA256 @@ -828,6 +830,18 @@ mod tests { ); } + #[test] + fn network_endpoint_without_transport_allowlist_decodes_empty() { + // Encoded using the descriptor before allowed_transports was added. + let bytes = legacy_bytes("0a0f6170692e6578616d706c652e636f6d10bb031a0472657374"); + let endpoint = openshell_core::proto::NetworkEndpoint::decode(bytes.as_slice()).unwrap(); + assert_eq!(endpoint.host, "api.example.com"); + assert_eq!(endpoint.port, 443); + assert_eq!(endpoint.protocol, "rest"); + assert!(endpoint.allowed_transports.is_empty()); + assert_eq!(endpoint.encode_to_vec(), bytes); + } + #[test] fn service_endpoint_without_authorization_mode_decodes_as_strip() { use openshell_core::proto::{ diff --git a/crates/openshell-supervisor-network/data/sandbox-policy.rego b/crates/openshell-supervisor-network/data/sandbox-policy.rego index 91d8e222e7..63ae1bf282 100644 --- a/crates/openshell-supervisor-network/data/sandbox-policy.rego +++ b/crates/openshell-supervisor-network/data/sandbox-policy.rego @@ -1125,3 +1125,7 @@ endpoint_has_extended_config(ep) if { endpoint_has_extended_config(ep) if { ep.tls } + +endpoint_has_extended_config(ep) if { + count(object.get(ep, "allowed_transports", [])) > 0 +} diff --git a/crates/openshell-supervisor-network/src/opa/raw_schema.rs b/crates/openshell-supervisor-network/src/opa/raw_schema.rs index 02ae769034..e42652a219 100644 --- a/crates/openshell-supervisor-network/src/opa/raw_schema.rs +++ b/crates/openshell-supervisor-network/src/opa/raw_schema.rs @@ -8,6 +8,9 @@ //! the original objects retain their extra fields for Rego evaluation. use miette::Result; +use openshell_core::policy_l7::{ + network_tls_mode_from_str, network_transport_from_str, validate_allowed_transports, +}; use openshell_policy_schema::{ JsonRpcConfig, L7Allow, L7DenyRule, McpConfig, NetworkBinary, NetworkEndpoint, NetworkPolicyRule, @@ -54,7 +57,17 @@ fn validate_endpoint(endpoint: &Value) -> Result<()> { // through the canonical config DTOs and owns their diagnostic category. fields.remove("mcp"); fields.remove("json_rpc"); - validate_known::(fields, diagnostic)?; + let config = deserialize_known::(fields, diagnostic)?; + let transports: Option> = config + .allowed_transports + .iter() + .map(|label| network_transport_from_str(label).map(|transport| transport as i32)) + .collect(); + let transports = transports.ok_or_else(|| miette::miette!(diagnostic))?; + let tls = network_tls_mode_from_str(&config.tls).map_or(-1, |mode| mode as i32); + if validate_allowed_transports(&transports, &config.protocol, tls).is_some() { + return Err(miette::miette!(diagnostic)); + } validate_renamed::( endpoint, @@ -168,8 +181,14 @@ fn validate_known( fields: Map, diagnostic: &'static str, ) -> Result<()> { + deserialize_known::(fields, diagnostic).map(|_| ()) +} + +fn deserialize_known( + fields: Map, + diagnostic: &'static str, +) -> Result { T::deserialize(KnownFields(Value::Object(fields))) - .map(|_| ()) // Serde errors include authored values and keys. Do not retain their // Display, Debug, or source chain at the policy loading boundary. .map_err(|_| miette::miette!(diagnostic)) diff --git a/crates/openshell-supervisor-network/src/policy_local.rs b/crates/openshell-supervisor-network/src/policy_local.rs index bdf8898986..790ab9d1be 100644 --- a/crates/openshell-supervisor-network/src/policy_local.rs +++ b/crates/openshell-supervisor-network/src/policy_local.rs @@ -1311,6 +1311,7 @@ fn network_endpoint_from_json( protocol: endpoint.protocol, tls: openshell_policy::network_tls_mode_from_str(&endpoint.tls) .ok_or_else(|| format!("unknown tls value '{}'", endpoint.tls))? as i32, + allowed_transports: Vec::new(), enforcement: openshell_policy::network_enforcement_mode_from_str(&endpoint.enforcement) .ok_or_else(|| format!("unknown enforcement value '{}'", endpoint.enforcement))? as i32, diff --git a/crates/openshell-supervisor-network/src/proxy.rs b/crates/openshell-supervisor-network/src/proxy.rs index 5226f66d2c..25240aa37b 100644 --- a/crates/openshell-supervisor-network/src/proxy.rs +++ b/crates/openshell-supervisor-network/src/proxy.rs @@ -10,6 +10,8 @@ mod relay; pub(crate) use relay::relay_inspected_http_stream_for_test; #[cfg(test)] mod trace_tests; +#[cfg(test)] +mod transport_tests; #[cfg(test)] use openshell_sandbox_backend::test_support as rpc_test; @@ -42,6 +44,7 @@ use openshell_core::net::{ set_tcp_nodelay_best_effort, }; use openshell_core::policy::ProxyPolicy; +use openshell_core::policy_l7::AllowedTransports; use openshell_core::provider_credentials::ProviderCredentialState; use openshell_core::secrets::{self, SecretResolver, rewrite_header_line_checked}; #[cfg(any(test, feature = "test-support"))] @@ -171,10 +174,6 @@ const TUNNEL_PROTOCOL_PEEK_BYTES: usize = crate::l7::rest::HTTP2_PRIOR_KNOWLEDGE const TUNNEL_PROTOCOL_PEEK_TIMEOUT: std::time::Duration = std::time::Duration::from_millis(100); #[cfg(test)] const TUNNEL_PROTOCOL_PEEK_TIMEOUT: std::time::Duration = std::time::Duration::from_millis(10); -#[cfg(not(test))] -const TUNNEL_PROTOCOL_PEEK_POLL: std::time::Duration = std::time::Duration::from_millis(5); -#[cfg(test)] -const TUNNEL_PROTOCOL_PEEK_POLL: std::time::Duration = std::time::Duration::from_millis(1); const FORWARD_ENCODED_SLASH_REJECTION_DETAIL: &str = "request-target contains an encoded '/' (%2F) which is not allowed on this endpoint"; @@ -1472,6 +1471,16 @@ async fn handle_transparent_tcp_connection( return Ok(()); } + if query_allowed_transports(&decision)?.is_some() { + emit_transport_denial( + &decision, + workload_addr, + "Inspected transport is unavailable on the raw transparent TCP adapter", + ); + emit_activity(&activity_tx, true, "transport_not_allowed"); + return Ok(()); + } + if mapping.record.is_observation() { emit_transparent_mapping_denial( workload_addr, @@ -2055,31 +2064,94 @@ fn middleware_uninspectable_gate( Ok(crate::l7::middleware::uninspectable_traffic_gate(&chain)) } -async fn peek_tunnel_protocol(client: &mut C) -> Result> +/// Read far enough to classify a fragmented prefix. Bytes consumed while +/// waiting for the next fragment must be replayed into the selected relay. +async fn peek_tunnel_protocol(client: &mut C) -> Result)>> where C: tokio::io::AsyncBufRead + Unpin, { - let deadline = tokio::time::Instant::now() + TUNNEL_PROTOCOL_PEEK_TIMEOUT; + let available = client.fill_buf().await.into_diagnostic()?; + if available.is_empty() { + return Ok(None); + } + let peek = &available[..available.len().min(TUNNEL_PROTOCOL_PEEK_BYTES)]; + let protocol = classify_tunnel_protocol(peek); + if protocol != TunnelProtocol::Unsupported || !could_be_supported_tunnel_protocol_prefix(peek) { + return Ok(Some((protocol, Vec::new()))); + } - loop { - let available = client.fill_buf().await.into_diagnostic()?; + let mut prefix = peek.to_vec(); + client.consume(prefix.len()); + let deadline = tokio::time::Instant::now() + TUNNEL_PROTOCOL_PEEK_TIMEOUT; + while prefix.len() < TUNNEL_PROTOCOL_PEEK_BYTES { + let Ok(read) = tokio::time::timeout_at(deadline, client.fill_buf()).await else { + break; + }; + let available = read.into_diagnostic()?; if available.is_empty() { - return Ok(None); + break; } - - let n = available.len().min(TUNNEL_PROTOCOL_PEEK_BYTES); - let peek = &available[..n]; - let protocol = classify_tunnel_protocol(peek); + let n = available + .len() + .min(TUNNEL_PROTOCOL_PEEK_BYTES - prefix.len()); + prefix.extend_from_slice(&available[..n]); + client.consume(n); + let protocol = classify_tunnel_protocol(&prefix); if protocol != TunnelProtocol::Unsupported - || !could_be_supported_tunnel_protocol_prefix(peek) - || n == TUNNEL_PROTOCOL_PEEK_BYTES - || tokio::time::Instant::now() >= deadline + || !could_be_supported_tunnel_protocol_prefix(&prefix) { - return Ok(Some(protocol)); + return Ok(Some((protocol, prefix))); } + } + Ok(Some((TunnelProtocol::Unsupported, prefix))) +} - tokio::time::sleep(TUNNEL_PROTOCOL_PEEK_POLL).await; +fn replay_tunnel_prefix(client: ProxyClient, prefix: Vec) -> ProxyClient { + if prefix.is_empty() { + return client; } + let (read, write) = tokio::io::split(client); + let prefixed = std::io::Cursor::new(prefix).chain(read); + tokio::io::BufReader::new(Box::new(tokio::io::join(prefixed, write))) +} + +fn transport_rejection( + transports: AllowedTransports, + protocol: TunnelProtocol, +) -> Option<&'static str> { + match (transports, protocol) { + (AllowedTransports::Tls, TunnelProtocol::Tls) + | (AllowedTransports::Plaintext, TunnelProtocol::Http1) + | (AllowedTransports::Both, TunnelProtocol::Tls | TunnelProtocol::Http1) => None, + (AllowedTransports::Both, _) => Some("Endpoint requires inspected TLS or plaintext HTTP"), + (AllowedTransports::Tls, _) => Some("Endpoint requires inspected TLS"), + (AllowedTransports::Plaintext, _) => Some("Endpoint requires inspected plaintext HTTP"), + } +} + +fn emit_transport_denial(decision: &EgressDecision, workload: SocketAddr, detail: &str) { + let policy_name = match &decision.action { + NetworkAction::Allow { matched_policy } => matched_policy.as_deref().unwrap_or("-"), + NetworkAction::Deny { .. } => "-", + }; + let destination = &decision.intent.destination; + let event = NetworkActivityBuilder::new(openshell_ocsf::ctx::ctx()) + .activity(ActivityId::Open) + .action(ActionId::Denied) + .disposition(DispositionId::Blocked) + .severity(SeverityId::Medium) + .status(StatusId::Failure) + .dst_endpoint(Endpoint::from_domain(&destination.host, destination.port)) + .src_endpoint_addr(workload.ip(), workload.port()) + .actor_process(decision.actor_process()) + .firewall_rule(policy_name, "transport") + .message(format!( + "Transport denied for {}:{}", + destination.host, destination.port + )) + .status_detail(detail) + .build(); + egress_emit!(event); } fn emit_connect_activity_if_l4_only( @@ -3147,14 +3219,16 @@ async fn handle_mediated_connection( // allowed_ips validation below — so an internal-address CONNECT still gets // the SSRF 403 and telemetry in degraded state — but before the upstream // connect and before `200 Connection Established`. + let allowed_transports = query_allowed_transports(&decision)?; hydrate_tls_mode(&mut decision); - let effective_tls_skip = decision.endpoint.tls_mode == crate::l7::TlsMode::Skip; + let effective_tls_skip = + allowed_transports.is_none() && decision.endpoint.tls_mode == crate::l7::TlsMode::Skip; let credential_guard = query_endpoint_credential_guard(&network_engine, &decision, &host_lc, port)?; // Route materialization is safe before destination dialing and lets an // unambiguous MCP authority report local fail-closed outcomes that occur // before the HTTP request path becomes available. - hydrate_l7_route(&mut decision); + hydrate_l7_route(&mut decision, allowed_transports.is_some()); let connect_endpoint_observer = begin_unambiguous_endpoint_observation( decision.endpoint.l7_route.as_ref(), endpoint_observation_tx.as_ref(), @@ -3255,8 +3329,17 @@ async fn handle_mediated_connection( // the first bytes on the socket rather than a post-200 in-tunnel write the // client would misread as a TLS error. No "allowed CONNECT" event is emitted // for this path — that log lives after the `200` below. - if refuse_connect_when_tls_unavailable(&mut client, tls_state.is_some(), effective_tls_skip) - .await? + // When plaintext is permitted, wait for the client to select a transport. + // A missing TLS context still blocks TLS before we connect to the origin. + if !matches!( + allowed_transports, + Some(AllowedTransports::Plaintext | AllowedTransports::Both) + ) && refuse_connect_when_tls_unavailable( + &mut client, + tls_state.is_some(), + effective_tls_skip, + ) + .await? { if let Some(observer) = connect_endpoint_observer.as_ref() { observer.observe(EndpointResult::TlsFailed); @@ -3349,6 +3432,12 @@ async fn handle_mediated_connection( return Ok(()); } + let should_inspect_l7 = l7_inspection_active(l7_route); + if allowed_transports.is_some() && !should_inspect_l7 { + return Err(miette::miette!( + "inspected transport has no usable HTTP relay" + )); + } // Build request-processing context shared by CONNECT and forward HTTP. let mut ctx = relay::http_context( &decision, @@ -3392,28 +3481,70 @@ async fn handle_mediated_connection( } } + let mut pre_dial_protocol = None; + if let Some(transports) = allowed_transports { + // Clients send the tunnel payload only after this acknowledgement. + // Classify before dialing so a transport refusal cannot reach the origin. + respond(&mut client, b"HTTP/1.1 200 Connection Established\r\n\r\n").await?; + let peeked = tokio::select! { + peeked = peek_tunnel_protocol(&mut client) => peeked?, + () = connect_generation_guard.wait_until_stale() => None, + }; + let Some((protocol, prefix)) = peeked else { + return Ok(()); + }; + let rejection = transport_rejection(transports, protocol).or_else(|| { + (protocol == TunnelProtocol::Tls && tls_state.is_none()) + .then_some(TLS_TERMINATION_UNAVAILABLE_DETAIL) + }); + if let Some(detail) = rejection { + if let Some(observer) = connect_endpoint_observer.as_ref() { + observer.observe(EndpointResult::PolicyDenied); + } + emit_transport_denial(&decision, workload_addr, detail); + emit_activity_simple(activity_tx.as_ref(), true, "transport_not_allowed"); + if protocol == TunnelProtocol::Http1 { + respond( + &mut client, + &build_json_error_response(403, "Forbidden", "transport_not_allowed", detail), + ) + .await?; + } + return Ok(()); + } + client = replay_tunnel_prefix(client, prefix); + pre_dial_protocol = Some(protocol); + } + let dial_span = egress::dial_span(&connect_span); let upstream_result = tokio::select! { result = dial_upstream(&upstream_proxy, &host_lc, &raw_host_lc, port, connector.addrs()) .instrument(dial_span.clone()) => Some(result), () = connect_generation_guard.wait_until_stale() => None, }; - let Some(upstream_result) = upstream_result else { - reject_stale_connect_policy( - &mut client, - &host_lc, - port, - activity_tx.as_ref(), - miette::miette!( - "policy changed while CONNECT was dialing upstream \ - [captured_generation:{} current_generation:{}]", - connect_generation_guard.captured_generation(), - connect_generation_guard.current_generation(), - ), - ) - .await?; - return Ok(()); + let stale_error = if upstream_result.is_some() { + connect_generation_guard.ensure_current().err() + } else { + Some(miette::miette!( + "policy changed while CONNECT was dialing upstream \ + [captured_generation:{} current_generation:{}]", + connect_generation_guard.captured_generation(), + connect_generation_guard.current_generation(), + )) }; + if let Some(error) = stale_error { + if pre_dial_protocol.is_some() { + // The tunnel is established, so close it without sending an HTTP + // response into a possibly TLS-speaking stream. + emit_l7_tunnel_close_after_policy_change(&host_lc, port, error); + emit_activity_simple(activity_tx.as_ref(), true, "policy_stale"); + } else { + reject_stale_connect_policy(&mut client, &host_lc, port, activity_tx.as_ref(), error) + .await?; + } + return Ok(()); + } + let upstream_result = upstream_result.expect("missing dial result implies stale policy"); let mut upstream = match upstream_result { Ok(upstream) => upstream, Err(error) => { @@ -3424,18 +3555,12 @@ async fn handle_mediated_connection( return Err(error).into_diagnostic(); } }; - if let Err(error) = connect_generation_guard.ensure_current() { - reject_stale_connect_policy(&mut client, &host_lc, port, activity_tx.as_ref(), error) - .await?; - return Ok(()); - } - drop(dial_span); drop(connect_span); - respond(&mut client, b"HTTP/1.1 200 Connection Established\r\n\r\n").await?; - - let should_inspect_l7 = l7_inspection_active(l7_route); + if pre_dial_protocol.is_none() { + respond(&mut client, b"HTTP/1.1 200 Connection Established\r\n\r\n").await?; + } // Log the allowed CONNECT — use CONNECT_L7 when L7 inspection follows, // so log consumers can distinguish L4-only decisions from tunnel lifecycle events. @@ -3471,8 +3596,14 @@ async fn handle_mediated_connection( // Auto-detect the tunnel payload. L7-configured endpoints must only // enter relays that can enforce their configured protocol; unsupported // bytes fail closed below instead of falling through to raw relay. - let Some(tunnel_protocol) = peek_tunnel_protocol(&mut client).await? else { - return Ok(()); + let tunnel_protocol = if let Some(protocol) = pre_dial_protocol { + protocol + } else { + let Some((protocol, prefix)) = peek_tunnel_protocol(&mut client).await? else { + return Ok(()); + }; + client = replay_tunnel_prefix(client, prefix); + protocol }; if tunnel_protocol == TunnelProtocol::Tls { @@ -4294,10 +4425,43 @@ where /// /// Returns `Some(L7EndpointConfig)` if the matched endpoint has L7 config (protocol field), /// `None` for L4-only endpoints. -fn hydrate_l7_route(decision: &mut EgressDecision) { +fn hydrate_l7_route(decision: &mut EgressDecision, http_transport: bool) { let host = decision.intent.destination.host.clone(); let port = decision.intent.destination.port; - decision.endpoint.l7_route = query_l7_route_snapshot(decision, &host, port); + let mut route = query_l7_route_snapshot(decision, &host, port); + if http_transport && let Some(route) = route.as_mut() { + // The legacy SQL adapter can copy opaque bytes. It must not become + // the relay for a connection with an inspected HTTP transport policy. + route + .configs + .retain(|snapshot| snapshot.config.protocol != crate::l7::L7Protocol::Sql); + } + decision.endpoint.l7_route = route; +} + +/// A connection picks a transport before its HTTP path is known. Read all +/// inspected configs from the captured authorization, without letting a bare +/// L4 sibling hide the transport policy. +fn query_allowed_transports(decision: &EgressDecision) -> Result> { + let mut effective = None; + let port = decision.intent.destination.port; + for config in &decision.endpoint.policy_configs { + let Some(allowed) = config + .allowed_transports_for_port(port) + .map_err(|reason| miette::miette!("{reason}"))? + else { + continue; + }; + if effective + .replace(allowed) + .is_some_and(|previous| previous != allowed) + { + return Err(miette::miette!( + "matched endpoints disagree on allowed_transports" + )); + } + } + Ok(effective) } fn hydrate_tls_mode(decision: &mut EgressDecision) { @@ -6074,7 +6238,25 @@ async fn handle_forward_proxy_inner( // connection, so a single evaluation suffices. The shared HTTP relay // strips hop-by-hop `Connection` headers and drops the upstream after // the response instead of asking the upstream to close it. - hydrate_l7_route(&mut decision); + let allowed_transports = query_allowed_transports(&decision)?; + hydrate_l7_route(&mut decision, allowed_transports.is_some()); + if let Some(transports) = allowed_transports { + if let Some(detail) = transport_rejection(transports, TunnelProtocol::Http1) { + emit_transport_denial(&decision, workload_addr, detail); + emit_activity_simple(activity_tx, true, "transport_not_allowed"); + respond( + client, + &build_json_error_response(403, "Forbidden", "transport_not_allowed", detail), + ) + .await?; + return Ok(()); + } + if !l7_inspection_active(decision.endpoint.l7_route.as_ref()) { + return Err(miette::miette!( + "inspected transport has no usable HTTP relay" + )); + } + } let canonicalize_options = crate::l7::path::CanonicalizeOptions { allow_encoded_slash: decision.endpoint.l7_route.as_ref().is_some_and(|route| { route @@ -7965,7 +8147,7 @@ process: ); assert_eq!(query_allowed_ips(&decision), ["192.0.2.0/24"]); - hydrate_l7_route(&mut decision); + hydrate_l7_route(&mut decision, false); let route = decision .endpoint .l7_route @@ -13641,6 +13823,28 @@ network_policies: assert!(!could_be_supported_tunnel_protocol_prefix(b"SSH")); } + #[tokio::test] + async fn fragmented_tunnel_prefix_is_replayed_to_the_relay() { + let (mut sender, stream) = tokio::io::duplex(128); + let mut client: ProxyClient = tokio::io::BufReader::new(Box::new(stream)); + sender.write_all(b"GE").await.unwrap(); + + let mut classification = Box::pin(peek_tunnel_protocol(&mut client)); + assert!(futures::poll!(classification.as_mut()).is_pending()); + sender + .write_all(b"T /status HTTP/1.1\r\n\r\n") + .await + .unwrap(); + sender.shutdown().await.unwrap(); + let (protocol, prefix) = classification.await.unwrap().unwrap(); + assert_eq!(protocol, TunnelProtocol::Http1); + + let mut client = replay_tunnel_prefix(client, prefix); + let mut replayed = Vec::new(); + client.read_to_end(&mut replayed).await.unwrap(); + assert_eq!(replayed, b"GET /status HTTP/1.1\r\n\r\n"); + } + #[tokio::test] async fn h2c_prior_knowledge_is_blocked_for_l7_tunnel() { use crate::l7::middleware::UninspectableTrafficGate; @@ -13655,7 +13859,7 @@ network_policies: .await .unwrap(); - let protocol = peek_tunnel_protocol(&mut tokio::io::BufReader::new(&mut server)) + let (protocol, _) = peek_tunnel_protocol(&mut tokio::io::BufReader::new(&mut server)) .await .expect("peek should succeed") .expect("client sent bytes"); diff --git a/crates/openshell-supervisor-network/src/proxy/transport_tests.rs b/crates/openshell-supervisor-network/src/proxy/transport_tests.rs new file mode 100644 index 0000000000..8d3b4483ed --- /dev/null +++ b/crates/openshell-supervisor-network/src/proxy/transport_tests.rs @@ -0,0 +1,371 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +use super::*; +use crate::l7::tls::{self, CertCache, SandboxCa}; +use crate::opa::OpaEngine; +use crate::test_support::{executable_path, policy_with_native_executable_paths}; +use openshell_core::proposals::AgentProposals; +use rustls::ClientConfig; +use rustls::pki_types::{CertificateDer, ServerName, pem::PemObject as _}; +use std::time::Duration; +use tokio_rustls::TlsConnector; + +const HOST: &str = "host.openshell.internal"; +const LOOPBACK: &str = "127.0.0.1:0"; +const DEADLINE: Duration = Duration::from_secs(10); +const TLS_ONLY: &str = " allowed_transports: [tls]\n"; +const PLAINTEXT_ONLY: &str = " allowed_transports: [plaintext]\n"; +const BOTH_TRANSPORTS: &str = " allowed_transports: [tls, plaintext]\n"; +const CREDENTIALED: &str = " provider_credentialed: true\n"; +const ORIGIN_RESPONSE: &[u8] = + b"HTTP/1.1 200 OK\r\nContent-Length: 9\r\nConnection: close\r\n\r\norigin-ok"; + +async fn proxy_connection( + port: u16, + endpoint_fields: &str, + tls_state: Option>, + upstream_proxy: Option, +) -> (TcpStream, JoinHandle>) { + let policy = policy_with_native_executable_paths(&format!( + r#" +network_policies: + api: + name: api + endpoints: + - host: {HOST} + port: {port} + protocol: rest + enforcement: enforce +{endpoint_fields} rules: + - allow: {{ method: GET, path: /status }} + binaries: + - path: /usr/bin/test-client +"#, + )); + let engine = Arc::new( + OpaEngine::from_strings(include_str!("../../data/sandbox-policy.rego"), &policy) + .expect("load transport policy"), + ); + let identity = ContractBinaryIdentity { + executable: ContractExecutableIdentity { + path: executable_path("/usr/bin/test-client"), + digest: Some("00".repeat(32).parse().unwrap()), + }, + ancestors: Vec::new(), + cmdline_paths: Vec::new(), + process: None, + }; + let listener = TcpListener::bind(LOOPBACK).await.unwrap(); + let client = connect_tcp_nodelay_best_effort(listener.local_addr().unwrap()) + .await + .unwrap(); + let (server, peer) = listener.accept().await.unwrap(); + let addresses = Some((peer, server.local_addr().unwrap())); + let task = tokio::spawn(Box::pin(handle_mediated_connection( + tokio::io::BufReader::new(Box::new(server)), + Some(Ok(identity)), + addresses, + None, // transparent_open + None, // policy_dns + engine.into(), + Arc::new(BinaryIdentityCache::new()), + Arc::new(AtomicU32::new(0)), + tls_state, + None, // policy_local_ctx + AgentProposals::default(), + Arc::new(Some("127.0.0.1".parse().unwrap())), // backend-pinned gateway + Arc::new(None), // trusted_host_gateway + Arc::new(upstream_proxy), + None, // provider_credentials + None, // secret_resolver + None, // denial_tx + None, // activity_tx + None, // endpoint_observation_tx + None, // required_proxy_authorization + ))); + (client, task) +} + +async fn read_headers(stream: &mut (impl TokioAsyncRead + Unpin)) -> Vec { + let mut headers = Vec::new(); + while !headers.ends_with(b"\r\n\r\n") { + headers.push(stream.read_u8().await.expect("complete HTTP headers")); + } + headers +} + +async fn start_connect(client: &mut TcpStream, port: u16) { + let authority = format!("{HOST}:{port}"); + let request = format!("CONNECT {authority} HTTP/1.1\r\nHost: {authority}\r\n\r\n"); + client.write_all(request.as_bytes()).await.unwrap(); + let response = read_headers(client).await; + assert!( + response.starts_with(b"HTTP/1.1 200 Connection Established\r\n"), + "{}", + String::from_utf8_lossy(&response) + ); +} + +fn request(port: u16, absolute_form: bool) -> Vec { + let target = if absolute_form { + format!("http://{HOST}:{port}/status") + } else { + "/status".to_string() + }; + format!("GET {target} HTTP/1.1\r\nHost: {HOST}:{port}\r\nConnection: close\r\n\r\n") + .into_bytes() +} + +async fn respond_from_origin(mut stream: impl TokioAsyncRead + TokioAsyncWrite + Unpin) { + let headers = read_headers(&mut stream).await; + assert!(headers.starts_with(b"GET /status HTTP/1.1\r\n")); + stream.write_all(ORIGIN_RESPONSE).await.unwrap(); + stream.shutdown().await.unwrap(); +} + +fn assert_origin_response(response: &[u8]) { + let response = String::from_utf8_lossy(response); + assert!(response.starts_with("HTTP/1.1 200 OK\r\n"), "{response}"); + assert!(response.ends_with("\r\n\r\norigin-ok"), "{response}"); +} + +fn assert_transport_denial(response: &[u8]) { + let response = String::from_utf8_lossy(response); + assert!( + response.starts_with("HTTP/1.1 403 Forbidden\r\n"), + "{response}" + ); + let (_, body) = response.split_once("\r\n\r\n").unwrap(); + let body: serde_json::Value = serde_json::from_str(body).unwrap(); + assert_eq!(body["error"], "transport_not_allowed"); +} + +// The upstream proxy fixture makes logical port 443 testable without a +// privileged listener. It also supplies the actual origin on the tunnel. +async fn upstream_listener() -> (TcpListener, UpstreamProxyConfig) { + let listener = TcpListener::bind(LOOPBACK).await.unwrap(); + let upstream = UpstreamProxyConfig::from_args(&upstream_proxy::UpstreamProxyArgs { + https_proxy: Some(format!("http://{}", listener.local_addr().unwrap())), + ..Default::default() + }) + .unwrap() + .unwrap(); + (listener, upstream) +} + +async fn accept_origin(listener: &TcpListener, port: u16) -> TcpStream { + let (mut socket, _) = listener.accept().await.unwrap(); + let headers = read_headers(&mut socket).await; + assert!(headers.starts_with(format!("CONNECT 127.0.0.1:{port} HTTP/1.1\r\n").as_bytes())); + socket + .write_all(b"HTTP/1.1 200 Connection Established\r\n\r\n") + .await + .unwrap(); + socket +} + +async fn assert_no_origin_connection(listener: &TcpListener) { + assert!( + tokio::time::timeout(Duration::from_millis(50), listener.accept()) + .await + .is_err(), + "the transport denial opened an origin connection" + ); +} + +fn trust_ca(ca: &SandboxCa) -> Arc { + let mut roots = rustls::RootCertStore::empty(); + roots + .add(CertificateDer::from_pem_slice(ca.cert_pem().as_bytes()).unwrap()) + .unwrap(); + Arc::new( + openshell_crypto::tls::client_builder() + .with_root_certificates(roots) + .with_no_client_auth(), + ) +} + +#[tokio::test] +async fn connect_enforces_plaintext_transport_before_sending_application_bytes() { + for (port, endpoint_fields, allowed) in [ + (443, "", false), + (443, TLS_ONLY, false), + (8443, CREDENTIALED, false), + (443, PLAINTEXT_ONLY, true), + (443, BOTH_TRANSPORTS, true), + ] { + tokio::time::timeout(DEADLINE, async { + let (listener, upstream) = upstream_listener().await; + // Plaintext is usable without a TLS context, including on mixed endpoints. + let tls = (!allowed).then(|| { + let ca = SandboxCa::generate().unwrap(); + let roots = trust_ca(&ca); + Arc::new(ProxyTlsState::new(CertCache::new(ca), roots)) + }); + let (mut client, proxy) = + proxy_connection(port, endpoint_fields, tls, Some(upstream)).await; + let listener = Arc::new(listener); + let origin = allowed.then(|| { + let listener = Arc::clone(&listener); + tokio::spawn(async move { + respond_from_origin(accept_origin(&listener, port).await).await; + }) + }); + + start_connect(&mut client, port).await; + client.write_all(&request(port, false)).await.unwrap(); + let mut response = Vec::new(); + client.read_to_end(&mut response).await.unwrap(); + if allowed { + assert_origin_response(&response); + } else { + assert_transport_denial(&response); + } + proxy.await.unwrap().unwrap(); + if let Some(origin) = origin { + origin.await.unwrap(); + } else { + assert_no_origin_connection(&listener).await; + } + }) + .await + .unwrap_or_else(|_| { + panic!("plaintext CONNECT timed out for {port} with {endpoint_fields:?}") + }); + } +} + +#[tokio::test] +async fn tls_connect_requires_an_allowed_transport_and_a_trusted_origin() { + for (endpoint_fields, origin_name, trusted) in [ + ("", HOST, true), + (TLS_ONLY, HOST, true), + (BOTH_TRANSPORTS, HOST, true), + (TLS_ONLY, "wrong.example.test", true), + (TLS_ONLY, HOST, false), + (PLAINTEXT_ONLY, HOST, true), + ] { + tokio::time::timeout(DEADLINE, async { + let port = 443; + let plaintext_only = endpoint_fields == PLAINTEXT_ONLY; + let origin_verified = trusted && origin_name == HOST; + let (listener, upstream) = upstream_listener().await; + let proxy_ca = SandboxCa::generate().unwrap(); + let client_roots = trust_ca(&proxy_ca); + let origin_ca = SandboxCa::generate().unwrap(); + let origin_roots = if trusted { + trust_ca(&origin_ca) + } else { + Arc::clone(&client_roots) + }; + let origin_tls = + ProxyTlsState::new(CertCache::new(origin_ca), Arc::clone(&origin_roots)); + let proxy_tls = Arc::new(ProxyTlsState::new(CertCache::new(proxy_ca), origin_roots)); + let (mut client, proxy) = + proxy_connection(port, endpoint_fields, Some(proxy_tls), Some(upstream)).await; + let listener = Arc::new(listener); + let origin = (!plaintext_only).then(|| { + let listener = Arc::clone(&listener); + tokio::spawn(async move { + let socket = accept_origin(&listener, port).await; + let tls = tls::tls_terminate_client(socket, &origin_tls, origin_name).await; + if origin_verified { + respond_from_origin(tls.expect("verified origin TLS handshake")).await; + } else { + assert!(tls.is_err(), "unverified origin completed a TLS handshake"); + } + }) + }); + + start_connect(&mut client, port).await; + let downstream_tls = TlsConnector::from(client_roots) + .connect(ServerName::try_from(HOST).unwrap(), client) + .await; + if plaintext_only { + assert!( + downstream_tls.is_err(), + "plaintext-only policy accepted TLS" + ); + } else { + let mut downstream_tls = downstream_tls.expect("sandbox TLS handshake"); + let write = downstream_tls.write_all(&request(port, false)).await; + if origin_verified { + write.unwrap(); + let mut response = read_headers(&mut downstream_tls).await; + let mut body = [0; 9]; + downstream_tls.read_exact(&mut body).await.unwrap(); + response.extend_from_slice(&body); + assert_origin_response(&response); + } else { + let mut response = Vec::new(); + let _ = downstream_tls.read_to_end(&mut response).await; + assert!(response.is_empty(), "unverified origin returned a response"); + } + } + let result = proxy.await.unwrap(); + if plaintext_only || origin_verified { + result.unwrap(); + } else { + assert!( + result.is_err(), + "proxy accepted an invalid origin certificate" + ); + } + if let Some(origin) = origin { + origin.await.unwrap(); + } else { + assert_no_origin_connection(&listener).await; + } + }) + .await + .unwrap_or_else(|_| { + panic!("TLS CONNECT timed out with {endpoint_fields:?} and {origin_name}") + }); + } +} + +#[tokio::test] +async fn absolute_form_http_enforces_the_same_transport_policy() { + for (endpoint_fields, allowed) in [ + (TLS_ONLY, false), + (CREDENTIALED, false), + (PLAINTEXT_ONLY, true), + ] { + tokio::time::timeout(DEADLINE, async { + let listener = TcpListener::bind(LOOPBACK).await.unwrap(); + let port = listener.local_addr().unwrap().port(); + let (mut client, proxy) = proxy_connection(port, endpoint_fields, None, None).await; + client.write_all(&request(port, true)).await.unwrap(); + let mut response = Vec::new(); + if allowed { + let (origin, _) = listener.accept().await.unwrap(); + respond_from_origin(origin).await; + client.read_to_end(&mut response).await.unwrap(); + assert_origin_response(&response); + } else { + client.read_to_end(&mut response).await.unwrap(); + assert_transport_denial(&response); + assert_no_origin_connection(&listener).await; + } + proxy.await.unwrap().unwrap(); + }) + .await + .unwrap_or_else(|_| panic!("absolute-form HTTP timed out with {endpoint_fields:?}")); + } +} + +#[tokio::test] +async fn mixed_transports_never_fall_back_to_an_opaque_tunnel() { + let (listener, upstream) = upstream_listener().await; + let (mut client, proxy) = proxy_connection(443, BOTH_TRANSPORTS, None, Some(upstream)).await; + start_connect(&mut client, 443).await; + client.write_all(b"SSH-2.0-test\r\n").await.unwrap(); + client.shutdown().await.unwrap(); + tokio::time::timeout(DEADLINE, proxy) + .await + .unwrap() + .unwrap() + .unwrap(); + assert_no_origin_connection(&listener).await; +} diff --git a/crates/openshell-supervisor/src/lib.rs b/crates/openshell-supervisor/src/lib.rs index 6278307846..7d6087724d 100644 --- a/crates/openshell-supervisor/src/lib.rs +++ b/crates/openshell-supervisor/src/lib.rs @@ -2241,10 +2241,7 @@ async fn flush_activity_to_gateway( /// Versioned policy capabilities compiled into this supervisor. fn supported_policy_capabilities() -> Vec { - openshell_core::extension_protocol::capabilities_if( - openshell_core::extension_protocol::POLICY_CEDAR_V1, - cfg!(feature = "experimental"), - ) + openshell_core::extension_protocol::policy_capabilities(cfg!(feature = "experimental")) } /// Minimum read-only paths required for a proxy-mode sandbox child process to diff --git a/crates/openshell-supervisor/src/main.rs b/crates/openshell-supervisor/src/main.rs index b455799f1e..0de254563e 100644 --- a/crates/openshell-supervisor/src/main.rs +++ b/crates/openshell-supervisor/src/main.rs @@ -508,10 +508,9 @@ fn main() -> Result<()> { openshell_crypto::tls::ensure_default_provider(); let exit = openshell_supervisor_process::debug_rpc::run( &raw_args[2..], - openshell_core::extension_protocol::capabilities_if( - openshell_core::extension_protocol::POLICY_CEDAR_V1, - cfg!(feature = "experimental"), - ), + openshell_core::extension_protocol::policy_capabilities(cfg!( + feature = "experimental" + )), ) .await?; std::process::exit(exit); diff --git a/docs/how-it-works/policies/network-rules.mdx b/docs/how-it-works/policies/network-rules.mdx index e9ed7bd495..a399beda81 100644 --- a/docs/how-it-works/policies/network-rules.mdx +++ b/docs/how-it-works/policies/network-rules.mdx @@ -121,6 +121,47 @@ protocol combine. Rules using another protocol cannot authorize the request; for example, a broader REST rule cannot allow a method excluded by a JSON-RPC route. Matching deny rules still take precedence over allows. +### Allowed Transports + +Use `allowed_transports` to choose how a client connects to an inspected HTTP +endpoint. Use `protocol` and `rules` to choose which requests it can send. + +```yaml +endpoints: + - host: api.example.com + port: 8443 + allowed_transports: [tls] + protocol: rest + access: read-only + enforcement: enforce + - host: legacy.example.com + port: 443 + allowed_transports: [tls, plaintext] + protocol: rest + access: read-only + enforcement: enforce +``` + +| `allowed_transports` | Accepted connections | +|---|---| +| `[tls]` | The client must use TLS. OpenShell terminates it and verifies the upstream server over a separate TLS connection. | +| `[plaintext]` | The client must send plaintext HTTP. | +| `[tls, plaintext]` | The client can use either. OpenShell still inspects the request. | + +If you omit the field, inspected HTTP endpoints require TLS on port 443 and +on any port where the endpoint uses provider credentials, a credential binding, +or request signing. Other inspected HTTP endpoints accept both transports. +The default applies separately to each port in `ports`. + +When upgrading, check clients that send plaintext to those endpoints. Allow +`plaintext` explicitly only if the route is trusted to carry the request and +any credentials it uses without encryption. A failed TLS handshake never +retries in plaintext. Transport restrictions apply even in `audit` mode. + +Use this field with `rest`, `graphql`, `websocket`, `json-rpc`, or `mcp`. +Native TCP and opaque `tls: skip` rules keep their existing behavior and do +not accept `allowed_transports`. + ### HTTP Connection Failures When an HTTP upstream closes an idle connection, OpenShell closes the client @@ -169,7 +210,8 @@ matching deny rule takes precedence over any allow, regardless of where either appears in the file. If one matching rule inspects requests and another does not, OpenShell inspects the connection, and the rule without `protocol` adds no request access. Endpoints that can match the same host and port must also agree -on settings such as `tls` and `allowed_ips`, or OpenShell rejects the policy. +on settings such as `tls` and `allowed_ips`. Inspected HTTP endpoints must agree +on the effective transports for each shared port, even across different paths. For example, suppose one rule allows `GET /repos/**` on a host and another rule for the same host, port, and binary denies `GET /repos/private/**`. OpenShell diff --git a/docs/how-it-works/policies/schema.mdx b/docs/how-it-works/policies/schema.mdx index bb87555ab0..f23a636e65 100644 --- a/docs/how-it-works/policies/schema.mdx +++ b/docs/how-it-works/policies/schema.mdx @@ -159,6 +159,7 @@ the gateway host. | Field | Type | Default | Description | |---|---|---|---| | `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). | +| `allowed_transports` | list of strings | [By port and credentials](/how-it-works/policies/network-rules#allowed-transports) | Accept `tls`, `plaintext`, or both on an inspected HTTP endpoint. An explicit list must be nonempty and contain no duplicates. | | `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. | | `access` | string | None | Access preset: `read-only`, `read-write`, or `full`. Refer to [Access Presets](#access-presets). | @@ -226,6 +227,7 @@ OpenShell rejects an endpoint that breaks these rules: signing, or protocol options. - 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 HTTP endpoints must allow the same transports on each shared port. Inspected endpoints that can match the same request must also agree on `protocol`, `enforcement`, and credential settings. diff --git a/e2e/python/test_sandbox_providers.py b/e2e/python/test_sandbox_providers.py index 95904bebdf..3240f1a33d 100644 --- a/e2e/python/test_sandbox_providers.py +++ b/e2e/python/test_sandbox_providers.py @@ -188,6 +188,7 @@ def _native_inference_profile( port=port, protocol="rest", tls=sandbox_pb2.NETWORK_TLS_MODE_UNSPECIFIED, + allowed_transports=[sandbox_pb2.NETWORK_TRANSPORT_PLAINTEXT], enforcement=sandbox_pb2.NETWORK_ENFORCEMENT_MODE_ENFORCE, rules=rules, allowed_ips=[ diff --git a/e2e/rust/tests/kubernetes_shared_supervisor.rs b/e2e/rust/tests/kubernetes_shared_supervisor.rs index a908b7eb8c..7a9b8c7184 100644 --- a/e2e/rust/tests/kubernetes_shared_supervisor.rs +++ b/e2e/rust/tests/kubernetes_shared_supervisor.rs @@ -293,6 +293,7 @@ endpoints: - host: {TEST_HOST} port: {port} protocol: rest + allowed_transports: [plaintext] access: full binaries: - path: /usr/bin/python* @@ -307,7 +308,7 @@ fn policy(ports: &[u16]) -> NamedTempFile { let endpoints = ports.iter().fold(String::new(), |mut endpoints, port| { let _ = write!( endpoints, - " - host: {TEST_HOST}\n port: {port}\n protocol: rest\n access: full\n" + " - host: {TEST_HOST}\n port: {port}\n protocol: rest\n allowed_transports: [plaintext]\n access: full\n" ); endpoints }); diff --git a/e2e/rust/tests/kubernetes_shared_supervisor_spiffe.rs b/e2e/rust/tests/kubernetes_shared_supervisor_spiffe.rs index b89f60fd90..1b60169cac 100644 --- a/e2e/rust/tests/kubernetes_shared_supervisor_spiffe.rs +++ b/e2e/rust/tests/kubernetes_shared_supervisor_spiffe.rs @@ -453,6 +453,7 @@ endpoints: port: {target_port} path: /** protocol: rest + allowed_transports: [plaintext] access: read-write enforcement: enforce allowed_ips: diff --git a/e2e/rust/tests/provider_token_exchange.rs b/e2e/rust/tests/provider_token_exchange.rs index 9105be98bc..0c8ec04e46 100644 --- a/e2e/rust/tests/provider_token_exchange.rs +++ b/e2e/rust/tests/provider_token_exchange.rs @@ -677,6 +677,7 @@ endpoints: port: {target_port} path: /** protocol: rest + allowed_transports: [plaintext] access: read-write enforcement: enforce allowed_ips: @@ -739,6 +740,7 @@ endpoints: port: {target_port} path: /{route}/** protocol: rest + allowed_transports: [plaintext] access: read-write enforcement: enforce allowed_ips: diff --git a/e2e/rust/tests/support/provider_refresh_handles.rs b/e2e/rust/tests/support/provider_refresh_handles.rs index a8624c1edf..6dfcc89127 100644 --- a/e2e/rust/tests/support/provider_refresh_handles.rs +++ b/e2e/rust/tests/support/provider_refresh_handles.rs @@ -71,6 +71,7 @@ fn write_profile( .suffix(".yaml") .tempfile() .map_err(|error| format!("create profile: {error}"))?; + let transport = if github { "tls" } else { "plaintext" }; let profile = format!( r"id: {PROFILE_ID} display_name: Stable refresh handle E2E @@ -97,6 +98,7 @@ endpoints: port: {resource_port} path: /probe protocol: rest + allowed_transports: [{transport}] access: full enforcement: enforce allowed_ips: @@ -137,6 +139,7 @@ fn write_policy( .suffix(".yaml") .tempfile() .map_err(|error| format!("create policy: {error}"))?; + let transport = if github { "tls" } else { "plaintext" }; let policy = format!( r"version: 1 filesystem_policy: @@ -156,6 +159,7 @@ network_policies: port: {resource_port} path: /probe protocol: rest + allowed_transports: [{transport}] access: full enforcement: enforce allowed_ips: diff --git a/proto/sandbox.proto b/proto/sandbox.proto index 4699ee244d..b5e55b5fd5 100644 --- a/proto/sandbox.proto +++ b/proto/sandbox.proto @@ -148,6 +148,16 @@ enum NetworkTlsMode { NETWORK_TLS_MODE_PASSTHROUGH = 3 [deprecated = true]; } +// Transport accepted by an inspected HTTP-family endpoint. +enum NetworkTransport { + // Rejected in an explicit transport allowlist. + NETWORK_TRANSPORT_UNSPECIFIED = 0; + // TLS from the workload and verified TLS to the destination. + NETWORK_TRANSPORT_TLS = 1; + // Inspected plaintext HTTP. + NETWORK_TRANSPORT_PLAINTEXT = 2; +} + // Enforcement behavior for inspected network traffic. enum NetworkEnforcementMode { // Preserve the existing default: log violations and allow traffic. @@ -268,6 +278,10 @@ message NetworkEndpoint { // It binds the provider record and complete profile policy, or the active // global policy, to this endpoint. User-authored values are ignored. string token_grant_owner = 27; + // Allowed transports for an inspected HTTP-family endpoint. Empty selects + // the endpoint's default. Explicit values must be unique and cannot be + // combined with tls: skip. + repeated NetworkTransport allowed_transports = 28; } // MCP options are grouped so MCP-specific policy can grow without adding more diff --git a/tests/suites/conformance/src/credential_gating.rs b/tests/suites/conformance/src/credential_gating.rs index 5230b86428..d5d16191cf 100644 --- a/tests/suites/conformance/src/credential_gating.rs +++ b/tests/suites/conformance/src/credential_gating.rs @@ -23,6 +23,7 @@ use testkit::{ }; const BASH: &str = "/usr/bin/bash"; +const PLAINTEXT: i32 = proto::NetworkTransport::Plaintext as i32; const TOKEN_ENV: &str = "E2E_GATING_TOKEN"; const TEST_SECRET: &str = "e2e-gating-secret-value"; @@ -48,7 +49,8 @@ async fn profile_rest_endpoint_keeps_body_placeholder(cx: &mut Context) -> testk let mut policy = policy::base(); allow_host(&mut policy, "credential_gating", server.port) .rest(Access::Full) - .request_body_credential_rewrite(false); + .request_body_credential_rewrite(false) + .allowed_transports = vec![PLAINTEXT]; let sandbox = create_sandbox(cx, "rest", policy, &[&provider]).await?; post_token_body(&sandbox, server.port).await?; expect_placeholder_body(&server).await @@ -125,7 +127,8 @@ async fn policy_binding_rest_body_keeps_placeholder_without_rewrite( allow_host(&mut policy, "credential_gating", server.port) .rest(Access::Full) .request_body_credential_rewrite(false) - .credential_binding(&provider); + .credential_binding(&provider) + .allowed_transports = vec![PLAINTEXT]; let sandbox = create_sandbox(cx, "body", policy, &[&provider]).await?; post_token_body(&sandbox, server.port).await?; expect_placeholder_body(&server).await @@ -144,7 +147,8 @@ async fn policy_binding_rest_body_rewrite_sends_secret_upstream( allow_host(&mut policy, "credential_gating", server.port) .rest(Access::Full) .request_body_credential_rewrite(true) - .credential_binding(&provider); + .credential_binding(&provider) + .allowed_transports = vec![PLAINTEXT]; let sandbox = create_sandbox(cx, "rw", policy, &[&provider]).await?; post_token_body(&sandbox, server.port).await?; let request = one_request(&server).await?; @@ -200,7 +204,8 @@ async fn profile_rest_endpoint_rewrites_header_and_body(cx: &mut Context) -> tes ep.rest(Access::Full) .path("/probe") .enforce() - .request_body_credential_rewrite(true); + .request_body_credential_rewrite(true) + .allowed_transports = vec![PLAINTEXT]; }) .await?; let token = provider_token(&sandbox).await?; @@ -246,6 +251,7 @@ async fn profile_websocket_endpoint_rewrites_text_frames(cx: &mut Context) -> te let server = WebSocketRecorder::start().await?; let sandbox = profile_endpoint_sandbox(cx, "wstxt", server.port, |ep| { ep.websocket(Access::ReadWrite).path("/ws").enforce(); + ep.allowed_transports = vec![PLAINTEXT]; ep.websocket_credential_rewrite = true; }) .await?; @@ -294,7 +300,7 @@ async fn profile_endpoints_bind_static_credentials(cx: &mut Context) -> testkit: let endpoint = |port| { format!( "{{host: {TEST_HOST}, port: {port}, path: /**, protocol: rest, access: full, \ - enforcement: enforce}}" + enforcement: enforce, allowed_transports: [plaintext]}}" ) }; let policy = policy::base_with(&format!( @@ -355,7 +361,9 @@ async fn send_binary_frame( providers: &[&str], ) -> Result { let mut policy = policy::base(); - allow_host(&mut policy, "credential_gating", server.port).websocket(Access::ReadWrite); + allow_host(&mut policy, "credential_gating", server.port) + .websocket(Access::ReadWrite) + .allowed_transports = vec![PLAINTEXT]; let sandbox = create_sandbox(cx, suffix, policy, providers).await?; sandbox .run_python( @@ -378,10 +386,10 @@ async fn install_gating_provider(cx: &Context, endpoints: Option<(u16, u16)>) -> if let Some((rest, websocket)) = endpoints { profile = profile .endpoint(TEST_HOST, rest, |ep| { - ep.rest(Access::Full); + ep.rest(Access::Full).allowed_transports = vec![PLAINTEXT]; }) .endpoint(TEST_HOST, websocket, |ep| { - ep.websocket(Access::ReadWrite); + ep.websocket(Access::ReadWrite).allowed_transports = vec![PLAINTEXT]; }); } install_gating_profile(cx, &profile).await @@ -416,7 +424,10 @@ async fn install_bound_provider( .display_name("E2E static endpoint binding") .credential(bearer_credential("bound_token", env_var)) .endpoint(TEST_HOST, port, |ep| { - ep.rest(Access::Full).path("/allowed/**").enforce(); + ep.rest(Access::Full) + .path("/allowed/**") + .enforce() + .allowed_transports = vec![PLAINTEXT]; }) .binaries([BASH]) .to_yaml()?; From 1b34173947e125287067b49e9261413636d765fa Mon Sep 17 00:00:00 2001 From: Free Wortley Date: Tue, 1 Dec 2026 10:44:08 -0800 Subject: [PATCH 02/11] feat(cli): show effective transports per port and verify credential delivery Signed-off-by: Free Wortley --- crates/openshell-cli/src/commands/provider.rs | 47 +++++++++++++++++++ .../src/proxy/transport_tests.rs | 32 ++++++++++--- docs/how-it-works/policies/network-rules.mdx | 4 ++ docs/how-it-works/providers/profiles.mdx | 2 +- e2e/rust/tests/provider_readiness.rs | 1 + .../tests/stable_external_placeholders.rs | 1 + 6 files changed, 79 insertions(+), 8 deletions(-) diff --git a/crates/openshell-cli/src/commands/provider.rs b/crates/openshell-cli/src/commands/provider.rs index b619cfb96e..7729e69226 100644 --- a/crates/openshell-cli/src/commands/provider.rs +++ b/crates/openshell-cli/src/commands/provider.rs @@ -13,6 +13,9 @@ use crate::commands::common::{ use crate::tls::{TlsOptions, grpc_client}; use dialoguer::Confirm; use miette::{IntoDiagnostic, Result, WrapErr, miette}; +use openshell_core::policy_l7::{ + AllowedTransports, effective_endpoint_ports, endpoint_allowed_transports, +}; use openshell_core::proto::ProviderProfileCategory; use openshell_core::proto::{ AttachSandboxProviderRequest, ConfigureProviderRefreshRequest, CreateProviderRequest, @@ -2650,6 +2653,7 @@ fn format_provider_profile_details(profile: &ProviderProfile) -> String { } } + let credentialed = ProviderTypeProfile::from_proto(profile).has_credentialed_endpoints(); rendered.push_str("\nEndpoints (declared policy):\n"); if profile.endpoints.is_empty() { rendered.push_str(" None declared.\n"); @@ -2698,6 +2702,28 @@ fn format_provider_profile_details(profile: &ProviderProfile) -> String { None => format!("unknown({})", endpoint.tls), }; let _ = writeln!(rendered, " TLS: {tls}"); + // The gateway derives credential provenance when it attaches the profile. + let mut declared = endpoint.clone(); + declared.provider_credentialed = credentialed; + let source = if endpoint.allowed_transports.is_empty() { + " (default)" + } else { + "" + }; + for port in effective_endpoint_ports(endpoint) { + let Some(allowed) = endpoint_allowed_transports(&declared, port) else { + continue; + }; + let label = match allowed { + AllowedTransports::Tls => "tls", + AllowedTransports::Plaintext => "plaintext", + AllowedTransports::Both => "tls, plaintext", + }; + let _ = writeln!( + rendered, + " Allowed transports on {port}: {label}{source}" + ); + } let _ = writeln!( rendered, " Allow uninspected credentials: {}", @@ -3167,6 +3193,27 @@ mod tests { assert!(rendered.contains("Binaries:\n None declared.\n")); } + #[test] + fn profile_description_shows_transports_for_each_port() { + use openshell_core::proto::{NetworkEndpoint, NetworkTransport}; + let mut profile = ProviderProfile { + endpoints: vec![NetworkEndpoint { + host: "api.example.com".into(), + ports: vec![443, 8443], + protocol: "rest".into(), + ..Default::default() + }], + ..Default::default() + }; + let text = format_provider_profile_details(&profile); + assert!(text.contains("Allowed transports on 443: tls (default)")); + assert!(text.contains("Allowed transports on 8443: tls, plaintext (default)")); + profile.endpoints[0].allowed_transports = vec![NetworkTransport::Plaintext as i32]; + let text = format_provider_profile_details(&profile); + assert!(text.contains("Allowed transports on 443: plaintext\n")); + assert!(text.contains("Allowed transports on 8443: plaintext\n")); + } + #[test] fn profile_description_distinguishes_tls_skip_and_credential_opt_in() { let profile = parse_profile_yaml( diff --git a/crates/openshell-supervisor-network/src/proxy/transport_tests.rs b/crates/openshell-supervisor-network/src/proxy/transport_tests.rs index 8d3b4483ed..50e42f497e 100644 --- a/crates/openshell-supervisor-network/src/proxy/transport_tests.rs +++ b/crates/openshell-supervisor-network/src/proxy/transport_tests.rs @@ -62,6 +62,14 @@ network_policies: .unwrap(); let (server, peer) = listener.accept().await.unwrap(); let addresses = Some((peer, server.local_addr().unwrap())); + let (_, resolver) = SecretResolver::from_provider_env( + [( + "TRANSPORT_TEST_TOKEN".to_string(), + "test-origin-token".to_string(), + )] + .into_iter() + .collect(), + ); let task = tokio::spawn(Box::pin(handle_mediated_connection( tokio::io::BufReader::new(Box::new(server)), Some(Ok(identity)), @@ -77,12 +85,12 @@ network_policies: Arc::new(Some("127.0.0.1".parse().unwrap())), // backend-pinned gateway Arc::new(None), // trusted_host_gateway Arc::new(upstream_proxy), - None, // provider_credentials - None, // secret_resolver - None, // denial_tx - None, // activity_tx - None, // endpoint_observation_tx - None, // required_proxy_authorization + None, // provider_credentials + resolver.map(Arc::new), // secret_resolver + None, // denial_tx + None, // activity_tx + None, // endpoint_observation_tx + None, // required_proxy_authorization ))); (client, task) } @@ -113,13 +121,23 @@ fn request(port: u16, absolute_form: bool) -> Vec { } else { "/status".to_string() }; - format!("GET {target} HTTP/1.1\r\nHost: {HOST}:{port}\r\nConnection: close\r\n\r\n") + format!("GET {target} HTTP/1.1\r\nHost: {HOST}:{port}\r\nAuthorization: Bearer openshell:resolve:env:TRANSPORT_TEST_TOKEN\r\nConnection: close\r\n\r\n") .into_bytes() } async fn respond_from_origin(mut stream: impl TokioAsyncRead + TokioAsyncWrite + Unpin) { let headers = read_headers(&mut stream).await; assert!(headers.starts_with(b"GET /status HTTP/1.1\r\n")); + let headers = String::from_utf8_lossy(&headers); + let auth: Vec<_> = headers + .lines() + .filter_map(|line| { + let (name, value) = line.split_once(':')?; + name.eq_ignore_ascii_case("authorization") + .then(|| value.trim()) + }) + .collect(); + assert_eq!(auth, ["Bearer test-origin-token"]); stream.write_all(ORIGIN_RESPONSE).await.unwrap(); stream.shutdown().await.unwrap(); } diff --git a/docs/how-it-works/policies/network-rules.mdx b/docs/how-it-works/policies/network-rules.mdx index a399beda81..17f9f8d80c 100644 --- a/docs/how-it-works/policies/network-rules.mdx +++ b/docs/how-it-works/policies/network-rules.mdx @@ -153,6 +153,10 @@ on any port where the endpoint uses provider credentials, a credential binding, or request signing. Other inspected HTTP endpoints accept both transports. The default applies separately to each port in `ports`. +Upgrade the gateway and supervisors before relying on this field. An older +gateway cannot preserve the new field. An upgraded gateway refuses to deliver +a policy that requires transport enforcement to an incompatible supervisor. + When upgrading, check clients that send plaintext to those endpoints. Allow `plaintext` explicitly only if the route is trusted to carry the request and any credentials it uses without encryption. A failed TLS handshake never diff --git a/docs/how-it-works/providers/profiles.mdx b/docs/how-it-works/providers/profiles.mdx index 9b083fe05e..17de43de88 100644 --- a/docs/how-it-works/providers/profiles.mdx +++ b/docs/how-it-works/providers/profiles.mdx @@ -287,7 +287,7 @@ openshell profile describe github openshell profile describe github -o yaml ``` -The description shows metadata, credential names and authentication settings, endpoints with their protocols and policy rule counts, allowed binaries, source, and scope. Endpoint details include TLS handling, permission for uninspected credential traffic, and MCP method and tool-name settings. A `tls: skip` endpoint is shown as a raw tunnel without L7 inspection or credential rewrite, even when it declares an L7 protocol and rules. Use JSON or YAML output to inspect the complete rule definitions. The description reads the reusable definition without reading credential values from provider instances. A missing profile ID returns an error. +The description shows metadata, credential names and authentication settings, endpoints with their protocols and policy rule counts, allowed binaries, source, and scope. Endpoint details include the allowed transports for each inspected HTTP port, TLS handling, permission for uninspected credential traffic, and MCP method and tool-name settings. A `tls: skip` endpoint is shown as a raw tunnel without L7 inspection or credential rewrite, even when it declares an L7 protocol and rules. Use JSON or YAML output to inspect the complete rule definitions. The description reads the reusable definition without reading credential values from provider instances. A missing profile ID returns an error. For MCP endpoints, the text output labels `allow_all_known_mcp_methods` as `Allow core MCP methods for the selected revision` and shows the profile's declared revisions. These are configuration values; `describe` does not observe a connection or its negotiated capabilities. At request time, OpenShell selects the revision from `MCP-Protocol-Version`, or uses `2025-03-26` when the header is absent. Legacy standalone `initialize` requests negotiate their revision in the body, as described in [MCP version selection](/how-it-works/policies/schema#mcp-version-selection). The option allows [core methods for that revision](/how-it-works/policies/schema#core-mcp-methods), subject to tool restrictions and deny rules. Without tool-specific allow rules, it allows every tool name, subject to deny rules and tool-name validation. Extension methods still require an exact allow rule. JSON and YAML output retain the `allow_all_known_mcp_methods` field name. diff --git a/e2e/rust/tests/provider_readiness.rs b/e2e/rust/tests/provider_readiness.rs index b7d1256641..bbe9cc59f1 100644 --- a/e2e/rust/tests/provider_readiness.rs +++ b/e2e/rust/tests/provider_readiness.rs @@ -890,6 +890,7 @@ fn write_policy( .map(|(host, port)| { json!({"host": host, "port": port, "path": "/**", "protocol": "rest", "access": "full", "enforcement": "enforce", + "allowed_transports": ["tls"], "allowed_ips": [host]}) }) .collect::>(); diff --git a/e2e/rust/tests/stable_external_placeholders.rs b/e2e/rust/tests/stable_external_placeholders.rs index 16002c21c2..67617303fa 100644 --- a/e2e/rust/tests/stable_external_placeholders.rs +++ b/e2e/rust/tests/stable_external_placeholders.rs @@ -835,6 +835,7 @@ fn write_policy( .map(|(host, port)| { json!({"host": host, "port": port, "path": "/**", "protocol": "rest", "access": "full", "enforcement": "enforce", + "allowed_transports": ["tls"], "allowed_ips": ["10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "fc00::/7"]}) }) .collect::>(); From cf665f946a77b0f2f45a5680814110efd43a68d6 Mon Sep 17 00:00:00 2001 From: freeqaz Date: Wed, 2 Dec 2026 03:40:03 +0000 Subject: [PATCH 03/11] fix(policy): intersect compatible endpoint transports and reject sql+http shared ports Use transport-set intersection across overlapping host:port endpoints so a credentialed path (default TLS) tightens plain siblings to TLS instead of retroactively rejecting previously valid stored policies, while still rejecting disjoint TLS vs plaintext combinations. Also reject sql+HTTP combinations sharing a host and port at admission, add unit coverage for raw transparent TCP fail-close on inspected HTTP endpoints, and fix pre-dial stale-policy and missing-TLS telemetry in the CONNECT handler. Signed-off-by: freeqaz --- crates/openshell-core/src/policy_l7.rs | 94 +++++++++-- crates/openshell-policy/src/ambiguity.rs | 99 ++++++++--- .../openshell-supervisor-network/src/proxy.rs | 109 +++++++++--- .../src/proxy/transport_tests.rs | 159 ++++++++++++++++++ 4 files changed, 403 insertions(+), 58 deletions(-) diff --git a/crates/openshell-core/src/policy_l7.rs b/crates/openshell-core/src/policy_l7.rs index 722b69b10b..b3438b484b 100644 --- a/crates/openshell-core/src/policy_l7.rs +++ b/crates/openshell-core/src/policy_l7.rs @@ -42,6 +42,24 @@ pub enum AllowedTransports { Both, } +impl AllowedTransports { + /// Intersect two transport allowlists on a shared `host:port`. + /// + /// Returns `None` when the sets are disjoint (`Tls` vs `Plaintext`) and + /// no single connection transport can satisfy both. + #[must_use] + pub const fn intersect(self, other: Self) -> Option { + match (self, other) { + (Self::Tls, Self::Tls | Self::Both) | (Self::Both, Self::Tls) => Some(Self::Tls), + (Self::Plaintext, Self::Plaintext | Self::Both) | (Self::Both, Self::Plaintext) => { + Some(Self::Plaintext) + } + (Self::Both, Self::Both) => Some(Self::Both), + (Self::Tls, Self::Plaintext) | (Self::Plaintext, Self::Tls) => None, + } + } +} + pub fn network_transport_from_str(value: &str) -> Option { match value { "tls" => Some(NetworkTransport::Tls), @@ -58,21 +76,23 @@ pub fn network_transport_to_str(value: i32) -> Option<&'static str> { } } +/// Returns the inspected L7 protocol when `tls` does not skip termination. +#[must_use] +pub fn inspected_l7_protocol(protocol: &str, tls: i32) -> Option { + if tls == NetworkTlsMode::Unspecified as i32 { + L7Protocol::parse(protocol) + } else { + None + } +} + /// Validate the authored set without assigning defaults to an omitted field. pub fn validate_allowed_transports( explicit: &[i32], protocol: &str, tls: i32, ) -> Option<&'static str> { - parse_allowed_transports(explicit, inspected_protocol(protocol, tls)).err() -} - -fn inspected_protocol(protocol: &str, tls: i32) -> Option { - if tls == NetworkTlsMode::Unspecified as i32 { - L7Protocol::parse(protocol) - } else { - None - } + parse_allowed_transports(explicit, inspected_l7_protocol(protocol, tls)).err() } fn parse_allowed_transports( @@ -142,7 +162,7 @@ pub fn endpoint_allowed_transports( ) -> Option { effective_allowed_transports( &endpoint.allowed_transports, - inspected_protocol(&endpoint.protocol, endpoint.tls), + inspected_l7_protocol(&endpoint.protocol, endpoint.tls), endpoint_is_credentialed(endpoint), port, ) @@ -150,6 +170,17 @@ pub fn endpoint_allowed_transports( .flatten() } +/// Whether `endpoint` requires a supervisor that enforces endpoint transport +/// restrictions (either an explicit allowlist or a TLS-only default on any +/// selected port). +#[must_use] +pub fn endpoint_requires_transport_enforcement(endpoint: &NetworkEndpoint) -> bool { + !endpoint.allowed_transports.is_empty() + || selector_ports(endpoint).iter().any(|&port| { + endpoint_allowed_transports(endpoint, port) == Some(AllowedTransports::Tls) + }) +} + pub fn network_enforcement_mode_from_str(value: &str) -> Option { match value { "" => Some(NetworkEnforcementMode::Unspecified), @@ -232,7 +263,10 @@ impl L7Protocol { } } - fn is_http(self) -> bool { + /// Returns `true` for protocols carried over HTTP (`rest`, `websocket`, + /// `graphql`, `json-rpc`, `mcp`). + #[must_use] + pub const fn is_http(self) -> bool { matches!( self, Self::Rest | Self::Websocket | Self::Graphql | Self::JsonRpc | Self::Mcp @@ -343,12 +377,48 @@ mod transport_tests { for protocol in ["", "tcp", "sql", "ssh"] { assert!(validate_allowed_transports(&[tls], protocol, 0).is_some()); assert_eq!( - effective_allowed_transports(&[], inspected_protocol(protocol, 0), false, 443), + effective_allowed_transports(&[], inspected_l7_protocol(protocol, 0), false, 443), Ok(None) ); } assert!(validate_allowed_transports(&[tls], "rest", NetworkTlsMode::Skip as i32).is_some()); } + + #[test] + fn intersect_tightens_compatible_sets_and_rejects_disjoint_sets() { + use AllowedTransports::{Both, Plaintext, Tls}; + + assert_eq!(Tls.intersect(Tls), Some(Tls)); + assert_eq!(Tls.intersect(Both), Some(Tls)); + assert_eq!(Both.intersect(Tls), Some(Tls)); + assert_eq!(Plaintext.intersect(Plaintext), Some(Plaintext)); + assert_eq!(Plaintext.intersect(Both), Some(Plaintext)); + assert_eq!(Both.intersect(Plaintext), Some(Plaintext)); + assert_eq!(Both.intersect(Both), Some(Both)); + assert_eq!(Tls.intersect(Plaintext), None); + assert_eq!(Plaintext.intersect(Tls), None); + } + + #[test] + fn transport_enforcement_requirement_tracks_defaults_and_explicit_lists() { + let mut endpoint = NetworkEndpoint { + protocol: "rest".into(), + port: 8443, + ..Default::default() + }; + assert!(!endpoint_requires_transport_enforcement(&endpoint)); + + endpoint.port = 443; + assert!(endpoint_requires_transport_enforcement(&endpoint)); + + endpoint.port = 8443; + endpoint.provider_credentialed = true; + assert!(endpoint_requires_transport_enforcement(&endpoint)); + + endpoint.provider_credentialed = false; + endpoint.allowed_transports = vec![NetworkTransport::Plaintext as i32]; + assert!(endpoint_requires_transport_enforcement(&endpoint)); + } } #[cfg(test)] diff --git a/crates/openshell-policy/src/ambiguity.rs b/crates/openshell-policy/src/ambiguity.rs index 3c4c1e94f7..138a3101af 100644 --- a/crates/openshell-policy/src/ambiguity.rs +++ b/crates/openshell-policy/src/ambiguity.rs @@ -3,7 +3,7 @@ //! Validation for endpoint selectors whose policy-derived behavior conflicts. -use openshell_core::policy_l7::endpoint_allowed_transports; +use openshell_core::policy_l7::{L7Protocol, endpoint_allowed_transports, inspected_l7_protocol}; use openshell_core::proto::{ NetworkEndpoint, NetworkEnforcementMode, NetworkTlsMode, SandboxPolicy, }; @@ -92,13 +92,15 @@ pub fn find_endpoint_ambiguities(policy: &SandboxPolicy) -> Vec Vec< &normalized_strings(&left.allowed_ips), &normalized_strings(&right.allowed_ips), ); + // SQL uses a non-HTTP wire relay that cannot share a connection port with + // an inspected HTTP transport policy. + let left_sql = L7Protocol::parse(&left.protocol) == Some(L7Protocol::Sql); + let right_sql = L7Protocol::parse(&right.protocol) == Some(L7Protocol::Sql); + let left_http = + inspected_l7_protocol(&left.protocol, left.tls).is_some_and(L7Protocol::is_http); + let right_http = + inspected_l7_protocol(&right.protocol, right.tls).is_some_and(L7Protocol::is_http); + if (left_sql && right_http) || (right_sql && left_http) { + push_conflict( + &mut conflicts, + "protocol", + &normalized_request_protocol(&left.protocol), + &normalized_request_protocol(&right.protocol), + ); + } conflicts } @@ -792,23 +810,66 @@ mod tests { } #[test] - fn transport_conflicts_compare_effective_sets_per_shared_port_before_path_matching() { + fn transport_conflicts_allow_stricter_intersection_and_reject_disjoint_sets() { use openshell_core::proto::NetworkTransport::{Plaintext, Tls}; - let mut left = endpoint("*.example.com", 0); - left.ports = vec![443, 8443]; - left.protocol = "rest".into(); - left.path = "/read/**".into(); - let mut right = endpoint("api.example.com", 443); - right.protocol = "rest".into(); - right.path = "/write/**".into(); - right.allowed_transports = vec![Tls as i32]; - assert!(find_endpoint_ambiguities(&policy_with(left.clone(), right.clone())).is_empty()); - right.port = 8443; - let conflicts = find_endpoint_ambiguities(&policy_with(left.clone(), right.clone())); + + // Credentialed path (default TLS) and plain sibling (default Both) on a + // non-443 port intersect cleanly to TLS, preserving stored policies. + let mut credentialed = endpoint("api.example.com", 8443); + credentialed.protocol = "rest".into(); + credentialed.path = "/auth/**".into(); + credentialed.provider_credentialed = true; + let mut sibling = endpoint("api.example.com", 8443); + sibling.protocol = "rest".into(); + sibling.path = "/public/**".into(); + assert!( + find_endpoint_ambiguities(&policy_with(credentialed.clone(), sibling.clone())) + .is_empty() + ); + + // Explicit [tls] with a broader default-Both rule also intersects to TLS. + let mut wildcard = endpoint("*.example.com", 0); + wildcard.ports = vec![443, 8443]; + wildcard.protocol = "rest".into(); + wildcard.path = "/read/**".into(); + let mut explicit_tls = endpoint("api.example.com", 8443); + explicit_tls.protocol = "rest".into(); + explicit_tls.path = "/write/**".into(); + explicit_tls.allowed_transports = vec![Tls as i32]; + assert!(find_endpoint_ambiguities(&policy_with(wildcard.clone(), explicit_tls)).is_empty()); + + // Disjoint sets (TLS vs plaintext) still fail before path matching. + let mut plaintext_only = endpoint("api.example.com", 443); + plaintext_only.protocol = "rest".into(); + plaintext_only.path = "/write/**".into(); + plaintext_only.allowed_transports = vec![Plaintext as i32]; + let conflicts = find_endpoint_ambiguities(&policy_with(wildcard, plaintext_only.clone())); assert_eq!(conflicts.len(), 1); - assert!(conflicts[0].conflicts[0].contains("allowed_transports on port 8443")); - right.allowed_transports.push(Plaintext as i32); - assert!(find_endpoint_ambiguities(&policy_with(left, right)).is_empty()); + assert!(conflicts[0].conflicts[0].contains("allowed_transports on port 443")); + + plaintext_only.port = 8443; + let cred_conflicts = find_endpoint_ambiguities(&policy_with(credentialed, plaintext_only)); + assert_eq!(cred_conflicts.len(), 1); + assert!(cred_conflicts[0].conflicts[0].contains("allowed_transports on port 8443")); + } + + #[test] + fn sql_and_inspected_http_cannot_share_a_host_and_port() { + let mut sql = endpoint("db.example.com", 5432); + sql.protocol = "sql".into(); + sql.path = "/sql/**".into(); + let mut http = endpoint("db.example.com", 5432); + http.protocol = "rest".into(); + http.path = "/health".into(); + + let conflicts = find_endpoint_ambiguities(&policy_with(sql, http)); + assert_eq!(conflicts.len(), 1); + assert!( + conflicts[0] + .conflicts + .iter() + .any(|c| c.contains("protocol=")) + ); } #[test] diff --git a/crates/openshell-supervisor-network/src/proxy.rs b/crates/openshell-supervisor-network/src/proxy.rs index 3883c0202f..056f74e3f6 100644 --- a/crates/openshell-supervisor-network/src/proxy.rs +++ b/crates/openshell-supervisor-network/src/proxy.rs @@ -1471,13 +1471,7 @@ async fn handle_transparent_tcp_connection( return Ok(()); } - if query_allowed_transports(&decision)?.is_some() { - emit_transport_denial( - &decision, - workload_addr, - "Inspected transport is unavailable on the raw transparent TCP adapter", - ); - emit_activity(&activity_tx, true, "transport_not_allowed"); + if reject_inspected_transparent_tcp(&decision, workload_addr, &activity_tx)? { return Ok(()); } @@ -1638,6 +1632,24 @@ struct TransparentTcpAllowAudit<'a> { engine: &'a str, } +#[cfg(any(target_os = "linux", test))] +fn reject_inspected_transparent_tcp( + decision: &EgressDecision, + workload_addr: SocketAddr, + activity_tx: &Option, +) -> Result { + if query_allowed_transports(decision)?.is_some() { + emit_transport_denial( + decision, + workload_addr, + "Inspected transport is unavailable on the raw transparent TCP adapter", + ); + emit_activity(activity_tx, true, "transport_not_allowed"); + return Ok(true); + } + Ok(false) +} + #[cfg(any(target_os = "linux", test))] fn build_transparent_tcp_allow_ocsf_event( audit: TransparentTcpAllowAudit<'_>, @@ -3486,18 +3498,31 @@ async fn handle_mediated_connection( // Clients send the tunnel payload only after this acknowledgement. // Classify before dialing so a transport refusal cannot reach the origin. respond(&mut client, b"HTTP/1.1 200 Connection Established\r\n\r\n").await?; + let mut stale_during_peek = false; let peeked = tokio::select! { peeked = peek_tunnel_protocol(&mut client) => peeked?, - () = connect_generation_guard.wait_until_stale() => None, + () = connect_generation_guard.wait_until_stale() => { + stale_during_peek = true; + None + } }; let Some((protocol, prefix)) = peeked else { + if stale_during_peek { + emit_l7_tunnel_close_after_policy_change( + &host_lc, + port, + miette::miette!( + "policy changed while CONNECT was classifying transport \ + [captured_generation:{} current_generation:{}]", + connect_generation_guard.captured_generation(), + connect_generation_guard.current_generation(), + ), + ); + emit_activity_simple(activity_tx.as_ref(), true, "policy_stale"); + } return Ok(()); }; - let rejection = transport_rejection(transports, protocol).or_else(|| { - (protocol == TunnelProtocol::Tls && tls_state.is_none()) - .then_some(TLS_TERMINATION_UNAVAILABLE_DETAIL) - }); - if let Some(detail) = rejection { + if let Some(detail) = transport_rejection(transports, protocol) { if let Some(observer) = connect_endpoint_observer.as_ref() { observer.observe(EndpointResult::PolicyDenied); } @@ -3512,6 +3537,38 @@ async fn handle_mediated_connection( } return Ok(()); } + if protocol == TunnelProtocol::Tls && tls_state.is_none() { + if let Some(observer) = connect_endpoint_observer.as_ref() { + observer.observe(EndpointResult::TlsFailed); + } + let event = NetworkActivityBuilder::new(openshell_ocsf::ctx::ctx()) + .activity(ActivityId::Open) + .action(ActionId::Denied) + .disposition(DispositionId::Blocked) + .severity(SeverityId::High) + .status(StatusId::Failure) + .dst_endpoint(Endpoint::from_domain(&host_lc, port)) + .src_endpoint_addr(workload_addr.ip(), workload_addr.port()) + .actor_process(actor.clone()) + .firewall_rule(policy_str, "tls") + .message(format!( + "CONNECT refused for {host_lc}:{port}: {TLS_TERMINATION_UNAVAILABLE_DETAIL}" + )) + .status_detail(TLS_TERMINATION_UNAVAILABLE_DETAIL) + .build(); + egress_emit!(event); + emit_activity_simple(activity_tx.as_ref(), true, "tls_termination_unavailable"); + emit_denial( + &denial_tx, + &host_lc, + port, + &binary_str, + &decision, + TLS_TERMINATION_UNAVAILABLE_DETAIL, + "connect-tls-termination-unavailable", + ); + return Ok(()); + } client = replay_tunnel_prefix(client, prefix); pre_dial_protocol = Some(protocol); } @@ -4430,8 +4487,8 @@ fn hydrate_l7_route(decision: &mut EgressDecision, http_transport: bool) { let port = decision.intent.destination.port; let mut route = query_l7_route_snapshot(decision, &host, port); if http_transport && let Some(route) = route.as_mut() { - // The legacy SQL adapter can copy opaque bytes. It must not become - // the relay for a connection with an inspected HTTP transport policy. + // Defense in depth: admission rejects sql+HTTP on shared ports, and + // the SQL passthrough adapter must never relay an inspected HTTP port. route .configs .retain(|snapshot| snapshot.config.protocol != crate::l7::L7Protocol::Sql); @@ -4439,11 +4496,11 @@ fn hydrate_l7_route(decision: &mut EgressDecision, http_transport: bool) { decision.endpoint.l7_route = route; } -/// A connection picks a transport before its HTTP path is known. Read all -/// inspected configs from the captured authorization, without letting a bare -/// L4 sibling hide the transport policy. +/// A connection picks a transport before its HTTP path is known. Intersect all +/// inspected configs from the captured authorization so a stricter sibling +/// tightens the connection without letting a bare L4 grant hide the policy. fn query_allowed_transports(decision: &EgressDecision) -> Result> { - let mut effective = None; + let mut effective: Option = None; let port = decision.intent.destination.port; for config in &decision.endpoint.policy_configs { let Some(allowed) = config @@ -4452,14 +4509,12 @@ fn query_allowed_transports(decision: &EgressDecision) -> Result Some(allowed), + Some(previous) => Some(previous.intersect(allowed).ok_or_else(|| { + miette::miette!("matched endpoints have disjoint allowed_transports") + })?), + }; } Ok(effective) } diff --git a/crates/openshell-supervisor-network/src/proxy/transport_tests.rs b/crates/openshell-supervisor-network/src/proxy/transport_tests.rs index 50e42f497e..7ff2b01ef9 100644 --- a/crates/openshell-supervisor-network/src/proxy/transport_tests.rs +++ b/crates/openshell-supervisor-network/src/proxy/transport_tests.rs @@ -387,3 +387,162 @@ async fn mixed_transports_never_fall_back_to_an_opaque_tunnel() { .unwrap(); assert_no_origin_connection(&listener).await; } + +#[tokio::test] +async fn credentialed_sibling_intersects_to_tls_across_paths() { + let port = 8443; + let policy = policy_with_native_executable_paths(&format!( + r#" +network_policies: + auth_api: + name: auth_api + endpoints: + - host: {HOST} + port: {port} + path: /auth/** + protocol: rest + enforcement: enforce + provider_credentialed: true + rules: + - allow: {{ method: GET, path: /auth/token }} + binaries: + - path: /usr/bin/test-client + public_api: + name: public_api + endpoints: + - host: {HOST} + port: {port} + path: /status + protocol: rest + enforcement: enforce + rules: + - allow: {{ method: GET, path: /status }} + binaries: + - path: /usr/bin/test-client +"#, + )); + let engine = Arc::new( + OpaEngine::from_strings(include_str!("../../data/sandbox-policy.rego"), &policy) + .expect("load sibling transport policy"), + ); + let identity = ContractBinaryIdentity { + executable: ContractExecutableIdentity { + path: executable_path("/usr/bin/test-client"), + digest: Some("00".repeat(32).parse().unwrap()), + }, + ancestors: Vec::new(), + cmdline_paths: Vec::new(), + process: None, + }; + let (listener, upstream) = upstream_listener().await; + let ca = SandboxCa::generate().unwrap(); + let roots = trust_ca(&ca); + let tls_state = Arc::new(ProxyTlsState::new(CertCache::new(ca), roots)); + let proxy_listener = TcpListener::bind(LOOPBACK).await.unwrap(); + let mut client = connect_tcp_nodelay_best_effort(proxy_listener.local_addr().unwrap()) + .await + .unwrap(); + let (server, peer) = proxy_listener.accept().await.unwrap(); + let addresses = Some((peer, server.local_addr().unwrap())); + let proxy = tokio::spawn(Box::pin(handle_mediated_connection( + tokio::io::BufReader::new(Box::new(server)), + Some(Ok(identity)), + addresses, + None, + None, + engine.into(), + Arc::new(BinaryIdentityCache::new()), + Arc::new(AtomicU32::new(0)), + Some(tls_state), + None, + AgentProposals::default(), + Arc::new(Some("127.0.0.1".parse().unwrap())), + Arc::new(None), + Arc::new(Some(upstream)), + None, + None, + None, + None, + None, + None, + ))); + + start_connect(&mut client, port).await; + client.write_all(&request(port, false)).await.unwrap(); + let mut response = Vec::new(); + client.read_to_end(&mut response).await.unwrap(); + assert_transport_denial(&response); + proxy.await.unwrap().unwrap(); + assert_no_origin_connection(&listener).await; +} + +#[test] +fn raw_transparent_tcp_fails_closed_for_inspected_http_endpoints() { + let binary_path = executable_path("/usr/bin/test-client"); + for (port, endpoint_yaml, expected_rejected) in [ + (443, " protocol: rest\n access: full\n", true), + (8443, " protocol: rest\n access: full\n", true), + ( + 8443, + " protocol: rest\n access: full\n allowed_transports: [plaintext]\n", + true, + ), + (8443, " protocol: tcp\n", false), + (8443, "", false), + (8443, " tls: skip\n", false), + ] { + let policy = policy_with_native_executable_paths(&format!( + r#" +network_policies: + api: + name: api + endpoints: + - host: {HOST} + port: {port} +{endpoint_yaml} binaries: + - path: /usr/bin/test-client +"#, + )); + let engine: PolicyEngine = Arc::new( + OpaEngine::from_strings(include_str!("../../data/sandbox-policy.rego"), &policy) + .expect("load transparent policy"), + ) + .into(); + let input = crate::policy_types::NetworkInput { + host: HOST.to_string(), + port, + binary_path: binary_path.clone(), + binary_sha256: String::new(), + ancestors: Vec::new(), + cmdline_paths: Vec::new(), + }; + let authorization = engine.authorize_egress(&input).expect("authorize"); + assert!( + matches!(authorization.action, NetworkAction::Allow { .. }), + "expected allow for {endpoint_yaml:?}" + ); + let decision = EgressDecision { + intent: EgressIntent::transparent_tcp(HOST.to_string(), port), + action: authorization.action.clone(), + policy_generation: authorization.generation, + engine: "opa", + identity: ProcessIdentityEvidence::Available, + endpoint: EndpointDecision::from_authorization(&authorization), + binary: Some(binary_path.clone()), + binary_pid: None, + ancestors: Vec::new(), + cmdline_paths: Vec::new(), + process: None, + }; + let rejected = reject_inspected_transparent_tcp( + &decision, + SocketAddr::from(([127, 0, 0, 1], 40_000)), + &None, + ) + .expect("transport check"); + assert_eq!( + rejected, expected_rejected, + "transparent TCP rejection mismatch for port {port} ({endpoint_yaml:?})" + ); + } +} From 30723c9d0ffa667a4b95ff03393ff019a2cb7d67 Mon Sep 17 00:00:00 2001 From: freeqaz Date: Wed, 2 Dec 2026 03:42:57 +0000 Subject: [PATCH 04/11] fix(cedar): scope provider allowed_transports to inspected routes and check load-time conflicts Apply provider allowed_transports only when Cedar inspects the route so uninspected L4 or unmatched provider routes never fail allowed_transports_for_port and drop permitted connections at runtime. Add a shared Cedar/provider transport analyzer in openshell-policy-cedar-adapter and run it during LoadedPolicy::from_proto so provider transport lists that are disjoint from Cedar-derived defaults fail at load time instead of silently composing and erroring every connection. Also intersect authority transports before tightening sibling routes so an explicit plaintext credentialed route on a non-443 port does not stamp TLS onto empty siblings. Signed-off-by: freeqaz --- .../openshell-policy-cedar-adapter/src/lib.rs | 221 +++++++++++++++++- .../src/cedar_only/routes.rs | 46 +++- .../src/cedar_only/tests.rs | 112 +++++++++ crates/openshell-policy/src/lib.rs | 5 +- 4 files changed, 374 insertions(+), 10 deletions(-) diff --git a/crates/openshell-policy-cedar-adapter/src/lib.rs b/crates/openshell-policy-cedar-adapter/src/lib.rs index efbfb652e8..a06faaef82 100644 --- a/crates/openshell-policy-cedar-adapter/src/lib.rs +++ b/crates/openshell-policy-cedar-adapter/src/lib.rs @@ -3,9 +3,15 @@ //! Adapts Cedar analysis to sandbox policy messages for gateway and runtime composition. +use std::collections::{BTreeMap, HashMap}; +use std::hash::BuildHasher; + use miette::Result; -use openshell_core::policy_l7::{EffectiveFilesystem, effective_endpoint_ports}; -use openshell_core::proto::{FilesystemPolicy, NetworkEndpoint, NetworkTlsMode}; +use openshell_core::policy_l7::{ + AllowedTransports, EffectiveFilesystem, L7Protocol, effective_allowed_transports, + effective_endpoint_ports, endpoint_is_credentialed, +}; +use openshell_core::proto::{FilesystemPolicy, NetworkEndpoint, NetworkPolicyRule, NetworkTlsMode}; use openshell_policy_cedar::CedarEngine; pub mod endpoint_status; @@ -54,6 +60,154 @@ pub fn effective_filesystem(source: &str) -> Result { Ok(engine_filesystem(&engine)) } +/// Transport compatibility and capability summary for a Cedar policy composed +/// with attached provider rules. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CedarTransportAnalysis { + pub conflicts: Vec, + pub requires_transport_support: bool, +} + +/// Analyze effective transport constraints of a Cedar policy and attached +/// provider rules using an already-parsed [`CedarEngine`]. +#[must_use] +pub fn analyze_engine_provider_transports( + engine: &CedarEngine, + provider_rules: &HashMap, +) -> CedarTransportAnalysis { + let mut cedar_by_port: BTreeMap> = BTreeMap::new(); + for (host, port, path, _) in engine.configured_l7_endpoints() { + cedar_by_port.entry(port).or_default().push((host, path)); + } + + let mut providers: Vec<(&str, usize, &NetworkEndpoint)> = provider_rules + .iter() + .flat_map(|(name, rule)| { + rule.endpoints + .iter() + .enumerate() + .map(move |(index, endpoint)| (name.as_str(), index, endpoint)) + }) + .collect(); + providers.sort_by(|left, right| (left.0, left.1).cmp(&(right.0, right.1))); + + let mut conflicts = Vec::new(); + let mut requires_transport_support = false; + + for (port, cedar_entries) in &cedar_by_port { + if *port == 443 { + requires_transport_support = true; + } + let mut inspected_providers: Vec<(&str, usize, &NetworkEndpoint, AllowedTransports)> = + Vec::new(); + for &(rule_name, endpoint_index, endpoint) in &providers { + if endpoint.host.is_empty() + || !effective_endpoint_ports(endpoint).contains(&u32::from(*port)) + { + continue; + } + let covered = cedar_entries.iter().any(|(cedar_host, cedar_path)| { + openshell_core::host_pattern::host_patterns_overlap(&endpoint.host, cedar_host) + .unwrap_or(false) + && (cedar_path == &endpoint.path + || openshell_core::endpoint_path::matches(cedar_path, &endpoint.path)) + }); + if !covered { + continue; + } + match effective_allowed_transports( + &endpoint.allowed_transports, + Some(L7Protocol::Rest), + endpoint_is_credentialed(endpoint), + u32::from(*port), + ) { + Ok(Some(transports)) => { + if !endpoint.allowed_transports.is_empty() + || transports == AllowedTransports::Tls + { + requires_transport_support = true; + } + inspected_providers.push((rule_name, endpoint_index, endpoint, transports)); + } + Ok(None) => {} + Err(reason) => conflicts.push(format!( + "provider policy '{rule_name}' endpoint[{endpoint_index}] ({}:{port}): {reason}", + endpoint.host + )), + } + } + + for left_idx in 0..inspected_providers.len() { + for right_idx in (left_idx + 1)..inspected_providers.len() { + let left = inspected_providers[left_idx]; + let right = inspected_providers[right_idx]; + if openshell_core::host_pattern::host_patterns_overlap(&left.2.host, &right.2.host) + .unwrap_or(false) + && left.3.intersect(right.3).is_none() + { + conflicts.push(format!( + "provider policies '{}' endpoint[{}] ({}:{port}) and '{}' endpoint[{}] ({}:{port}) have disjoint allowed_transports ({:?} vs {:?})", + left.0, left.1, left.2.host, right.0, right.1, right.2.host, left.3, right.3 + )); + } + } + } + + if *port == 443 { + for &(rule_name, endpoint_index, endpoint, transports) in &inspected_providers { + if transports != AllowedTransports::Plaintext { + continue; + } + for (cedar_host, cedar_path) in cedar_entries { + if !openshell_core::host_pattern::host_patterns_overlap( + &endpoint.host, + cedar_host, + ) + .unwrap_or(false) + { + continue; + } + let path_covered_for_provider = + inspected_providers.iter().any(|(_, _, q, _)| { + q.path == *cedar_path + && (q.host.eq_ignore_ascii_case(&endpoint.host) + || openshell_core::host_pattern::host_matches( + &q.host, + &endpoint.host, + ) + .unwrap_or(false)) + }); + if !path_covered_for_provider { + conflicts.push(format!( + "provider policy '{rule_name}' endpoint[{endpoint_index}] ({}:443) allows plaintext, conflicting with Cedar-inspected endpoint '{cedar_host}:443' (default TLS)", + endpoint.host + )); + } + } + } + } + } + + CedarTransportAnalysis { + conflicts, + requires_transport_support, + } +} + +/// Parse Cedar source once and analyze transport compatibility and capability +/// requirements with attached provider rules. +/// +/// # Errors +/// Returns an error if the Cedar policy cannot be loaded. +pub fn analyze_provider_transports( + source: &str, + provider_rules: &HashMap, +) -> Result { + let engine = + CedarEngine::from_policy_str(source).map_err(|error| miette::miette!("{error}"))?; + Ok(analyze_engine_provider_transports(&engine, provider_rules)) +} + /// Derive the host and port selectors of a policy's inspected HTTP endpoints. /// /// # Errors @@ -111,3 +265,66 @@ pub fn engine_filesystem(engine: &CedarEngine) -> EffectiveFilesystem { needs_proxy_baseline: engine.has_network_permits(), } } + +#[cfg(test)] +mod tests { + use super::*; + use openshell_core::proto::NetworkTransport; + + fn provider_rules(endpoints: Vec) -> HashMap { + HashMap::from([( + "provider".to_string(), + NetworkPolicyRule { + name: "provider".to_string(), + endpoints, + ..Default::default() + }, + )]) + } + + #[test] + fn provider_transport_analysis_detects_conflicts_and_capability_requirements() { + let cedar_443 = r#" +permit (principal, action == Sandbox::Action::"NetworkConnect", + resource == Sandbox::NetworkEndpoint::"api.example.com:443"); +permit (principal, action == Sandbox::Action::"HttpRequest", + resource == Sandbox::NetworkEndpoint::"api.example.com:443") +when { context.method == "GET" }; +"#; + let analysis = analyze_provider_transports(cedar_443, &HashMap::new()).unwrap(); + assert!(analysis.conflicts.is_empty()); + assert!(analysis.requires_transport_support); + + let partial_plaintext = NetworkEndpoint { + host: "api.example.com".to_string(), + port: 443, + path: "/v1/**".to_string(), + allowed_transports: vec![NetworkTransport::Plaintext as i32], + ..Default::default() + }; + let conflict = + analyze_provider_transports(cedar_443, &provider_rules(vec![partial_plaintext])) + .unwrap(); + assert_eq!(conflict.conflicts.len(), 1); + assert!(conflict.requires_transport_support); + + // Uninspected L4-only Cedar endpoint does not require transport support + // even if an attached provider endpoint declares rest/443. + let l4_only = r#" +permit (principal, action == Sandbox::Action::"NetworkConnect", + resource == Sandbox::NetworkEndpoint::"api.example.com:443"); +"#; + let provider_ep = NetworkEndpoint { + host: "api.example.com".to_string(), + port: 443, + protocol: "rest".to_string(), + provider_credentialed: true, + allowed_transports: vec![NetworkTransport::Tls as i32], + ..Default::default() + }; + let uninspected = + analyze_provider_transports(l4_only, &provider_rules(vec![provider_ep])).unwrap(); + assert!(uninspected.conflicts.is_empty()); + assert!(!uninspected.requires_transport_support); + } +} diff --git a/crates/openshell-policy-cedar-runtime/src/cedar_only/routes.rs b/crates/openshell-policy-cedar-runtime/src/cedar_only/routes.rs index 614762a486..8124eab60f 100644 --- a/crates/openshell-policy-cedar-runtime/src/cedar_only/routes.rs +++ b/crates/openshell-policy-cedar-runtime/src/cedar_only/routes.rs @@ -11,6 +11,7 @@ use std::sync::Arc; use miette::Result; use openshell_core::endpoint_path::path_specificity; use openshell_core::policy_identity::deterministic_policy_hash; +use openshell_core::policy_l7::AllowedTransports; use openshell_core::proto::{ NetworkPolicyRule, NetworkTransport, SandboxPolicy as ProtoSandboxPolicy, }; @@ -127,6 +128,16 @@ impl LoadedPolicy { .build() ); } + let transport_analysis = openshell_policy_cedar_adapter::analyze_engine_provider_transports( + &cedar, + &policy.provider_credential_rules, + ); + if !transport_analysis.conflicts.is_empty() { + return Err(miette::miette!( + "provider credential rules have conflicting endpoint transports with Cedar policy: {}", + transport_analysis.conflicts.join("; ") + )); + } let mut providers = Vec::new(); for rule in policy.provider_credential_rules.values() { for endpoint in &rule.endpoints { @@ -227,12 +238,26 @@ impl LoadedPolicy { let plan = self.route_plan(host, port); let mut configs: Vec<_> = plan.routes.iter().map(|route| plan.build(route)).collect(); // Cedar derives separate request configs for paths on one connection. - // An inspected credentialed path makes TLS the default at its - // authority, while explicit transport selections still have to agree. - if configs - .iter() - .any(|config| config.protocol.l7().is_some() && config.is_credentialed()) - { + // Intersect effective transports across inspected routes so a + // credentialed or TLS-only path tightens default-Both siblings to TLS + // without overriding an explicit plaintext selection. + let mut authority_transports: Option = None; + let mut disjoint = false; + for config in &configs { + if let Ok(Some(allowed)) = config.allowed_transports_for_port(port) { + match authority_transports { + None => authority_transports = Some(allowed), + Some(previous) => match previous.intersect(allowed) { + Some(narrowed) => authority_transports = Some(narrowed), + None => { + disjoint = true; + break; + } + }, + } + } + } + if !disjoint && authority_transports == Some(AllowedTransports::Tls) { for config in &mut configs { if config.protocol.l7().is_some() && config.allowed_transports.is_empty() { config.allowed_transports.push(NetworkTransport::Tls as i32); @@ -444,6 +469,11 @@ impl RoutePlan<'_> { ); if let Some(inspection) = inspection { apply_inspection(&mut config, inspection); + if let Some(provider) = route.provider { + config + .allowed_transports + .clone_from(&provider.allowed_transports); + } } // Every inspected protocol binds grant reporting to the policy // selected before credential acquisition, as the YAML engine does. @@ -772,6 +802,8 @@ struct ProviderEndpoint { ports: Vec, /// The endpoint's `allowed_ips`, empty for none, or why one is invalid. allowed_ips: ProviderRanges, + /// Authored `allowed_transports`, applied only when Cedar inspects the route. + allowed_transports: Vec, /// The endpoint's credential settings, as the L7 config parser reads /// them (see [`provider_config`]). config: EndpointConfig, @@ -800,6 +832,7 @@ impl ProviderEndpoint { host: endpoint.host.to_ascii_lowercase(), ports: connection_ports(endpoint), allowed_ips: parse_provider_allowed_ips(&endpoint.allowed_ips), + allowed_transports: endpoint.allowed_transports.clone(), config: provider_config(endpoint), } } @@ -995,7 +1028,6 @@ fn provider_config(endpoint: &openshell_core::proto::NetworkEndpoint) -> Endpoin .collect(), path: endpoint.path.clone(), tls: TlsSetting::from_proto(endpoint.tls), - allowed_transports: endpoint.allowed_transports.clone(), has_credential_binding: endpoint.credential_binding.is_some(), allow_encoded_slash: endpoint.allow_encoded_slash, websocket_credential_rewrite: endpoint.websocket_credential_rewrite, diff --git a/crates/openshell-policy-cedar-runtime/src/cedar_only/tests.rs b/crates/openshell-policy-cedar-runtime/src/cedar_only/tests.rs index 04149d783f..bb4b3d88e7 100644 --- a/crates/openshell-policy-cedar-runtime/src/cedar_only/tests.rs +++ b/crates/openshell-policy-cedar-runtime/src/cedar_only/tests.rs @@ -1870,6 +1870,118 @@ fn credentialed_cedar_path_sets_tls_default_for_its_authority() { ); } +#[test] +fn uninspected_cedar_provider_route_drops_explicit_allowed_transports() { + use openshell_core::proto::NetworkTransport; + + let mut unrelated = credentialed_endpoint(); + unrelated.path = "/elsewhere/**".to_string(); + unrelated.allowed_transports = vec![NetworkTransport::Tls as i32]; + let engine = CedarOnlyEngine::from_proto(&provider_policy(PATHS_POLICY, vec![unrelated])) + .expect("policy loads"); + let configs = engine + .credential_guards("api.example.com", 443) + .expect("configs build"); + + let uninspected = configs + .iter() + .find(|config| config.path == "/elsewhere/**") + .expect("uninspected provider config"); + assert!(uninspected.allowed_transports.is_empty()); + assert_eq!(uninspected.allowed_transports_for_port(443), Ok(None)); + + // Also verify a host:port permitted only at L4 (no HttpRequest policy). + let l4_cedar = r#" +permit (principal, action == Sandbox::Action::"NetworkConnect", + resource == Sandbox::NetworkEndpoint::"api.example.com:8443"); +"#; + let mut l4_provider = credentialed_endpoint(); + l4_provider.port = 8443; + l4_provider.allowed_transports = vec![NetworkTransport::Tls as i32]; + let l4_engine = CedarOnlyEngine::from_proto(&provider_policy(l4_cedar, vec![l4_provider])) + .expect("L4 policy loads"); + let l4_configs = l4_engine + .credential_guards("api.example.com", 8443) + .expect("L4 configs build"); + assert_eq!(l4_configs.len(), 1); + assert!(l4_configs[0].allowed_transports.is_empty()); + assert_eq!(l4_configs[0].allowed_transports_for_port(8443), Ok(None)); +} + +#[test] +fn provider_plaintext_conflicting_with_cedar_443_default_fails_at_load_time() { + use openshell_core::proto::NetworkTransport; + + // Provider only covers /ws on 443 with plaintext, while Cedar also inspects + // /graphql on 443 (default TLS) -> disjoint at load time. + let mut provider = credentialed_endpoint(); + provider.path = "/ws".to_string(); + provider.port = 443; + provider.allowed_transports = vec![NetworkTransport::Plaintext as i32]; + let error = CedarOnlyEngine::from_proto(&provider_policy(PATHS_POLICY, vec![provider])) + .expect_err("disjoint provider plaintext vs Cedar 443 default must fail at load time"); + assert!( + error + .to_string() + .contains("conflicting endpoint transports"), + "{error:?}" + ); +} + +#[test] +fn provider_plaintext_covering_entire_cedar_443_route_loads_cleanly() { + use openshell_core::policy_l7::AllowedTransports; + use openshell_core::proto::NetworkTransport; + + let cedar = r#" +permit (principal, action == Sandbox::Action::"NetworkConnect", + resource == Sandbox::NetworkEndpoint::"api.example.com:443"); +permit (principal, action == Sandbox::Action::"HttpRequest", + resource == Sandbox::NetworkEndpoint::"api.example.com:443") +when { context.method == "GET" }; +"#; + let mut provider = credentialed_endpoint(); + provider.path.clear(); + provider.port = 443; + provider.allowed_transports = vec![NetworkTransport::Plaintext as i32]; + let engine = CedarOnlyEngine::from_proto(&provider_policy(cedar, vec![provider])) + .expect("full-coverage plaintext provider loads cleanly"); + let configs = engine + .credential_guards("api.example.com", 443) + .expect("configs build"); + assert_eq!(configs.len(), 1); + assert_eq!( + configs[0].allowed_transports_for_port(443), + Ok(Some(AllowedTransports::Plaintext)) + ); +} + +#[test] +fn credentialed_provider_plaintext_on_8443_does_not_stamp_tls_on_cedar_siblings() { + use openshell_core::policy_l7::AllowedTransports; + use openshell_core::proto::NetworkTransport; + + let mut provider = credentialed_endpoint(); + provider.path = "/ws".to_string(); + provider.port = 8443; + provider.allowed_transports = vec![NetworkTransport::Plaintext as i32]; + let cedar = PATHS_POLICY.replace(":443", ":8443"); + let engine = CedarOnlyEngine::from_proto(&provider_policy(&cedar, vec![provider])) + .expect("plaintext credentialed provider on 8443 loads cleanly"); + let configs = engine + .credential_guards("api.example.com", 8443) + .expect("configs build"); + let effective = configs.iter().try_fold(None, |acc, config| { + let next = config.allowed_transports_for_port(8443).unwrap(); + match (acc, next) { + (None, value) => Ok(value), + (value, None) => Ok(value), + (Some(a), Some(b)) => a.intersect(b).map(Some).ok_or(()), + } + }); + assert_eq!(effective, Ok(Some(AllowedTransports::Plaintext))); +} + #[test] fn provider_endpoints_take_the_inspection_of_their_path() { let mut ws = credentialed_endpoint(); diff --git a/crates/openshell-policy/src/lib.rs b/crates/openshell-policy/src/lib.rs index 27ba3ce3ac..6729de1f28 100644 --- a/crates/openshell-policy/src/lib.rs +++ b/crates/openshell-policy/src/lib.rs @@ -13,7 +13,10 @@ mod cedar; #[cfg(feature = "experimental")] -pub use openshell_policy_cedar_adapter::http_endpoint_selectors as cedar_http_endpoint_selectors; +pub use openshell_policy_cedar_adapter::{ + CedarTransportAnalysis, analyze_provider_transports as cedar_analyze_provider_transports, + http_endpoint_selectors as cedar_http_endpoint_selectors, +}; mod compose; pub mod endpoint_status; From e95ddf6c8f70ae426192dbdf3e881f562cacfd30 Mon Sep 17 00:00:00 2001 From: freeqaz Date: Wed, 2 Dec 2026 03:52:28 +0000 Subject: [PATCH 05/11] fix(server): cache effective policy transport analysis and preserve admission errors - Memoize effective-policy ambiguity and transport-capability analysis per canonical policy_hash in ServerState so polling and stream delivery do not repeatedly rebuild Cedar engines or rescan endpoint pairs. - Validate Cedar + provider transport conflicts in both effective-policy write validation (including operator merge writes) and snapshot delivery. - Preserve existing configuration_error diagnostics on unadmitted snapshots instead of overwriting them with ENDPOINT_TRANSPORT_SUPPORT_REQUIRED for legacy supervisors. - Remove the unused cedar_http_endpoint_selectors adapter helper, update existing server capability test fixtures, and remove unused_qualifications warnings. Signed-off-by: freeqaz --- .../openshell-policy-cedar-adapter/src/lib.rs | 13 - crates/openshell-policy/src/lib.rs | 1 - .../src/config_delivery/mod.rs | 6 +- .../src/config_delivery/session.rs | 4 +- crates/openshell-server/src/grpc/policy.rs | 354 ++++++++++++++---- .../src/grpc/policy/endpoint_status_tests.rs | 8 +- crates/openshell-server/src/lib.rs | 5 + 7 files changed, 305 insertions(+), 86 deletions(-) diff --git a/crates/openshell-policy-cedar-adapter/src/lib.rs b/crates/openshell-policy-cedar-adapter/src/lib.rs index a06faaef82..f38481210b 100644 --- a/crates/openshell-policy-cedar-adapter/src/lib.rs +++ b/crates/openshell-policy-cedar-adapter/src/lib.rs @@ -208,19 +208,6 @@ pub fn analyze_provider_transports( Ok(analyze_engine_provider_transports(&engine, provider_rules)) } -/// Derive the host and port selectors of a policy's inspected HTTP endpoints. -/// -/// # Errors -/// Returns an error if the policy cannot be loaded. -pub fn http_endpoint_selectors(source: &str) -> Result> { - let engine = - CedarEngine::from_policy_str(source).map_err(|error| miette::miette!("{error}"))?; - Ok(engine - .configured_l7_endpoints() - .map(|(host, port, _, _)| (host, port)) - .collect()) -} - /// Returns the first inspected `host:port` that `endpoint` selects when it /// sets `tls: skip`. /// diff --git a/crates/openshell-policy/src/lib.rs b/crates/openshell-policy/src/lib.rs index 6729de1f28..d0e76977a9 100644 --- a/crates/openshell-policy/src/lib.rs +++ b/crates/openshell-policy/src/lib.rs @@ -15,7 +15,6 @@ mod cedar; #[cfg(feature = "experimental")] pub use openshell_policy_cedar_adapter::{ CedarTransportAnalysis, analyze_provider_transports as cedar_analyze_provider_transports, - http_endpoint_selectors as cedar_http_endpoint_selectors, }; mod compose; diff --git a/crates/openshell-server/src/config_delivery/mod.rs b/crates/openshell-server/src/config_delivery/mod.rs index 27be802548..3d793dba44 100644 --- a/crates/openshell-server/src/config_delivery/mod.rs +++ b/crates/openshell-server/src/config_delivery/mod.rs @@ -455,7 +455,7 @@ async fn build_sandbox_config( }; match built { Ok((inputs, mut snapshot)) => Ok(Some( - match require_policy_capabilities(&supported_capabilities, snapshot.policy.as_ref()) { + match require_policy_capabilities(state, &supported_capabilities, &snapshot) { Ok(()) => BuiltSandboxConfig::Built(Box::new(inputs), snapshot), Err(error) => { if !reject_unsupported_endpoint_transport(&mut snapshot, &error) { @@ -2027,9 +2027,7 @@ mod tests { provider_environment: bootstrap.and_then(|bootstrap| bootstrap.provider_environment), captured_seq: 0, rebuild: false, - supported_capabilities: vec![ - openshell_core::extension_protocol::POLICY_CEDAR_V1.to_string(), - ], + supported_capabilities: openshell_core::extension_protocol::policy_capabilities(true), }); (harness, record) } diff --git a/crates/openshell-server/src/config_delivery/session.rs b/crates/openshell-server/src/config_delivery/session.rs index 3ab9fcd25e..6cff281b62 100644 --- a/crates/openshell-server/src/config_delivery/session.rs +++ b/crates/openshell-server/src/config_delivery/session.rs @@ -927,7 +927,7 @@ async fn build_config_bootstrap( Err(error) => return Err(error), }; if let Err(error) = - require_policy_capabilities(&supported_capabilities, sandbox_config.policy.as_ref()) + require_policy_capabilities(state, &supported_capabilities, &sandbox_config) { if !reject_unsupported_endpoint_transport(&mut sandbox_config, &error) { sandbox_config = unadmitted_sandbox_config(state, sandbox, &error); @@ -2309,7 +2309,7 @@ BEGIN SELECT RAISE(ABORT, 'database unavailable'); END; let bootstrap = build_config_bootstrap( state, &sandbox, - vec![openshell_core::extension_protocol::POLICY_CEDAR_V1.to_string()], + openshell_core::extension_protocol::policy_capabilities(true), ) .await .unwrap(); diff --git a/crates/openshell-server/src/grpc/policy.rs b/crates/openshell-server/src/grpc/policy.rs index c6ecea675e..ace65475eb 100644 --- a/crates/openshell-server/src/grpc/policy.rs +++ b/crates/openshell-server/src/grpc/policy.rs @@ -54,7 +54,7 @@ use openshell_core::extension_protocol::{ use openshell_core::net::{is_always_blocked_ip, is_internal_ip}; use openshell_core::policy_identity::canonical_rule_bytes; pub use openshell_core::policy_identity::deterministic_policy_hash; -use openshell_core::policy_l7::{AllowedTransports, endpoint_allowed_transports, selector_ports}; +use openshell_core::policy_l7::endpoint_requires_transport_enforcement; #[cfg(test)] use openshell_core::proto::StaticCredentialBinding; use openshell_core::proto::policy_merge_operation; @@ -2139,6 +2139,25 @@ fn validate_endpoint_ambiguities(policy: &ProtoSandboxPolicy) -> Result<(), Stat ))) } +fn validate_effective_policy_ambiguities(policy: &ProtoSandboxPolicy) -> Result<(), Status> { + validate_endpoint_ambiguities(policy)?; + #[cfg(feature = "experimental")] + if policy.is_cedar() { + let cedar = openshell_policy::cedar_analyze_provider_transports( + policy.cedar_source(), + &policy.provider_credential_rules, + ) + .map_err(|_| Status::failed_precondition("stored Cedar policy is invalid"))?; + if !cedar.conflicts.is_empty() { + return Err(Status::failed_precondition(format!( + "network endpoint ambiguity validation failed:\n{}", + cedar.conflicts.join("\n") + ))); + } + } + Ok(()) +} + pub(super) fn validate_candidate_effective_policy( base_policy: &ProtoSandboxPolicy, provider_layers: &[ProviderPolicyLayer], @@ -2148,7 +2167,7 @@ pub(super) fn validate_candidate_effective_policy( } else { compose_effective_policy(base_policy, provider_layers) }; - validate_endpoint_ambiguities(&effective_policy) + validate_effective_policy_ambiguities(&effective_policy) } fn policy_static_credential_endpoint_bindings( @@ -2612,7 +2631,8 @@ pub(super) async fn validate_candidate_sandbox_credential_policy( policy.cloned().unwrap_or_default(), ) .await?; - validate_uninspected_credentialed_endpoints(&effective) + validate_uninspected_credentialed_endpoints(&effective)?; + validate_effective_policy_ambiguities(&effective) } fn truncate_for_log(input: &str, max_chars: usize) -> String { @@ -2900,7 +2920,7 @@ async fn handle_get_sandbox_config_inner( let mut snapshot = build_sandbox_config_snapshot(state, &sandbox).await?; if matches!(principal, Principal::Sandbox(_)) && let Err(error) = - require_policy_capabilities(&req.supported_capabilities, snapshot.policy.as_ref()) + require_policy_capabilities(state, &req.supported_capabilities, &snapshot) && !reject_unsupported_endpoint_transport(&mut snapshot, &error) { return Err(error); @@ -2911,20 +2931,134 @@ async fn handle_get_sandbox_config_inner( const CEDAR_SUPPORT_REQUIRED: &str = "Cedar policy requires a supervisor with Cedar support"; const ENDPOINT_TRANSPORT_SUPPORT_REQUIRED: &str = "Effective policy requires a supervisor with endpoint transport support"; +const EFFECTIVE_POLICY_ANALYSIS_CACHE_CAPACITY: usize = 4_096; + +/// Memoized effective-policy ambiguity and transport-capability analysis, +/// keyed by the canonical policy hash computed after credential stamping. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct EffectivePolicyAnalysis { + pub(crate) ambiguity_error: Option, + pub(crate) requires_endpoint_transport_support: bool, +} + +/// Bounded in-memory cache of [`EffectivePolicyAnalysis`] keyed by +/// `deterministic_policy_hash`. +#[derive(Debug, Default)] +pub(crate) struct EffectivePolicyAnalysisCache { + entries: std::sync::Mutex>, +} + +impl EffectivePolicyAnalysisCache { + pub(crate) fn get_or_compute( + &self, + policy_hash: &str, + compute: impl FnOnce() -> Result, + ) -> Result { + if !policy_hash.is_empty() + && let Some(cached) = self + .entries + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .get(policy_hash) + .cloned() + { + return Ok(cached); + } + let computed = compute()?; + if !policy_hash.is_empty() { + let mut guard = self + .entries + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + if guard.len() >= EFFECTIVE_POLICY_ANALYSIS_CACHE_CAPACITY { + guard.clear(); + } + guard.insert(policy_hash.to_string(), computed.clone()); + } + Ok(computed) + } +} + +fn analyze_effective_policy( + state: &ServerState, + policy_hash: &str, + policy: &ProtoSandboxPolicy, +) -> Result { + let owned_hash; + let key = if policy_hash.is_empty() { + owned_hash = deterministic_policy_hash(policy); + owned_hash.as_str() + } else { + policy_hash + }; + state + .effective_policy_analysis + .get_or_compute(key, || compute_effective_policy_analysis(policy)) +} + +fn compute_effective_policy_analysis( + policy: &ProtoSandboxPolicy, +) -> Result { + if policy.is_cedar() { + #[cfg(feature = "experimental")] + { + let cedar = openshell_policy::cedar_analyze_provider_transports( + policy.cedar_source(), + &policy.provider_credential_rules, + ) + .map_err(|_| Status::failed_precondition("stored Cedar policy is invalid"))?; + let ambiguity_error = (!cedar.conflicts.is_empty()).then(|| { + format!( + "network endpoint ambiguity validation failed:\n{}", + cedar.conflicts.join("\n") + ) + }); + return Ok(EffectivePolicyAnalysis { + ambiguity_error, + requires_endpoint_transport_support: cedar.requires_transport_support, + }); + } + #[cfg(not(feature = "experimental"))] + return Ok(EffectivePolicyAnalysis { + ambiguity_error: None, + requires_endpoint_transport_support: false, + }); + } + + let ambiguity_error = validate_endpoint_ambiguities(policy) + .err() + .map(|error| error.message().to_string()); + let requires_endpoint_transport_support = policy + .network_policies + .values() + .chain(policy.provider_credential_rules.values()) + .flat_map(|rule| &rule.endpoints) + .chain(&policy.endpoint_settings) + .any(endpoint_requires_transport_enforcement); + Ok(EffectivePolicyAnalysis { + ambiguity_error, + requires_endpoint_transport_support, + }) +} /// Refuse policies the supervisor cannot enforce. pub fn require_policy_capabilities( + state: &ServerState, supported_capabilities: &[String], - policy: Option<&ProtoSandboxPolicy>, + snapshot: &SandboxConfigSnapshot, ) -> Result<(), Status> { - let Some(policy) = policy else { + let Some(policy) = snapshot.policy.as_ref() else { return Ok(()); }; if policy.is_cedar() && !has_capability(supported_capabilities, POLICY_CEDAR_V1) { return Err(Status::unimplemented(CEDAR_SUPPORT_REQUIRED)); } - if !has_capability(supported_capabilities, POLICY_ENDPOINT_TRANSPORTS_V1) - && requires_endpoint_transport_support(policy)? + // Preserve any existing admission failure diagnostic rather than + // overwriting it with a transport-capability refusal. + if snapshot.configuration_admitted + && !has_capability(supported_capabilities, POLICY_ENDPOINT_TRANSPORTS_V1) + && analyze_effective_policy(state, &snapshot.policy_hash, policy)? + .requires_endpoint_transport_support { return Err(Status::unimplemented(ENDPOINT_TRANSPORT_SUPPORT_REQUIRED)); } @@ -2958,45 +3092,6 @@ pub fn reject_unsupported_endpoint_transport( true } -fn requires_endpoint_transport_support(policy: &ProtoSandboxPolicy) -> Result { - let endpoint_requires_transport_support = |endpoint: &NetworkEndpoint| { - !endpoint.allowed_transports.is_empty() - || selector_ports(endpoint).iter().any(|&port| { - endpoint_allowed_transports(endpoint, port) == Some(AllowedTransports::Tls) - }) - }; - if policy - .network_policies - .values() - .chain(policy.provider_credential_rules.values()) - .flat_map(|rule| &rule.endpoints) - .chain(&policy.endpoint_settings) - .any(endpoint_requires_transport_support) - { - return Ok(true); - } - #[cfg(feature = "experimental")] - if policy.is_cedar() { - // Cedar derives HTTP inspection from its source, including on a - // provider endpoint whose own protocol need not be HTTP. - let inspections = openshell_policy::cedar_http_endpoint_selectors(policy.cedar_source()) - .map_err(|_| Status::failed_precondition("stored Cedar policy is invalid"))?; - return Ok(inspections.into_iter().any(|(host, port)| { - port == 443 - || policy - .provider_credential_rules - .values() - .flat_map(|rule| &rule.endpoints) - .any(|endpoint| { - openshell_core::policy_l7::endpoint_is_credentialed(endpoint) - && selector_ports(endpoint).contains(&u32::from(port)) - && host_patterns_overlap(&endpoint.host, &host).unwrap_or(false) - }) - })); - } - Ok(false) -} - /// 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( @@ -3156,13 +3251,15 @@ async fn build_sandbox_config_snapshot_with_sources( if matches!(policy_source, PolicySource::Global) { openshell_core::policy_identity::stamp_global_token_grant_owners(effective_policy); } + policy_hash = deterministic_policy_hash(effective_policy); if let Err(error) = validate_uninspected_credentialed_endpoints(effective_policy) { configuration_error = bounded_configuration_diagnostic(error.message()); - } else if let Err(error) = validate_endpoint_ambiguities(effective_policy) { + } else if let Some(error) = + analyze_effective_policy(state, &policy_hash, effective_policy)?.ambiguity_error + { // Credential provenance can change a route's transport default. - configuration_error = bounded_configuration_diagnostic(error.message()); + configuration_error = bounded_configuration_diagnostic(&error); } - policy_hash = deterministic_policy_hash(effective_policy); } if let Some(policy) = policy.as_ref() { @@ -7907,7 +8004,8 @@ fn validate_operator_merged_credential_policy( // Recompute the credential flags without clearing owner IDs that provider // composition already derived for this effective policy. stamp_provider_credentialed_endpoints(effective_policy, &credentialed_scopes); - validate_uninspected_credentialed_endpoints(effective_policy) + validate_uninspected_credentialed_endpoints(effective_policy)?; + validate_effective_policy_ambiguities(effective_policy) } fn stage_validated_merge_operation( @@ -9698,7 +9796,7 @@ mod tests { workspace_scope: Some(openshell_core::proto::workspace_selector( "default".to_string(), )), - ..Default::default() + supported_capabilities: policy_capabilities(false), }), sandbox_id, ), @@ -10013,7 +10111,7 @@ mod tests { Request::new(GetSandboxConfigRequest { name: sandbox_id.to_string(), workspace_scope: None, - ..Default::default() + supported_capabilities: policy_capabilities(false), }), sandbox_id, ), @@ -10078,7 +10176,7 @@ mod tests { Request::new(GetSandboxConfigRequest { name: sandbox_id.clone(), workspace_scope: None, - ..Default::default() + supported_capabilities: policy_capabilities(false), }), &sandbox_id, ), @@ -10347,7 +10445,7 @@ mod tests { Request::new(GetSandboxConfigRequest { name: sandbox_id.to_string(), workspace_scope: None, - ..Default::default() + supported_capabilities: policy_capabilities(false), }), sandbox_id, ), @@ -10417,7 +10515,7 @@ mod tests { Request::new(GetSandboxConfigRequest { name: sandbox_id.to_string(), workspace_scope: None, - ..Default::default() + supported_capabilities: policy_capabilities(false), }), sandbox_id, ), @@ -13540,7 +13638,7 @@ mod tests { Request::new(GetSandboxConfigRequest { name: "cedar-compat".to_string(), supported_capabilities: openshell_core::extension_protocol::capabilities_if( - openshell_core::extension_protocol::POLICY_CEDAR_V1, + POLICY_CEDAR_V1, supported, ), ..Default::default() @@ -13649,6 +13747,64 @@ mod tests { } } + #[tokio::test] + async fn unadmitted_snapshot_preserves_existing_error_for_legacy_supervisor() { + let state = test_server_state().await; + let mut policy = test_policy_with_rule("base", "api.example.com"); + let endpoint = &mut policy.network_policies.get_mut("base").unwrap().endpoints[0]; + endpoint.protocol = "rest".to_string(); + endpoint.access = openshell_core::proto::NetworkAccessPreset::Full as i32; + endpoint.port = 443; + let snapshot = SandboxConfigSnapshot { + policy: Some(policy), + configuration_admitted: false, + configuration_error: "existing admission failure".to_string(), + ..Default::default() + }; + require_policy_capabilities(&state, &[], &snapshot) + .expect("unadmitted snapshot must preserve its existing diagnostic"); + } + + #[test] + fn effective_policy_analysis_cache_memoizes_by_policy_hash() { + let cache = EffectivePolicyAnalysisCache::default(); + let mut calls = 0usize; + let expected = EffectivePolicyAnalysis { + ambiguity_error: None, + requires_endpoint_transport_support: true, + }; + let first = cache + .get_or_compute("hash-a", || { + calls += 1; + Ok(expected.clone()) + }) + .unwrap(); + let second = cache + .get_or_compute("hash-a", || { + calls += 1; + Ok(EffectivePolicyAnalysis { + ambiguity_error: Some("should not recompute".to_string()), + requires_endpoint_transport_support: false, + }) + }) + .unwrap(); + assert_eq!(calls, 1); + assert_eq!(first, expected); + assert_eq!(second, expected); + + let third = cache + .get_or_compute("hash-b", || { + calls += 1; + Ok(EffectivePolicyAnalysis { + ambiguity_error: None, + requires_endpoint_transport_support: false, + }) + }) + .unwrap(); + assert_eq!(calls, 2); + assert!(!third.requires_endpoint_transport_support); + } + #[cfg(feature = "experimental")] #[test] fn cedar_endpoint_transport_detection_uses_derived_inspection() { @@ -13679,12 +13835,86 @@ when {{ context.method == "GET" }};"# policy.provider_credential_rules = provider.network_policies; } assert_eq!( - requires_endpoint_transport_support(&policy).unwrap(), + compute_effective_policy_analysis(&policy) + .unwrap() + .requires_endpoint_transport_support, requires_support ); } } + #[cfg(feature = "experimental")] + #[test] + fn cedar_uninspected_l4_endpoint_with_provider_does_not_require_transport_support() { + use openshell_core::proto::NetworkTransport; + + let mut provider = test_policy_with_rule("provider", "api.example.com"); + let endpoint = &mut provider + .network_policies + .get_mut("provider") + .unwrap() + .endpoints[0]; + endpoint.port = 443; + endpoint.protocol = "rest".to_string(); + endpoint.provider_credentialed = true; + endpoint.allowed_transports = vec![NetworkTransport::Tls as i32]; + + let policy = ProtoSandboxPolicy { + cedar_policy: Some(openshell_core::proto::CedarPolicy { + source: r#"permit (principal, action == Sandbox::Action::"NetworkConnect", + resource == Sandbox::NetworkEndpoint::"api.example.com:443");"# + .to_string(), + }), + provider_credential_rules: provider.network_policies, + ..Default::default() + }; + + let analysis = compute_effective_policy_analysis(&policy).unwrap(); + assert!(analysis.ambiguity_error.is_none(), "{analysis:?}"); + assert!(!analysis.requires_endpoint_transport_support); + } + + #[cfg(feature = "experimental")] + #[test] + fn cedar_provider_plaintext_conflict_on_443_is_rejected() { + use openshell_core::proto::NetworkTransport; + + let mut provider = test_policy_with_rule("provider", "api.example.com"); + let endpoint = &mut provider + .network_policies + .get_mut("provider") + .unwrap() + .endpoints[0]; + endpoint.port = 443; + endpoint.path = "/v1/**".to_string(); + endpoint.allowed_transports = vec![NetworkTransport::Plaintext as i32]; + + let policy = ProtoSandboxPolicy { + cedar_policy: Some(openshell_core::proto::CedarPolicy { + source: r#"permit (principal, action == Sandbox::Action::"NetworkConnect", + resource == Sandbox::NetworkEndpoint::"api.example.com:443"); +permit (principal, action == Sandbox::Action::"HttpRequest", + resource == Sandbox::NetworkEndpoint::"api.example.com:443") +when { context.method == "GET" };"# + .to_string(), + }), + provider_credential_rules: provider.network_policies, + ..Default::default() + }; + + let analysis = compute_effective_policy_analysis(&policy).unwrap(); + assert!( + analysis + .ambiguity_error + .as_deref() + .is_some_and(|message| message.contains("plaintext")), + "{analysis:?}" + ); + let err = validate_effective_policy_ambiguities(&policy) + .expect_err("Cedar + partial plaintext provider on 443 must fail validation"); + assert_eq!(err.code(), Code::FailedPrecondition); + } + #[cfg(feature = "experimental")] #[tokio::test] async fn sandbox_config_delivers_provider_rules_separately_for_a_cedar_policy() { @@ -14871,9 +15101,7 @@ when {{ context.method == "GET" }};"# with_sandbox( Request::new(GetSandboxConfigRequest { name: "invalid-legacy".to_string(), - supported_capabilities: vec![ - openshell_core::extension_protocol::POLICY_CEDAR_V1.to_string(), - ], + supported_capabilities: vec![POLICY_CEDAR_V1.to_string()], workspace_scope: Some(openshell_core::proto::workspace_selector("default")), }), "sb-invalid-legacy", @@ -24224,9 +24452,7 @@ when {{ context.method == "GET" }};"# let request = || { Request::new(GetSandboxConfigRequest { name: "cedar".to_string(), - supported_capabilities: vec![ - openshell_core::extension_protocol::POLICY_CEDAR_V1.to_string(), - ], + supported_capabilities: vec![POLICY_CEDAR_V1.to_string()], workspace_scope: Some(openshell_core::proto::workspace_selector("default")), }) }; diff --git a/crates/openshell-server/src/grpc/policy/endpoint_status_tests.rs b/crates/openshell-server/src/grpc/policy/endpoint_status_tests.rs index aaa9108cf9..2c88e5501d 100644 --- a/crates/openshell-server/src/grpc/policy/endpoint_status_tests.rs +++ b/crates/openshell-server/src/grpc/policy/endpoint_status_tests.rs @@ -599,7 +599,9 @@ async fn report_endpoint_status_rejects_stale_configuration_epoch() { Request::new(GetSandboxConfigRequest { name: sandbox_id.to_string(), workspace_scope: None, - ..Default::default() + supported_capabilities: openshell_core::extension_protocol::policy_capabilities( + false, + ), }), sandbox_id, ), @@ -2124,7 +2126,9 @@ async fn report_endpoint_status_is_session_bound_and_retry_idempotent() { Request::new(GetSandboxConfigRequest { name: sandbox_id.to_string(), workspace_scope: None, - ..Default::default() + supported_capabilities: openshell_core::extension_protocol::policy_capabilities( + false, + ), }), sandbox_id, ), diff --git a/crates/openshell-server/src/lib.rs b/crates/openshell-server/src/lib.rs index 8edc7adc6b..3fbaf367fc 100644 --- a/crates/openshell-server/src/lib.rs +++ b/crates/openshell-server/src/lib.rs @@ -457,6 +457,10 @@ pub struct ServerState { pub(crate) sandbox_identity: Option>>, + /// Memoized effective-policy ambiguity and transport-capability analysis + /// keyed by `deterministic_policy_hash`. + pub(crate) effective_policy_analysis: grpc::policy::EffectivePolicyAnalysisCache, + /// OIDC admin role name for workspace-level authorization. /// Empty when OIDC is not configured — `authorize_workspace()` treats /// every authenticated user as Platform Admin in that case. @@ -724,6 +728,7 @@ impl ServerState { provider_profile_sources: provider_profile_sources::ProviderProfileSources::with_default_sources(), sandbox_identity, + effective_policy_analysis: grpc::policy::EffectivePolicyAnalysisCache::default(), admin_role, }) } From 4c77515629e7a3a1619c5d61e9f001b24ec977d0 Mon Sep 17 00:00:00 2001 From: freeqaz Date: Wed, 2 Dec 2026 03:52:48 +0000 Subject: [PATCH 06/11] docs(policy): clarify upgrade order, transport intersection, and transparent TCP fail-close Signed-off-by: freeqaz --- docs/how-it-works/policies/network-rules.mdx | 22 ++++++++++++++------ docs/how-it-works/policies/schema.mdx | 8 ++++--- 2 files changed, 21 insertions(+), 9 deletions(-) diff --git a/docs/how-it-works/policies/network-rules.mdx b/docs/how-it-works/policies/network-rules.mdx index 17f9f8d80c..b7d5db4d3f 100644 --- a/docs/how-it-works/policies/network-rules.mdx +++ b/docs/how-it-works/policies/network-rules.mdx @@ -153,14 +153,21 @@ on any port where the endpoint uses provider credentials, a credential binding, or request signing. Other inspected HTTP endpoints accept both transports. The default applies separately to each port in `ports`. -Upgrade the gateway and supervisors before relying on this field. An older -gateway cannot preserve the new field. An upgraded gateway refuses to deliver -a policy that requires transport enforcement to an incompatible supervisor. +Upgrade supervisors before upgrading the gateway. The default TLS-only rule on +port 443 and credentialed endpoints requires supervisor transport enforcement +even when `allowed_transports` is omitted. During a gateway-first rolling +upgrade, any sandbox whose effective policy contains an inspected HTTP endpoint +on port 443, a credentialed inspected HTTP endpoint, or an explicit +`allowed_transports` list receives a fail-closed unadmitted configuration until +its supervisor is upgraded. Older gateways also cannot preserve explicit +`allowed_transports` fields. When upgrading, check clients that send plaintext to those endpoints. Allow `plaintext` explicitly only if the route is trusted to carry the request and any credentials it uses without encryption. A failed TLS handshake never -retries in plaintext. Transport restrictions apply even in `audit` mode. +retries in plaintext. Transport restrictions apply even in `audit` mode, and +inspected HTTP endpoints fail closed on the raw transparent TCP path instead of +bypassing HTTP/TLS inspection. Use this field with `rest`, `graphql`, `websocket`, `json-rpc`, or `mcp`. Native TCP and opaque `tls: skip` rules keep their existing behavior and do @@ -214,8 +221,11 @@ matching deny rule takes precedence over any allow, regardless of where either appears in the file. If one matching rule inspects requests and another does not, OpenShell inspects the connection, and the rule without `protocol` adds no request access. Endpoints that can match the same host and port must also agree -on settings such as `tls` and `allowed_ips`. Inspected HTTP endpoints must agree -on the effective transports for each shared port, even across different paths. +on settings such as `tls` and `allowed_ips`. Inspected HTTP endpoints that +overlap on the same host and port intersect their effective transports (for +example, a credentialed or `tls`-only endpoint tightens a shared port to TLS), +while disjoint transport sets (`[tls]` versus `[plaintext]`) and mixing `sql` +with inspected HTTP on the same host and port are rejected. For example, suppose one rule allows `GET /repos/**` on a host and another rule for the same host, port, and binary denies `GET /repos/private/**`. OpenShell diff --git a/docs/how-it-works/policies/schema.mdx b/docs/how-it-works/policies/schema.mdx index f23a636e65..6bd1522567 100644 --- a/docs/how-it-works/policies/schema.mdx +++ b/docs/how-it-works/policies/schema.mdx @@ -227,9 +227,11 @@ OpenShell rejects an endpoint that breaks these rules: signing, or protocol options. - 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 HTTP endpoints must allow the same transports on each shared port. - Inspected endpoints that can match the same request must also agree on - `protocol`, `enforcement`, and credential settings. + Inspected HTTP endpoints that overlap on the same host and port must have + compatible effective transports (their intersection applies; disjoint `[tls]` + and `[plaintext]` sets are rejected), and `sql` cannot share a host and port + with inspected HTTP endpoints. Inspected endpoints that can match the same + request must also agree on `protocol`, `enforcement`, and credential settings. Without `protocol`, `access` and `rules` have no effect. From 047b6c71f413bf08f9a51051dcf33cc9df7cf1a9 Mon Sep 17 00:00:00 2001 From: freeqaz Date: Wed, 2 Dec 2026 04:01:21 +0000 Subject: [PATCH 07/11] chore: resolve clippy lints in transport deserialization, policy, and tests - Replace BTreeMap in deserialize_credential_binding with a zero-allocation serde Visitor to satisfy clippy::zero_sized_map_values. - Clean up redundant_clone, single_match_else, match_same_arms, useless_let_if_seq, redundant_pub_crate, needless_raw_string_hashes, and iter_on_single_items lints across modified crates and tests. Signed-off-by: freeqaz --- .../src/cedar_only/routes.rs | 9 ++--- .../src/cedar_only/tests.rs | 3 +- .../src/policy_types.rs | 35 ++++++++++++++++++- crates/openshell-policy/src/ambiguity.rs | 5 +-- crates/openshell-server/src/grpc/policy.rs | 10 +++--- .../openshell-supervisor-network/src/proxy.rs | 9 ++--- .../src/proxy/transport_tests.rs | 17 +++++---- 7 files changed, 59 insertions(+), 29 deletions(-) diff --git a/crates/openshell-policy-cedar-runtime/src/cedar_only/routes.rs b/crates/openshell-policy-cedar-runtime/src/cedar_only/routes.rs index 8124eab60f..00b31cabf6 100644 --- a/crates/openshell-policy-cedar-runtime/src/cedar_only/routes.rs +++ b/crates/openshell-policy-cedar-runtime/src/cedar_only/routes.rs @@ -247,13 +247,14 @@ impl LoadedPolicy { if let Ok(Some(allowed)) = config.allowed_transports_for_port(port) { match authority_transports { None => authority_transports = Some(allowed), - Some(previous) => match previous.intersect(allowed) { - Some(narrowed) => authority_transports = Some(narrowed), - None => { + Some(previous) => { + if let Some(narrowed) = previous.intersect(allowed) { + authority_transports = Some(narrowed); + } else { disjoint = true; break; } - }, + } } } } diff --git a/crates/openshell-policy-cedar-runtime/src/cedar_only/tests.rs b/crates/openshell-policy-cedar-runtime/src/cedar_only/tests.rs index bb4b3d88e7..2ae629ff77 100644 --- a/crates/openshell-policy-cedar-runtime/src/cedar_only/tests.rs +++ b/crates/openshell-policy-cedar-runtime/src/cedar_only/tests.rs @@ -1974,8 +1974,7 @@ fn credentialed_provider_plaintext_on_8443_does_not_stamp_tls_on_cedar_siblings( let effective = configs.iter().try_fold(None, |acc, config| { let next = config.allowed_transports_for_port(8443).unwrap(); match (acc, next) { - (None, value) => Ok(value), - (value, None) => Ok(value), + (None, value) | (value, None) => Ok(value), (Some(a), Some(b)) => a.intersect(b).map(Some).ok_or(()), } }); diff --git a/crates/openshell-policy-runtime-interface/src/policy_types.rs b/crates/openshell-policy-runtime-interface/src/policy_types.rs index d65271fbb7..72d0eee086 100644 --- a/crates/openshell-policy-runtime-interface/src/policy_types.rs +++ b/crates/openshell-policy-runtime-interface/src/policy_types.rs @@ -327,7 +327,40 @@ fn deserialize_allowed_transports<'de, D: Deserializer<'de>>( fn deserialize_credential_binding<'de, D: Deserializer<'de>>( deserializer: D, ) -> std::result::Result { - Ok(Option::>::deserialize(deserializer)?.is_some()) + struct OptionalMapVisitor; + + impl<'de> serde::de::Visitor<'de> for OptionalMapVisitor { + type Value = bool; + + fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str("a credential_binding mapping or null") + } + + fn visit_none(self) -> std::result::Result { + Ok(false) + } + + fn visit_unit(self) -> std::result::Result { + Ok(false) + } + + fn visit_some>( + self, + deserializer: D, + ) -> std::result::Result { + deserializer.deserialize_map(self) + } + + fn visit_map>( + self, + mut map: A, + ) -> std::result::Result { + while map.next_entry::()?.is_some() {} + Ok(true) + } + } + + deserializer.deserialize_option(OptionalMapVisitor) } /// One policy endpoint as policy DNS reads it: its host selector, ports, diff --git a/crates/openshell-policy/src/ambiguity.rs b/crates/openshell-policy/src/ambiguity.rs index 138a3101af..0fa0620528 100644 --- a/crates/openshell-policy/src/ambiguity.rs +++ b/crates/openshell-policy/src/ambiguity.rs @@ -822,10 +822,7 @@ mod tests { let mut sibling = endpoint("api.example.com", 8443); sibling.protocol = "rest".into(); sibling.path = "/public/**".into(); - assert!( - find_endpoint_ambiguities(&policy_with(credentialed.clone(), sibling.clone())) - .is_empty() - ); + assert!(find_endpoint_ambiguities(&policy_with(credentialed.clone(), sibling)).is_empty()); // Explicit [tls] with a broader default-Both rule also intersects to TLS. let mut wildcard = endpoint("*.example.com", 0); diff --git a/crates/openshell-server/src/grpc/policy.rs b/crates/openshell-server/src/grpc/policy.rs index ace65475eb..e211e4fac8 100644 --- a/crates/openshell-server/src/grpc/policy.rs +++ b/crates/openshell-server/src/grpc/policy.rs @@ -2936,20 +2936,20 @@ const EFFECTIVE_POLICY_ANALYSIS_CACHE_CAPACITY: usize = 4_096; /// Memoized effective-policy ambiguity and transport-capability analysis, /// keyed by the canonical policy hash computed after credential stamping. #[derive(Debug, Clone, PartialEq, Eq)] -pub(crate) struct EffectivePolicyAnalysis { - pub(crate) ambiguity_error: Option, - pub(crate) requires_endpoint_transport_support: bool, +pub struct EffectivePolicyAnalysis { + pub ambiguity_error: Option, + pub requires_endpoint_transport_support: bool, } /// Bounded in-memory cache of [`EffectivePolicyAnalysis`] keyed by /// `deterministic_policy_hash`. #[derive(Debug, Default)] -pub(crate) struct EffectivePolicyAnalysisCache { +pub struct EffectivePolicyAnalysisCache { entries: std::sync::Mutex>, } impl EffectivePolicyAnalysisCache { - pub(crate) fn get_or_compute( + pub fn get_or_compute( &self, policy_hash: &str, compute: impl FnOnce() -> Result, diff --git a/crates/openshell-supervisor-network/src/proxy.rs b/crates/openshell-supervisor-network/src/proxy.rs index 056f74e3f6..93df1ebcd8 100644 --- a/crates/openshell-supervisor-network/src/proxy.rs +++ b/crates/openshell-supervisor-network/src/proxy.rs @@ -3493,8 +3493,7 @@ async fn handle_mediated_connection( } } - let mut pre_dial_protocol = None; - if let Some(transports) = allowed_transports { + let pre_dial_protocol = if let Some(transports) = allowed_transports { // Clients send the tunnel payload only after this acknowledgement. // Classify before dialing so a transport refusal cannot reach the origin. respond(&mut client, b"HTTP/1.1 200 Connection Established\r\n\r\n").await?; @@ -3570,8 +3569,10 @@ async fn handle_mediated_connection( return Ok(()); } client = replay_tunnel_prefix(client, prefix); - pre_dial_protocol = Some(protocol); - } + Some(protocol) + } else { + None + }; let dial_span = egress::dial_span(&connect_span); let upstream_result = tokio::select! { diff --git a/crates/openshell-supervisor-network/src/proxy/transport_tests.rs b/crates/openshell-supervisor-network/src/proxy/transport_tests.rs index 7ff2b01ef9..c6a18be121 100644 --- a/crates/openshell-supervisor-network/src/proxy/transport_tests.rs +++ b/crates/openshell-supervisor-network/src/proxy/transport_tests.rs @@ -28,7 +28,7 @@ async fn proxy_connection( upstream_proxy: Option, ) -> (TcpStream, JoinHandle>) { let policy = policy_with_native_executable_paths(&format!( - r#" + r" network_policies: api: name: api @@ -41,7 +41,7 @@ network_policies: - allow: {{ method: GET, path: /status }} binaries: - path: /usr/bin/test-client -"#, +", )); let engine = Arc::new( OpaEngine::from_strings(include_str!("../../data/sandbox-policy.rego"), &policy) @@ -63,11 +63,10 @@ network_policies: let (server, peer) = listener.accept().await.unwrap(); let addresses = Some((peer, server.local_addr().unwrap())); let (_, resolver) = SecretResolver::from_provider_env( - [( + std::iter::once(( "TRANSPORT_TEST_TOKEN".to_string(), "test-origin-token".to_string(), - )] - .into_iter() + )) .collect(), ); let task = tokio::spawn(Box::pin(handle_mediated_connection( @@ -392,7 +391,7 @@ async fn mixed_transports_never_fall_back_to_an_opaque_tunnel() { async fn credentialed_sibling_intersects_to_tls_across_paths() { let port = 8443; let policy = policy_with_native_executable_paths(&format!( - r#" + r" network_policies: auth_api: name: auth_api @@ -419,7 +418,7 @@ network_policies: - allow: {{ method: GET, path: /status }} binaries: - path: /usr/bin/test-client -"#, +", )); let engine = Arc::new( OpaEngine::from_strings(include_str!("../../data/sandbox-policy.rego"), &policy) @@ -492,7 +491,7 @@ fn raw_transparent_tcp_fails_closed_for_inspected_http_endpoints() { (8443, " tls: skip\n", false), ] { let policy = policy_with_native_executable_paths(&format!( - r#" + r" network_policies: api: name: api @@ -501,7 +500,7 @@ network_policies: port: {port} {endpoint_yaml} binaries: - path: /usr/bin/test-client -"#, +", )); let engine: PolicyEngine = Arc::new( OpaEngine::from_strings(include_str!("../../data/sandbox-policy.rego"), &policy) From 70fb64b1d1296aee2aeda63aa69a8a5b19ab1d0f Mon Sep 17 00:00:00 2001 From: freeqaz Date: Wed, 2 Dec 2026 09:12:58 +0000 Subject: [PATCH 08/11] refactor(policy): replace allowed_transports list with scalar transport field - Replace repeated NetworkTransport allowed_transports with a single scalar NetworkTransport transport field (tls | plaintext) on NetworkEndpoint in proto, YAML/JSON schema, provider profiles, Rego/OPA data, Cedar runtime, merge/ambiguity validators, CLI provider details, prover, e2e, and test suites. - Preserve existing defaults when omitted: port 443 and credentialed inspected HTTP endpoints require TLS; other uncredentialed inspected HTTP endpoints continue to accept either TLS or plaintext. - Eliminate dual-transport list authoring on a single rule (making plaintext opt-in explicit and avoiding https/wss naming mismatch on WebSocket and future non-HTTP protocols). - Update reviewed storage_proto schema SHA-256 fingerprints. Signed-off-by: freeqaz --- crates/openshell-cli/src/commands/provider.rs | 17 +- .../openshell-core/src/extension_protocol.rs | 2 +- crates/openshell-core/src/policy_l7.rs | 86 ++++----- .../openshell-policy-cedar-adapter/src/lib.rs | 10 +- .../src/cedar_only/routes.rs | 16 +- .../src/cedar_only/tests.rs | 19 +- .../src/policy_data.rs | 14 +- .../src/policy_types.rs | 25 ++- crates/openshell-policy-schema/src/lib.rs | 41 +---- crates/openshell-policy/src/ambiguity.rs | 15 +- crates/openshell-policy/src/lib.rs | 167 ++++++++---------- crates/openshell-policy/src/merge.rs | 89 ++++------ crates/openshell-prover/src/containment.rs | 10 +- crates/openshell-providers/src/profiles.rs | 76 ++++---- crates/openshell-server/src/grpc/policy.rs | 12 +- crates/openshell-server/src/storage_proto.rs | 17 +- .../data/sandbox-policy.rego | 2 +- .../src/opa/raw_schema.rs | 12 +- .../src/policy_local.rs | 2 +- .../openshell-supervisor-network/src/proxy.rs | 8 +- .../src/proxy/transport_tests.rs | 28 ++- e2e/python/test_sandbox_providers.py | 2 +- .../tests/kubernetes_shared_supervisor.rs | 4 +- .../kubernetes_shared_supervisor_spiffe.rs | 2 +- e2e/rust/tests/provider_readiness.rs | 2 +- .../tests/stable_external_placeholders.rs | 2 +- .../tests/support/provider_refresh_handles.rs | 4 +- proto/sandbox.proto | 18 +- .../conformance/src/credential_gating.rs | 20 +-- .../tests/token_exchange.rs | 7 +- 30 files changed, 308 insertions(+), 421 deletions(-) diff --git a/crates/openshell-cli/src/commands/provider.rs b/crates/openshell-cli/src/commands/provider.rs index 7729e69226..9535b39fd9 100644 --- a/crates/openshell-cli/src/commands/provider.rs +++ b/crates/openshell-cli/src/commands/provider.rs @@ -2705,7 +2705,7 @@ fn format_provider_profile_details(profile: &ProviderProfile) -> String { // The gateway derives credential provenance when it attaches the profile. let mut declared = endpoint.clone(); declared.provider_credentialed = credentialed; - let source = if endpoint.allowed_transports.is_empty() { + let source = if endpoint.transport == 0 { " (default)" } else { "" @@ -2719,10 +2719,7 @@ fn format_provider_profile_details(profile: &ProviderProfile) -> String { AllowedTransports::Plaintext => "plaintext", AllowedTransports::Both => "tls, plaintext", }; - let _ = writeln!( - rendered, - " Allowed transports on {port}: {label}{source}" - ); + let _ = writeln!(rendered, " Transport on {port}: {label}{source}"); } let _ = writeln!( rendered, @@ -3206,12 +3203,12 @@ mod tests { ..Default::default() }; let text = format_provider_profile_details(&profile); - assert!(text.contains("Allowed transports on 443: tls (default)")); - assert!(text.contains("Allowed transports on 8443: tls, plaintext (default)")); - profile.endpoints[0].allowed_transports = vec![NetworkTransport::Plaintext as i32]; + assert!(text.contains("Transport on 443: tls (default)")); + assert!(text.contains("Transport on 8443: tls, plaintext (default)")); + profile.endpoints[0].transport = NetworkTransport::Plaintext as i32; let text = format_provider_profile_details(&profile); - assert!(text.contains("Allowed transports on 443: plaintext\n")); - assert!(text.contains("Allowed transports on 8443: plaintext\n")); + assert!(text.contains("Transport on 443: plaintext\n")); + assert!(text.contains("Transport on 8443: plaintext\n")); } #[test] diff --git a/crates/openshell-core/src/extension_protocol.rs b/crates/openshell-core/src/extension_protocol.rs index bc9cfef118..94205a5879 100644 --- a/crates/openshell-core/src/extension_protocol.rs +++ b/crates/openshell-core/src/extension_protocol.rs @@ -15,7 +15,7 @@ pub const PROTOCOL_MINOR: u32 = 0; /// Policy format implemented by a peer's registered Cedar backend. pub const POLICY_CEDAR_V1: &str = "openshell.policy.cedar.v1"; -/// Peer enforces endpoint transport allowlists and transport defaults. +/// Peer enforces explicit endpoint transport settings and transport defaults. pub const POLICY_ENDPOINT_TRANSPORTS_V1: &str = "openshell.policy.endpoint-transports.v1"; /// Policy capabilities advertised by a supervisor build. diff --git a/crates/openshell-core/src/policy_l7.rs b/crates/openshell-core/src/policy_l7.rs index b3438b484b..e77f85fda7 100644 --- a/crates/openshell-core/src/policy_l7.rs +++ b/crates/openshell-core/src/policy_l7.rs @@ -62,6 +62,7 @@ impl AllowedTransports { pub fn network_transport_from_str(value: &str) -> Option { match value { + "" => Some(NetworkTransport::Unspecified), "tls" => Some(NetworkTransport::Tls), "plaintext" => Some(NetworkTransport::Plaintext), _ => None, @@ -70,9 +71,9 @@ pub fn network_transport_from_str(value: &str) -> Option { pub fn network_transport_to_str(value: i32) -> Option<&'static str> { match NetworkTransport::try_from(value).ok()? { + NetworkTransport::Unspecified => Some(""), NetworkTransport::Tls => Some("tls"), NetworkTransport::Plaintext => Some("plaintext"), - NetworkTransport::Unspecified => None, } } @@ -86,57 +87,42 @@ pub fn inspected_l7_protocol(protocol: &str, tls: i32) -> Option { } } -/// Validate the authored set without assigning defaults to an omitted field. -pub fn validate_allowed_transports( - explicit: &[i32], +/// Validate the authored `transport` without assigning defaults to an omitted field. +pub fn validate_endpoint_transport( + transport: i32, protocol: &str, tls: i32, ) -> Option<&'static str> { - parse_allowed_transports(explicit, inspected_l7_protocol(protocol, tls)).err() + parse_endpoint_transport(transport, inspected_l7_protocol(protocol, tls)).err() } -fn parse_allowed_transports( - explicit: &[i32], +fn parse_endpoint_transport( + explicit: i32, protocol: Option, ) -> Result, &'static str> { - if explicit.is_empty() { - return Ok(None); - } + let transport = match NetworkTransport::try_from(explicit) { + Ok(NetworkTransport::Unspecified) => return Ok(None), + Ok(NetworkTransport::Tls) => AllowedTransports::Tls, + Ok(NetworkTransport::Plaintext) => AllowedTransports::Plaintext, + Err(_) => return Err("transport accepts only tls or plaintext"), + }; if !protocol.is_some_and(L7Protocol::is_http) { return Err( - "allowed_transports requires an inspected HTTP protocol and cannot be combined with tls: skip", + "transport requires an inspected HTTP protocol and cannot be combined with tls: skip", ); } - let mut tls = false; - let mut plaintext = false; - for value in explicit { - let seen = match NetworkTransport::try_from(*value) { - Ok(NetworkTransport::Tls) => &mut tls, - Ok(NetworkTransport::Plaintext) => &mut plaintext, - _ => return Err("allowed_transports accepts only tls and plaintext"), - }; - if *seen { - return Err("allowed_transports must not contain duplicates"); - } - *seen = true; - } - Ok(Some(match (tls, plaintext) { - (true, true) => AllowedTransports::Both, - (true, false) => AllowedTransports::Tls, - (false, true) => AllowedTransports::Plaintext, - (false, false) => unreachable!("nonempty transport list"), - })) + Ok(Some(transport)) } /// Resolve once for the destination port. An opaque connection has no HTTP -/// transport policy. Invalid lists are errors, never permission to relay raw TCP. +/// transport policy. Invalid values are errors, never permission to relay raw TCP. pub fn effective_allowed_transports( - explicit: &[i32], + explicit: i32, protocol: Option, credentialed: bool, port: u32, ) -> Result, &'static str> { - if let Some(transports) = parse_allowed_transports(explicit, protocol)? { + if let Some(transports) = parse_endpoint_transport(explicit, protocol)? { return Ok(Some(transports)); } Ok(protocol.filter(|p| p.is_http()).map(|_| { @@ -161,7 +147,7 @@ pub fn endpoint_allowed_transports( port: u32, ) -> Option { effective_allowed_transports( - &endpoint.allowed_transports, + endpoint.transport, inspected_l7_protocol(&endpoint.protocol, endpoint.tls), endpoint_is_credentialed(endpoint), port, @@ -171,11 +157,11 @@ pub fn endpoint_allowed_transports( } /// Whether `endpoint` requires a supervisor that enforces endpoint transport -/// restrictions (either an explicit allowlist or a TLS-only default on any +/// restrictions (either an explicit `transport` or a TLS-only default on any /// selected port). #[must_use] pub fn endpoint_requires_transport_enforcement(endpoint: &NetworkEndpoint) -> bool { - !endpoint.allowed_transports.is_empty() + endpoint.transport != NetworkTransport::Unspecified as i32 || selector_ports(endpoint).iter().any(|&port| { endpoint_allowed_transports(endpoint, port) == Some(AllowedTransports::Tls) }) @@ -353,35 +339,31 @@ mod transport_tests { endpoint_allowed_transports(&endpoint, 8443), Some(AllowedTransports::Tls) ); - endpoint.allowed_transports = vec![ - NetworkTransport::Plaintext as i32, - NetworkTransport::Tls as i32, - ]; + endpoint.transport = NetworkTransport::Plaintext as i32; assert_eq!( endpoint_allowed_transports(&endpoint, 443), - Some(AllowedTransports::Both) + Some(AllowedTransports::Plaintext) ); - endpoint.allowed_transports.pop(); + endpoint.transport = NetworkTransport::Tls as i32; assert_eq!( - endpoint_allowed_transports(&endpoint, 443), - Some(AllowedTransports::Plaintext) + endpoint_allowed_transports(&endpoint, 8443), + Some(AllowedTransports::Tls) ); } #[test] - fn invalid_transport_sets_and_opaque_protocols_are_rejected() { + fn invalid_transport_values_and_opaque_protocols_are_rejected() { let tls = NetworkTransport::Tls as i32; - for invalid in [&[0][..], &[99], &[tls, tls]] { - assert!(validate_allowed_transports(invalid, "rest", 0).is_some()); - } + assert_eq!(validate_endpoint_transport(0, "rest", 0), None); + assert!(validate_endpoint_transport(99, "rest", 0).is_some()); for protocol in ["", "tcp", "sql", "ssh"] { - assert!(validate_allowed_transports(&[tls], protocol, 0).is_some()); + assert!(validate_endpoint_transport(tls, protocol, 0).is_some()); assert_eq!( - effective_allowed_transports(&[], inspected_l7_protocol(protocol, 0), false, 443), + effective_allowed_transports(0, inspected_l7_protocol(protocol, 0), false, 443), Ok(None) ); } - assert!(validate_allowed_transports(&[tls], "rest", NetworkTlsMode::Skip as i32).is_some()); + assert!(validate_endpoint_transport(tls, "rest", NetworkTlsMode::Skip as i32).is_some()); } #[test] @@ -416,7 +398,7 @@ mod transport_tests { assert!(endpoint_requires_transport_enforcement(&endpoint)); endpoint.provider_credentialed = false; - endpoint.allowed_transports = vec![NetworkTransport::Plaintext as i32]; + endpoint.transport = NetworkTransport::Plaintext as i32; assert!(endpoint_requires_transport_enforcement(&endpoint)); } } diff --git a/crates/openshell-policy-cedar-adapter/src/lib.rs b/crates/openshell-policy-cedar-adapter/src/lib.rs index f38481210b..f672976424 100644 --- a/crates/openshell-policy-cedar-adapter/src/lib.rs +++ b/crates/openshell-policy-cedar-adapter/src/lib.rs @@ -116,13 +116,13 @@ pub fn analyze_engine_provider_transports( continue; } match effective_allowed_transports( - &endpoint.allowed_transports, + endpoint.transport, Some(L7Protocol::Rest), endpoint_is_credentialed(endpoint), u32::from(*port), ) { Ok(Some(transports)) => { - if !endpoint.allowed_transports.is_empty() + if endpoint.transport != openshell_core::proto::NetworkTransport::Unspecified as i32 || transports == AllowedTransports::Tls { requires_transport_support = true; @@ -146,7 +146,7 @@ pub fn analyze_engine_provider_transports( && left.3.intersect(right.3).is_none() { conflicts.push(format!( - "provider policies '{}' endpoint[{}] ({}:{port}) and '{}' endpoint[{}] ({}:{port}) have disjoint allowed_transports ({:?} vs {:?})", + "provider policies '{}' endpoint[{}] ({}:{port}) and '{}' endpoint[{}] ({}:{port}) have disjoint transport ({:?} vs {:?})", left.0, left.1, left.2.host, right.0, right.1, right.2.host, left.3, right.3 )); } @@ -286,7 +286,7 @@ when { context.method == "GET" }; host: "api.example.com".to_string(), port: 443, path: "/v1/**".to_string(), - allowed_transports: vec![NetworkTransport::Plaintext as i32], + transport: NetworkTransport::Plaintext as i32, ..Default::default() }; let conflict = @@ -306,7 +306,7 @@ permit (principal, action == Sandbox::Action::"NetworkConnect", port: 443, protocol: "rest".to_string(), provider_credentialed: true, - allowed_transports: vec![NetworkTransport::Tls as i32], + transport: NetworkTransport::Tls as i32, ..Default::default() }; let uninspected = diff --git a/crates/openshell-policy-cedar-runtime/src/cedar_only/routes.rs b/crates/openshell-policy-cedar-runtime/src/cedar_only/routes.rs index 00b31cabf6..d2fbdc7666 100644 --- a/crates/openshell-policy-cedar-runtime/src/cedar_only/routes.rs +++ b/crates/openshell-policy-cedar-runtime/src/cedar_only/routes.rs @@ -260,8 +260,10 @@ impl LoadedPolicy { } if !disjoint && authority_transports == Some(AllowedTransports::Tls) { for config in &mut configs { - if config.protocol.l7().is_some() && config.allowed_transports.is_empty() { - config.allowed_transports.push(NetworkTransport::Tls as i32); + if config.protocol.l7().is_some() + && config.transport == NetworkTransport::Unspecified as i32 + { + config.transport = NetworkTransport::Tls as i32; } } } @@ -471,9 +473,7 @@ impl RoutePlan<'_> { if let Some(inspection) = inspection { apply_inspection(&mut config, inspection); if let Some(provider) = route.provider { - config - .allowed_transports - .clone_from(&provider.allowed_transports); + config.transport = provider.transport; } } // Every inspected protocol binds grant reporting to the policy @@ -803,8 +803,8 @@ struct ProviderEndpoint { ports: Vec, /// The endpoint's `allowed_ips`, empty for none, or why one is invalid. allowed_ips: ProviderRanges, - /// Authored `allowed_transports`, applied only when Cedar inspects the route. - allowed_transports: Vec, + /// Authored `transport`, applied only when Cedar inspects the route. + transport: i32, /// The endpoint's credential settings, as the L7 config parser reads /// them (see [`provider_config`]). config: EndpointConfig, @@ -833,7 +833,7 @@ impl ProviderEndpoint { host: endpoint.host.to_ascii_lowercase(), ports: connection_ports(endpoint), allowed_ips: parse_provider_allowed_ips(&endpoint.allowed_ips), - allowed_transports: endpoint.allowed_transports.clone(), + transport: endpoint.transport, config: provider_config(endpoint), } } diff --git a/crates/openshell-policy-cedar-runtime/src/cedar_only/tests.rs b/crates/openshell-policy-cedar-runtime/src/cedar_only/tests.rs index 2ae629ff77..cf624297b3 100644 --- a/crates/openshell-policy-cedar-runtime/src/cedar_only/tests.rs +++ b/crates/openshell-policy-cedar-runtime/src/cedar_only/tests.rs @@ -1871,12 +1871,12 @@ fn credentialed_cedar_path_sets_tls_default_for_its_authority() { } #[test] -fn uninspected_cedar_provider_route_drops_explicit_allowed_transports() { +fn uninspected_cedar_provider_route_drops_explicit_transport() { use openshell_core::proto::NetworkTransport; let mut unrelated = credentialed_endpoint(); unrelated.path = "/elsewhere/**".to_string(); - unrelated.allowed_transports = vec![NetworkTransport::Tls as i32]; + unrelated.transport = NetworkTransport::Tls as i32; let engine = CedarOnlyEngine::from_proto(&provider_policy(PATHS_POLICY, vec![unrelated])) .expect("policy loads"); let configs = engine @@ -1887,7 +1887,7 @@ fn uninspected_cedar_provider_route_drops_explicit_allowed_transports() { .iter() .find(|config| config.path == "/elsewhere/**") .expect("uninspected provider config"); - assert!(uninspected.allowed_transports.is_empty()); + assert_eq!(uninspected.transport, NetworkTransport::Unspecified as i32); assert_eq!(uninspected.allowed_transports_for_port(443), Ok(None)); // Also verify a host:port permitted only at L4 (no HttpRequest policy). @@ -1897,14 +1897,17 @@ permit (principal, action == Sandbox::Action::"NetworkConnect", "#; let mut l4_provider = credentialed_endpoint(); l4_provider.port = 8443; - l4_provider.allowed_transports = vec![NetworkTransport::Tls as i32]; + l4_provider.transport = NetworkTransport::Tls as i32; let l4_engine = CedarOnlyEngine::from_proto(&provider_policy(l4_cedar, vec![l4_provider])) .expect("L4 policy loads"); let l4_configs = l4_engine .credential_guards("api.example.com", 8443) .expect("L4 configs build"); assert_eq!(l4_configs.len(), 1); - assert!(l4_configs[0].allowed_transports.is_empty()); + assert_eq!( + l4_configs[0].transport, + NetworkTransport::Unspecified as i32 + ); assert_eq!(l4_configs[0].allowed_transports_for_port(8443), Ok(None)); } @@ -1917,7 +1920,7 @@ fn provider_plaintext_conflicting_with_cedar_443_default_fails_at_load_time() { let mut provider = credentialed_endpoint(); provider.path = "/ws".to_string(); provider.port = 443; - provider.allowed_transports = vec![NetworkTransport::Plaintext as i32]; + provider.transport = NetworkTransport::Plaintext as i32; let error = CedarOnlyEngine::from_proto(&provider_policy(PATHS_POLICY, vec![provider])) .expect_err("disjoint provider plaintext vs Cedar 443 default must fail at load time"); assert!( @@ -1943,7 +1946,7 @@ when { context.method == "GET" }; let mut provider = credentialed_endpoint(); provider.path.clear(); provider.port = 443; - provider.allowed_transports = vec![NetworkTransport::Plaintext as i32]; + provider.transport = NetworkTransport::Plaintext as i32; let engine = CedarOnlyEngine::from_proto(&provider_policy(cedar, vec![provider])) .expect("full-coverage plaintext provider loads cleanly"); let configs = engine @@ -1964,7 +1967,7 @@ fn credentialed_provider_plaintext_on_8443_does_not_stamp_tls_on_cedar_siblings( let mut provider = credentialed_endpoint(); provider.path = "/ws".to_string(); provider.port = 8443; - provider.allowed_transports = vec![NetworkTransport::Plaintext as i32]; + provider.transport = NetworkTransport::Plaintext as i32; let cedar = PATHS_POLICY.replace(":443", ":8443"); let engine = CedarOnlyEngine::from_proto(&provider_policy(&cedar, vec![provider])) .expect("plaintext credentialed provider on 8443 loads cleanly"); diff --git a/crates/openshell-policy-runtime-interface/src/policy_data.rs b/crates/openshell-policy-runtime-interface/src/policy_data.rs index 8ecc61c5a6..70a5a04b19 100644 --- a/crates/openshell-policy-runtime-interface/src/policy_data.rs +++ b/crates/openshell-policy-runtime-interface/src/policy_data.rs @@ -59,16 +59,10 @@ pub fn endpoint_policy_value( .map_or_else(|| format!("unknown({})", e.tls), str::to_owned) .into(); } - if !e.allowed_transports.is_empty() { - let labels: Vec<_> = e - .allowed_transports - .iter() - .map(|value| { - openshell_core::policy_l7::network_transport_to_str(*value) - .map_or_else(|| format!("unknown({value})"), str::to_owned) - }) - .collect(); - ep["allowed_transports"] = labels.into(); + if e.transport != 0 { + ep["transport"] = openshell_core::policy_l7::network_transport_to_str(e.transport) + .map_or_else(|| format!("unknown({})", e.transport), str::to_owned) + .into(); } if e.enforcement != 0 { ep["enforcement"] = diff --git a/crates/openshell-policy-runtime-interface/src/policy_types.rs b/crates/openshell-policy-runtime-interface/src/policy_types.rs index 72d0eee086..3563c7e924 100644 --- a/crates/openshell-policy-runtime-interface/src/policy_types.rs +++ b/crates/openshell-policy-runtime-interface/src/policy_types.rs @@ -238,9 +238,10 @@ pub struct EndpointConfig { pub path: String, pub protocol: EndpointProtocol, pub tls: TlsSetting, - /// Authored transport selectors. Empty means the endpoint uses the port and credential defaults. - #[serde(deserialize_with = "deserialize_allowed_transports")] - pub allowed_transports: Vec, + /// Authored wire transport (`NetworkTransport` proto enum value). Zero + /// means the endpoint uses the port and credential defaults. + #[serde(deserialize_with = "deserialize_transport")] + pub transport: i32, pub enforcement: EnforcementSetting, pub access: AccessSetting, pub rules: Vec, @@ -303,7 +304,7 @@ impl EndpointConfig { TlsSetting::Unknown => return Err("unknown endpoint TLS setting"), }; effective_allowed_transports( - &self.allowed_transports, + self.transport, protocol, self.is_credentialed(), u32::from(port), @@ -311,17 +312,13 @@ impl EndpointConfig { } } -fn deserialize_allowed_transports<'de, D: Deserializer<'de>>( +fn deserialize_transport<'de, D: Deserializer<'de>>( deserializer: D, -) -> std::result::Result, D::Error> { - Vec::::deserialize(deserializer)? - .iter() - .map(|value| { - network_transport_from_str(value) - .map(|transport| transport as i32) - .ok_or_else(|| serde::de::Error::custom("invalid endpoint transport")) - }) - .collect() +) -> std::result::Result { + let value = String::deserialize(deserializer)?; + network_transport_from_str(&value) + .map(|transport| transport as i32) + .ok_or_else(|| serde::de::Error::custom("invalid endpoint transport")) } fn deserialize_credential_binding<'de, D: Deserializer<'de>>( diff --git a/crates/openshell-policy-schema/src/lib.rs b/crates/openshell-policy-schema/src/lib.rs index e6bce8d01e..d3b5c5025c 100644 --- a/crates/openshell-policy-schema/src/lib.rs +++ b/crates/openshell-policy-schema/src/lib.rs @@ -275,13 +275,9 @@ pub struct NetworkEndpoint { pub protocol: String, #[serde(default, skip_serializing_if = "String::is_empty")] pub tls: String, - /// Explicit transports for an inspected HTTP-family endpoint. - #[serde( - default, - deserialize_with = "deserialize_allowed_transports", - skip_serializing_if = "Vec::is_empty" - )] - pub allowed_transports: Vec, + /// Wire transport policy for an inspected HTTP-family endpoint (`tls` or `plaintext`). + #[serde(default, skip_serializing_if = "String::is_empty")] + pub transport: String, #[serde(default, skip_serializing_if = "String::is_empty")] pub enforcement: String, #[serde(default, skip_serializing_if = "String::is_empty")] @@ -538,35 +534,6 @@ where .ok_or_else(|| serde::de::Error::custom("null is not allowed for this field")) } -/// Parse a present transport allowlist shared by sandbox policies and profiles. -pub fn deserialize_allowed_transports<'de, D>( - deserializer: D, -) -> std::result::Result, D::Error> -where - D: Deserializer<'de>, -{ - let transports = Vec::::deserialize(deserializer)?; - if transports.is_empty() { - return Err(serde::de::Error::custom( - "allowed_transports must contain at least one transport when present", - )); - } - let mut seen = BTreeSet::new(); - for transport in &transports { - if !matches!(transport.as_str(), "tls" | "plaintext") { - return Err(serde::de::Error::custom(format!( - "unknown allowed_transports value '{transport}'. Expected tls or plaintext" - ))); - } - if !seen.insert(transport) { - return Err(serde::de::Error::custom(format!( - "duplicate allowed_transports value '{transport}'" - ))); - } - } - Ok(transports) -} - const MAX_UNKNOWN_FIELD_PATH_BYTES: usize = 1_024; // Unknown fields are inspected only to produce fail-closed diagnostics. @@ -871,7 +838,7 @@ fn inspect_endpoint(value: &serde_yml::Value, path: &str) -> InspectionResult { "ports", "protocol", "tls", - "allowed_transports", + "transport", "enforcement", "access", "rules", diff --git a/crates/openshell-policy/src/ambiguity.rs b/crates/openshell-policy/src/ambiguity.rs index 0fa0620528..8c92bae25c 100644 --- a/crates/openshell-policy/src/ambiguity.rs +++ b/crates/openshell-policy/src/ambiguity.rs @@ -101,12 +101,7 @@ pub fn find_endpoint_ambiguities(policy: &SandboxPolicy) -> Vec NetworkEndpoint { ports: normalized_ports, protocol: protocol.clone(), tls: network_tls_mode_from_str(&e.tls).expect("endpoint modes validated above") as i32, - allowed_transports: e - .allowed_transports - .iter() - .map(|transport| { - network_transport_from_str(transport) - .expect("authored transports validated by policy schema") as i32 - }) - .collect(), + transport: network_transport_from_str(&e.transport).expect("endpoint modes validated above") + as i32, enforcement: network_enforcement_mode_from_str(&e.enforcement) .expect("endpoint modes validated above") as i32, access: network_access_preset_from_str(&e.access).expect("endpoint modes validated above") @@ -579,8 +572,14 @@ fn endpoint_def_to_proto(e: NetworkEndpointDef) -> NetworkEndpoint { fn to_proto(raw: PolicyFile) -> Result { for (policy_name, rule) in &raw.network_policies { for (endpoint_index, endpoint) in rule.endpoints.iter().enumerate() { - let errors = + let mut errors = validate_endpoint_modes(&endpoint.tls, &endpoint.enforcement, &endpoint.access); + if network_transport_from_str(&endpoint.transport).is_none() { + errors.push(format!( + "unknown transport value '{}' (expected tls or plaintext)", + endpoint.transport + )); + } if !errors.is_empty() { return Err(miette::miette!( "network policy '{policy_name}': endpoint {endpoint_index}: {}", @@ -611,8 +610,8 @@ fn to_proto(raw: PolicyFile) -> Result { .map(endpoint_def_to_proto) .enumerate() .map(|(index, endpoint)| { - if let Some(reason) = validate_allowed_transports( - &endpoint.allowed_transports, + if let Some(reason) = validate_endpoint_transport( + endpoint.transport, &endpoint.protocol, endpoint.tls, ) { @@ -677,8 +676,8 @@ fn endpoint_setting_def_to_proto( index: usize, setting: NetworkEndpointDef, ) -> Result { - if !setting.allowed_transports.is_empty() { - let reason = RejectedSettingField::Access.reason("allowed_transports"); + if !setting.transport.is_empty() { + let reason = RejectedSettingField::Access.reason("transport"); miette::bail!("endpoint_settings[{index}]: {reason}"); } let errors = validate_endpoint_modes(&setting.tls, &setting.enforcement, &setting.access); @@ -806,15 +805,9 @@ fn endpoint_proto_to_def(e: &NetworkEndpoint) -> Result { tls: network_tls_mode_to_str(e.tls) .expect("policy enum values validated before serialization") .to_string(), - allowed_transports: e - .allowed_transports - .iter() - .map(|&transport| { - network_transport_to_str(transport) - .map(str::to_owned) - .ok_or_else(|| miette::miette!("invalid allowed_transports value {transport}")) - }) - .collect::>()?, + transport: network_transport_to_str(e.transport) + .ok_or_else(|| miette::miette!("invalid transport value {}", e.transport))? + .to_string(), enforcement: network_enforcement_mode_to_str(e.enforcement) .expect("policy enum values validated before serialization") .to_string(), @@ -1238,12 +1231,8 @@ fn validate_policy_enum_values(policy: &SandboxPolicy) -> Result<()> { let mut errors = validate_endpoint_mode_values(endpoint.tls, endpoint.enforcement, endpoint.access); errors.extend( - validate_allowed_transports( - &endpoint.allowed_transports, - &endpoint.protocol, - endpoint.tls, - ) - .map(str::to_owned), + validate_endpoint_transport(endpoint.transport, &endpoint.protocol, endpoint.tls) + .map(str::to_owned), ); if !errors.is_empty() { return Err(miette::miette!( @@ -1256,8 +1245,8 @@ fn validate_policy_enum_values(policy: &SandboxPolicy) -> Result<()> { for (index, setting) in policy.endpoint_settings.iter().enumerate() { let mut errors = validate_endpoint_mode_values(setting.tls, setting.enforcement, setting.access); - if !setting.allowed_transports.is_empty() { - errors.push(RejectedSettingField::Access.reason("allowed_transports")); + if setting.transport != 0 { + errors.push(RejectedSettingField::Access.reason("transport")); } if !errors.is_empty() { return Err(miette::miette!( @@ -2043,8 +2032,7 @@ fn validate_sandbox_policy_with_mcp_presence( ep.access, )); l7_errors.extend( - validate_allowed_transports(&ep.allowed_transports, &ep.protocol, ep.tls) - .map(str::to_owned), + validate_endpoint_transport(ep.transport, &ep.protocol, ep.tls).map(str::to_owned), ); let mut explicit_tcp_fields = Vec::new(); if ep.enforcement != 0 { @@ -2208,7 +2196,7 @@ fn endpoint_setting_rejected_fields( mcp, // Access and inspection, which the Cedar policy decides. protocol, - allowed_transports, + transport, enforcement, access, rules, @@ -2243,11 +2231,7 @@ fn endpoint_setting_rejected_fields( !protocol.is_empty(), RejectedSettingField::Access, ), - ( - "allowed_transports", - !allowed_transports.is_empty(), - RejectedSettingField::Access, - ), + ("transport", *transport != 0, RejectedSettingField::Access), ( "enforcement", *enforcement != 0, @@ -3191,7 +3175,7 @@ when { context.binary_path == "/usr/bin/curl" }; fn endpoint_settings_reject_access_and_credential_fields() { for (field, yaml) in [ ("protocol", "protocol: rest"), - ("allowed_transports", "allowed_transports: [tls]"), + ("transport", "transport: tls"), ("enforcement", "enforcement: enforce"), ("access", "access: read-only"), ("rules", "rules: [{ allow: { method: GET } }]"), @@ -3720,59 +3704,52 @@ network_policies: } #[test] - fn allowed_transports_round_trip_in_policy_yaml_and_json() { + fn transport_round_trip_in_policy_yaml_and_json() { use openshell_core::proto::NetworkTransport; for protocol in ["rest", "graphql", "websocket", "mcp", "json-rpc"] { - let policy = parse_sandbox_policy(&transport_endpoint_yaml(&format!( - "protocol: {protocol}, access: full, allowed_transports: [plaintext, tls]" - ))) - .expect("inspected policy"); - assert_eq!( - policy.network_policies["api"].endpoints[0].allowed_transports, - [ - NetworkTransport::Plaintext as i32, - NetworkTransport::Tls as i32 - ], - ); - let yaml = serialize_sandbox_policy(&policy).expect("serialize"); - assert_eq!(parse_sandbox_policy(&yaml).expect("reparse"), policy); - let json = sandbox_policy_to_json_value(&policy).expect("serialize"); - assert_eq!( - json["network_policies"]["api"]["endpoints"][0]["allowed_transports"], - serde_json::json!(["plaintext", "tls"]), - ); + for (label, expected) in [ + ("tls", NetworkTransport::Tls as i32), + ("plaintext", NetworkTransport::Plaintext as i32), + ] { + let policy = parse_sandbox_policy(&transport_endpoint_yaml(&format!( + "protocol: {protocol}, access: full, transport: {label}" + ))) + .expect("inspected policy"); + assert_eq!( + policy.network_policies["api"].endpoints[0].transport, + expected, + ); + let yaml = serialize_sandbox_policy(&policy).expect("serialize"); + assert_eq!(parse_sandbox_policy(&yaml).expect("reparse"), policy); + let json = sandbox_policy_to_json_value(&policy).expect("serialize"); + assert_eq!( + json["network_policies"]["api"]["endpoints"][0]["transport"], + serde_json::json!(label), + ); + } } let policy = parse_sandbox_policy(&transport_endpoint_yaml("protocol: rest, access: full")) - .expect("omitted allowlist"); - assert!( - policy.network_policies["api"].endpoints[0] - .allowed_transports - .is_empty() + .expect("omitted transport"); + assert_eq!( + policy.network_policies["api"].endpoints[0].transport, + NetworkTransport::Unspecified as i32 ); - let yaml = serialize_sandbox_policy(&policy).expect("serialize omitted allowlist"); - assert!(!yaml.contains("allowed_transports")); + let yaml = serialize_sandbox_policy(&policy).expect("serialize omitted transport"); + assert!(!yaml.contains("transport")); } #[test] - fn authored_transports_reject_invalid_lists_and_unsupported_endpoints() { - for transports in [ - "[]", - "[tls, tls]", - "[https]", - "[null]", - "null", - "tls", - "[1]", - ] { + fn authored_transport_rejects_invalid_values_and_unsupported_endpoints() { + for transport in ["https", "http", "any", "null", "[tls]", "1"] { let source = transport_endpoint_yaml(&format!( - "protocol: rest, access: full, allowed_transports: {transports}" + "protocol: rest, access: full, transport: {transport}" )); - let error = parse_sandbox_policy(&source).expect_err(transports); + let error = parse_sandbox_policy(&source).expect_err(transport); assert!( - error_chain(&error).contains("allowed_transports"), - "{error:?}" + error_chain(&error).contains("transport"), + "{transport}: {error:?}" ); } for fields in [ @@ -3781,41 +3758,39 @@ network_policies: "protocol: tcp", "protocol: ''", ] { - let source = transport_endpoint_yaml(&format!("{fields}, allowed_transports: [tls]")); + let source = transport_endpoint_yaml(&format!("{fields}, transport: tls")); let error = parse_sandbox_policy(&source).expect_err(fields); assert!( - error_chain(&error).contains("allowed_transports"), - "{error:?}" + error_chain(&error).contains("transport"), + "{fields}: {error:?}" ); } } #[test] - fn wire_policy_rejects_invalid_allowed_transports() { + fn wire_policy_rejects_invalid_transport() { use openshell_core::proto::{NetworkTlsMode, NetworkTransport}; let tls = NetworkTransport::Tls as i32; - for (transports, protocol, tls_mode) in [ - (vec![NetworkTransport::Unspecified as i32], "rest", 0), - (vec![99], "rest", 0), - (vec![tls, tls], "rest", 0), - (vec![tls], "rest", NetworkTlsMode::Skip as i32), - (vec![tls], "sql", 0), - (vec![tls], "tcp", 0), - (vec![tls], "", 0), + for (transport, protocol, tls_mode) in [ + (99, "rest", 0), + (tls, "rest", NetworkTlsMode::Skip as i32), + (tls, "sql", 0), + (tls, "tcp", 0), + (tls, "", 0), ] { let mut policy = parse_sandbox_policy(&transport_endpoint_yaml("protocol: rest, access: full")) .expect("base policy"); let endpoint = &mut policy.network_policies.get_mut("api").unwrap().endpoints[0]; - endpoint.allowed_transports = transports; + endpoint.transport = transport; endpoint.protocol = protocol.to_owned(); endpoint.tls = tls_mode; - let errors = validate_sandbox_policy(&policy).expect_err("wire allowlist is invalid"); + let errors = validate_sandbox_policy(&policy).expect_err("wire transport is invalid"); assert!( errors .iter() - .any(|error| error.to_string().contains("allowed_transports")) + .any(|error| error.to_string().contains("transport")) ); assert!(serialize_sandbox_policy(&policy).is_err()); } diff --git a/crates/openshell-policy/src/merge.rs b/crates/openshell-policy/src/merge.rs index 7840605f59..ebccfeb740 100644 --- a/crates/openshell-policy/src/merge.rs +++ b/crates/openshell-policy/src/merge.rs @@ -42,7 +42,7 @@ pub fn canonicalize_advisor_add_rule( let incoming_ports = canonical_ports(incoming_endpoint); if incoming_endpoint.host.trim().is_empty() || incoming_ports.len() != 1 - || !incoming_endpoint.allowed_transports.is_empty() + || incoming_endpoint.transport != NetworkTransport::Unspecified as i32 { return Ok((requested_rule_name.to_string(), incoming_rule.clone())); } @@ -68,7 +68,7 @@ pub fn canonicalize_advisor_add_rule( if transports == Some(AllowedTransports::Tls) && endpoint_allowed_transports(&endpoint, port) != transports { - endpoint.allowed_transports = vec![NetworkTransport::Tls as i32]; + endpoint.transport = NetworkTransport::Tls as i32; } endpoint }) @@ -148,7 +148,6 @@ fn normalize_advisor_contract(endpoint: &mut NetworkEndpoint) { endpoint.advisor_proposed = false; endpoint.token_grant_owner.clear(); normalize_endpoint(endpoint); - endpoint.allowed_transports.sort_unstable(); } /// Binary authorization affected by an incremental L7 rule append. @@ -569,7 +568,7 @@ impl std::fmt::Display for PolicyMergeError { port, } => write!( f, - "merge operation {operation_index} cannot combine allowed_transports at {host}:{port} without changing an endpoint transport contract" + "merge operation {operation_index} cannot combine transport at {host}:{port} without changing an endpoint transport contract" ), Self::NewBinaryWouldInheritAuthorization { operation_index, @@ -860,8 +859,8 @@ fn endpoint_attributes_cover(loaded: &NetworkEndpoint, proposed: &NetworkEndpoin if proposed.tls != NetworkTlsMode::Unspecified as i32 && loaded.tls != proposed.tls { return false; } - if !proposed.allowed_transports.is_empty() - && !transport_lists_match(&loaded.allowed_transports, &proposed.allowed_transports) + if proposed.transport != NetworkTransport::Unspecified as i32 + && loaded.transport != proposed.transport { return false; } @@ -1622,10 +1621,8 @@ fn merge_endpoint( port: conflict_port, }); } - if existing.allowed_transports.is_empty() { - existing - .allowed_transports - .clone_from(&incoming.allowed_transports); + if existing.transport == NetworkTransport::Unspecified as i32 { + existing.transport = incoming.transport; } if existing.host.is_empty() { @@ -1722,10 +1719,6 @@ fn merge_endpoint( Ok(()) } -fn transport_lists_match(left: &[i32], right: &[i32]) -> bool { - left.len() == right.len() && contains_all(left, right) && contains_all(right, left) -} - fn transport_conflict_port( existing: &NetworkEndpoint, incoming: &NetworkEndpoint, @@ -1733,22 +1726,20 @@ fn transport_conflict_port( incoming_ports: &[u32], overlapping_port: u32, ) -> Option { + let unspecified = NetworkTransport::Unspecified as i32; match ( - existing.allowed_transports.is_empty(), - incoming.allowed_transports.is_empty(), + existing.transport == unspecified, + incoming.transport == unspecified, ) { (true, true) => None, - (false, false) => { - (!transport_lists_match(&existing.allowed_transports, &incoming.allowed_transports)) - .then_some(overlapping_port) - } - // Taking on an explicit allowlist cannot change the transport on any - // existing port, even a sibling port the incoming rule did not name. + (false, false) => (existing.transport != incoming.transport).then_some(overlapping_port), + // Taking on an explicit transport cannot change the effective transport + // on any existing port, even a sibling port the incoming rule did not name. (true, false) => existing_ports.iter().copied().find(|&port| { endpoint_allowed_transports(existing, port) != endpoint_allowed_transports(incoming, port) }), - // The existing allowlist is retained. On newly added ports, it must + // The existing transport is retained. On newly added ports, it must // agree with any transport default selected by the incoming rule. (false, true) => { if incoming.tls == NetworkTlsMode::Skip as i32 { @@ -1957,7 +1948,7 @@ fn operation_declares( /// judged against. /// /// A carry-over field is one the merge never widens: it either retains the -/// existing value (`protocol`, `tls`, `allowed_transports`, `enforcement`, +/// existing value (`protocol`, `tls`, `transport`, `enforcement`, /// `access`) or ignores the /// incoming value entirely (the signing and GraphQL fields). Either way the new /// binary receives whatever the endpoint already carried, and the operation @@ -1987,10 +1978,8 @@ fn adopt_unset_retained_fields( if adopted.tls == NetworkTlsMode::Unspecified as i32 { adopted.tls = merged.tls; } - if adopted.allowed_transports.is_empty() { - adopted - .allowed_transports - .clone_from(&merged.allowed_transports); + if adopted.transport == NetworkTransport::Unspecified as i32 { + adopted.transport = merged.transport; } if adopted.enforcement == NetworkEnforcementMode::Unspecified as i32 { adopted.enforcement = merged.enforcement; @@ -2773,8 +2762,8 @@ mod tests { ); assert!(!canonical.endpoints[0].provider_credentialed); assert_eq!( - canonical.endpoints[0].allowed_transports, - [NetworkTransport::Tls as i32] + canonical.endpoints[0].transport, + NetworkTransport::Tls as i32 ); assert!(canonical.endpoints[0].advisor_proposed); assert!(canonical.endpoints[0].token_grant_owner.is_empty()); @@ -2974,17 +2963,14 @@ mod tests { policy } - fn transport_rule(ports: &[u32], transports: &[NetworkTransport]) -> NetworkPolicyRule { + fn transport_rule(ports: &[u32], transport: NetworkTransport) -> NetworkPolicyRule { rule_with_authorizations( "api", vec![NetworkEndpoint { ports: ports.to_vec(), protocol: "rest".to_owned(), access: NetworkAccessPreset::Full as i32, - allowed_transports: transports - .iter() - .map(|transport| *transport as i32) - .collect(), + transport: transport as i32, ..endpoint("api.example.com", ports[0]) }], &["/usr/bin/client"], @@ -2992,11 +2978,11 @@ mod tests { } #[test] - fn merge_keeps_explicit_transport_sets_and_coverage() { + fn merge_keeps_explicit_transport_and_coverage() { + let unspecified = NetworkTransport::Unspecified; let tls = NetworkTransport::Tls; - let plaintext = NetworkTransport::Plaintext; - let default_tls = policy_with_rule("api", transport_rule(&[443], &[])); - let explicit_tls = transport_rule(&[443], &[tls]); + let default_tls = policy_with_rule("api", transport_rule(&[443], unspecified)); + let explicit_tls = transport_rule(&[443], tls); assert!(!policy_covers_rule(&default_tls, &explicit_tls)); let adopted = merge_policy( default_tls, @@ -3005,41 +2991,42 @@ mod tests { rule: explicit_tls.clone(), }], ) - .expect("the explicit TLS list preserves the existing port's behavior"); + .expect("explicit TLS preserves the existing port's behavior"); assert!(policy_covers_rule(&adopted.policy, &explicit_tls)); - let loaded = policy_with_rule("api", transport_rule(&[8443], &[tls, plaintext])); - let reversed = transport_rule(&[8443], &[plaintext, tls]); - assert!(policy_covers_rule(&loaded, &reversed)); + let loaded = policy_with_rule("api", transport_rule(&[8443], tls)); + let same = transport_rule(&[8443], tls); + assert!(policy_covers_rule(&loaded, &same)); let merged = merge_policy( loaded, &[PolicyMergeOp::AddRule { rule_name: "api".to_owned(), - rule: reversed, + rule: same, }], ) - .expect("transport list order does not change authorization"); + .expect("identical explicit transport does not change authorization"); assert!(!merged.changed); } #[test] fn merge_rejects_transport_changes_across_overlapping_ports() { + let unspecified = NetworkTransport::Unspecified; let tls = NetworkTransport::Tls; let plaintext = NetworkTransport::Plaintext; for (loaded, incoming, conflict_port) in [ ( - transport_rule(&[443], &[tls]), - transport_rule(&[443], &[plaintext]), + transport_rule(&[443], tls), + transport_rule(&[443], plaintext), 443, ), ( - transport_rule(&[443, 8443], &[]), - transport_rule(&[443], &[tls]), + transport_rule(&[443, 8443], unspecified), + transport_rule(&[443], tls), 8443, ), ( - transport_rule(&[8443], &[tls, plaintext]), - transport_rule(&[443, 8443], &[]), + transport_rule(&[8443], plaintext), + transport_rule(&[443, 8443], unspecified), 443, ), ] { diff --git a/crates/openshell-prover/src/containment.rs b/crates/openshell-prover/src/containment.rs index 8dbedccfad..86b8d18fe4 100644 --- a/crates/openshell-prover/src/containment.rs +++ b/crates/openshell-prover/src/containment.rs @@ -1627,9 +1627,9 @@ fn validate_supported_endpoint_extensions( context: &str, endpoint: &Endpoint, ) -> Result<(), UnsupportedFeature> { - if !endpoint.allowed_transports.is_empty() { + if !endpoint.transport.is_empty() { return Err(UnsupportedFeature::policy_shape(format!( - "{context} uses allowed_transports outside the containment model" + "{context} uses transport outside the containment model" ))); } if !endpoint.tls.is_empty() @@ -2721,9 +2721,9 @@ mod tests { } #[test] - fn transport_allowlists_fail_closed_in_both_containment_inputs() { + fn explicit_transport_fails_closed_in_both_containment_inputs() { let restricted = parse( - "version: 1\nnetwork_policies:\n n:\n endpoints: [{ host: api.example.com, port: 8443, protocol: rest, enforcement: enforce, access: full, allowed_transports: [tls] }]\n binaries: [{ path: /usr/bin/curl }]\n", + "version: 1\nnetwork_policies:\n n:\n endpoints: [{ host: api.example.com, port: 8443, protocol: rest, enforcement: enforce, access: full, transport: tls }]\n binaries: [{ path: /usr/bin/curl }]\n", ); let empty = parse("version: 1\n"); for (boundary, candidate) in [(&restricted, &empty), (&empty, &restricted)] { @@ -2733,7 +2733,7 @@ mod tests { result, CheckResult::Unsupported(ref evidence) if evidence.reason_code() == ReasonCode::UnsupportedPolicyShape - && evidence.reason().contains("allowed_transports") + && evidence.reason().contains("transport") ), "{result:?}" ); diff --git a/crates/openshell-providers/src/profiles.rs b/crates/openshell-providers/src/profiles.rs index e7d2b703b4..b869892180 100644 --- a/crates/openshell-providers/src/profiles.rs +++ b/crates/openshell-providers/src/profiles.rs @@ -8,7 +8,7 @@ use openshell_core::mcp::{ canonicalize_mcp_versions, parse_mcp_versions, }; use openshell_core::policy_l7::{ - network_transport_from_str, network_transport_to_str, validate_allowed_transports, + network_transport_from_str, network_transport_to_str, validate_endpoint_transport, }; use openshell_core::proto::{ GraphqlOperation, L7Allow, L7DenyRule, L7QueryMatcher, L7Rule, McpOptions, NetworkBinary, @@ -20,10 +20,9 @@ use openshell_core::proto::{ }; use openshell_core::secrets::uses_reserved_revision_namespace; use openshell_policy::{ - L7EndpointFields, L7Protocol, deserialize_allowed_transports, network_access_preset_from_str, - network_access_preset_to_str, network_enforcement_mode_from_str, - network_enforcement_mode_to_str, network_tls_mode_from_str, network_tls_mode_to_str, - validate_endpoint_modes, validate_explicit_tcp_additional_fields, + L7EndpointFields, L7Protocol, network_access_preset_from_str, network_access_preset_to_str, + network_enforcement_mode_from_str, network_enforcement_mode_to_str, network_tls_mode_from_str, + network_tls_mode_to_str, validate_endpoint_modes, validate_explicit_tcp_additional_fields, validate_l7_endpoint_semantics, }; use serde::{Deserialize, Deserializer, Serialize, Serializer, de}; @@ -343,7 +342,7 @@ pub struct EndpointProfile { pub port: u32, pub protocol: String, pub tls: String, - pub allowed_transports: Vec, + pub transport: String, pub access: String, pub enforcement: String, pub rules: Option>, @@ -389,12 +388,8 @@ struct EndpointProfileSerde { protocol: String, #[serde(default, skip_serializing_if = "String::is_empty")] tls: String, - #[serde( - default, - deserialize_with = "deserialize_allowed_transports", - skip_serializing_if = "Vec::is_empty" - )] - allowed_transports: Vec, + #[serde(default, skip_serializing_if = "String::is_empty")] + transport: String, #[serde(default, skip_serializing_if = "String::is_empty")] access: String, #[serde(default, skip_serializing_if = "String::is_empty")] @@ -1668,7 +1663,7 @@ fn endpoint_to_proto(endpoint: &EndpointProfile) -> NetworkEndpoint { port: endpoint.port, protocol: endpoint.protocol.clone(), tls: network_tls_mode_from_str(&endpoint.tls).map_or(-1, |value| value as i32), - allowed_transports: endpoint_transport_values(endpoint), + transport: network_transport_from_str(&endpoint.transport).map_or(-1, |value| value as i32), enforcement: network_enforcement_mode_from_str(&endpoint.enforcement) .map_or(-1, |value| value as i32), access: network_access_preset_from_str(&endpoint.access).map_or(-1, |value| value as i32), @@ -1714,14 +1709,6 @@ fn endpoint_to_proto(endpoint: &EndpointProfile) -> NetworkEndpoint { } } -fn endpoint_transport_values(endpoint: &EndpointProfile) -> Vec { - endpoint - .allowed_transports - .iter() - .map(|transport| network_transport_from_str(transport).map_or(-1, |value| value as i32)) - .collect() -} - fn endpoint_from_proto(endpoint: &NetworkEndpoint) -> EndpointProfile { let mut profile = EndpointProfile { host: endpoint.host.clone(), @@ -1729,14 +1716,8 @@ fn endpoint_from_proto(endpoint: &NetworkEndpoint) -> EndpointProfile { protocol: endpoint.protocol.clone(), tls: network_tls_mode_to_str(endpoint.tls) .map_or_else(|| format!("unknown({})", endpoint.tls), str::to_owned), - allowed_transports: endpoint - .allowed_transports - .iter() - .map(|&transport| { - network_transport_to_str(transport) - .map_or_else(|| format!("unknown({transport})"), str::to_owned) - }) - .collect(), + transport: network_transport_to_str(endpoint.transport) + .map_or_else(|| format!("unknown({})", endpoint.transport), str::to_owned), access: network_access_preset_to_str(endpoint.access) .map_or_else(|| format!("unknown({})", endpoint.access), str::to_owned), enforcement: network_enforcement_mode_to_str(endpoint.enforcement).map_or_else( @@ -2847,15 +2828,15 @@ pub fn validate_catalog_profiles( )); } collect_mcp_profile_diagnostics(source, profile_id, index, endpoint, &mut diagnostics); - if let Some(message) = validate_allowed_transports( - &endpoint_transport_values(endpoint), + if let Some(message) = validate_endpoint_transport( + network_transport_from_str(&endpoint.transport).map_or(-1, |value| value as i32), &endpoint.protocol, network_tls_mode_from_str(&endpoint.tls).map_or(-1, |value| value as i32), ) { diagnostics.push(ProfileValidationDiagnostic::error( source, profile_id, - format!("endpoints[{index}].allowed_transports"), + format!("endpoints[{index}].transport"), message, )); } @@ -7099,7 +7080,7 @@ credentials: // -- L7 endpoint semantic validation (shared with runtime) ---------------- #[test] - fn profile_allowed_transports_round_trip_through_proto() { + fn profile_transport_round_trip_through_proto() { use openshell_core::proto::NetworkTransport; let source = r" @@ -7110,25 +7091,36 @@ endpoints: port: 8443 protocol: rest access: full - allowed_transports: [tls] + transport: tls "; let profile = parse_profile_yaml(source).expect("profile should parse"); let proto = profile.to_proto(); - assert_eq!( - proto.endpoints[0].allowed_transports, - [NetworkTransport::Tls as i32] - ); + assert_eq!(proto.endpoints[0].transport, NetworkTransport::Tls as i32); let exported = profile_to_yaml(&ProviderTypeProfile::from_proto(&proto)) .expect("profile should serialize"); let reparsed = parse_profile_yaml(&exported).expect("exported profile should parse"); - assert_eq!(reparsed.endpoints[0].allowed_transports, ["tls"]); + assert_eq!(reparsed.endpoints[0].transport, "tls"); - for entry in ["[]", "null", "[tls, tls]", "[https]"] { + for entry in ["null", "[tls]"] { assert!( - parse_profile_yaml(&source.replace("[tls]", entry)).is_err(), + parse_profile_yaml( + &source.replace("transport: tls", &format!("transport: {entry}")) + ) + .is_err(), "{entry}" ); } + let invalid_value = + parse_profile_yaml(&source.replace("transport: tls", "transport: https")) + .expect("profile shape should parse"); + let invalid_diagnostics = + validate_profile_set(&[("restricted.yaml".to_owned(), invalid_value)]); + assert!( + invalid_diagnostics + .iter() + .any(|diagnostic| diagnostic.field == "endpoints[0].transport") + ); + let skipped_tls = parse_profile_yaml(&source.replace("access: full", "access: full\n tls: skip")) .expect("profile shape should parse"); @@ -7136,7 +7128,7 @@ endpoints: assert!( diagnostics .iter() - .any(|diagnostic| diagnostic.field == "endpoints[0].allowed_transports") + .any(|diagnostic| diagnostic.field == "endpoints[0].transport") ); } diff --git a/crates/openshell-server/src/grpc/policy.rs b/crates/openshell-server/src/grpc/policy.rs index e211e4fac8..3ac503db41 100644 --- a/crates/openshell-server/src/grpc/policy.rs +++ b/crates/openshell-server/src/grpc/policy.rs @@ -13694,16 +13694,16 @@ mod tests { let state = test_server_state().await; for (port, explicit, requires_support) in [ - (443, Vec::new(), true), - (8443, vec![NetworkTransport::Plaintext as i32], true), - (8443, Vec::new(), false), + (443, NetworkTransport::Unspecified as i32, true), + (8443, NetworkTransport::Plaintext as i32, true), + (8443, NetworkTransport::Unspecified as i32, false), ] { let mut policy = test_policy_with_rule("base", "api.example.com"); let endpoint = &mut policy.network_policies.get_mut("base").unwrap().endpoints[0]; endpoint.protocol = "rest".to_string(); endpoint.access = NetworkAccessPreset::Full as i32; endpoint.port = port; - endpoint.allowed_transports = explicit; + endpoint.transport = explicit; state .store .put_message(&test_sandbox("sb-transport", "transport", policy, vec![])) @@ -13857,7 +13857,7 @@ when {{ context.method == "GET" }};"# endpoint.port = 443; endpoint.protocol = "rest".to_string(); endpoint.provider_credentialed = true; - endpoint.allowed_transports = vec![NetworkTransport::Tls as i32]; + endpoint.transport = NetworkTransport::Tls as i32; let policy = ProtoSandboxPolicy { cedar_policy: Some(openshell_core::proto::CedarPolicy { @@ -13887,7 +13887,7 @@ when {{ context.method == "GET" }};"# .endpoints[0]; endpoint.port = 443; endpoint.path = "/v1/**".to_string(); - endpoint.allowed_transports = vec![NetworkTransport::Plaintext as i32]; + endpoint.transport = NetworkTransport::Plaintext as i32; let policy = ProtoSandboxPolicy { cedar_policy: Some(openshell_core::proto::CedarPolicy { diff --git a/crates/openshell-server/src/storage_proto.rs b/crates/openshell-server/src/storage_proto.rs index c58cdc07ff..4bac541151 100644 --- a/crates/openshell-server/src/storage_proto.rs +++ b/crates/openshell-server/src/storage_proto.rs @@ -251,14 +251,14 @@ mod tests { // and the public/durable overlap remain unchanged. // The service backend HTTP version is part of both schemas. Legacy // endpoint records omit it and continue to use HTTP/1.1. - // NetworkEndpoint adds a repeated enum to both schemas. Legacy endpoint - // records decode with an empty list and select the endpoint default. + // NetworkEndpoint adds a scalar transport enum to both schemas. Legacy + // endpoint records decode as unspecified and select the endpoint default. const PUBLIC_RPC_SCHEMA_SHA256: &str = - "ae9342a1400d16120c814654f55f5048e0eefac9fdfc28afbd58ac6fc77b4301"; + "f7d47ed04a29f7ce099d8b89460e6a6c2006609b82201876996f5ec499980f9c"; // The storage.v2 refresh root adds retired handles and the first mint's // provider revision. All fields from the prior root retain their wire tags. const DURABLE_SCHEMA_SHA256: &str = - "70b94ef48e2d388afcc609ebc70f934da6d5533bd37a37b436b0d46a3c65bf55"; + "d28a01f623e82c759d0f8f72114ea6bb75b608a3cd0a7ff659d7a11ce93b6eec"; const PUBLIC_DURABLE_OVERLAP_SHA256: &str = "97abfec3c823db17b2904317f7da01c6d68a5db35398f788f2d9460ccdd1673a"; // Encoded with the schema that omitted stable_placeholder. Keep these @@ -831,14 +831,17 @@ mod tests { } #[test] - fn network_endpoint_without_transport_allowlist_decodes_empty() { - // Encoded using the descriptor before allowed_transports was added. + fn network_endpoint_without_transport_decodes_unspecified() { + // Encoded using the descriptor before transport was added. let bytes = legacy_bytes("0a0f6170692e6578616d706c652e636f6d10bb031a0472657374"); let endpoint = openshell_core::proto::NetworkEndpoint::decode(bytes.as_slice()).unwrap(); assert_eq!(endpoint.host, "api.example.com"); assert_eq!(endpoint.port, 443); assert_eq!(endpoint.protocol, "rest"); - assert!(endpoint.allowed_transports.is_empty()); + assert_eq!( + endpoint.transport, + openshell_core::proto::NetworkTransport::Unspecified as i32 + ); assert_eq!(endpoint.encode_to_vec(), bytes); } diff --git a/crates/openshell-supervisor-network/data/sandbox-policy.rego b/crates/openshell-supervisor-network/data/sandbox-policy.rego index 63ae1bf282..23512783d3 100644 --- a/crates/openshell-supervisor-network/data/sandbox-policy.rego +++ b/crates/openshell-supervisor-network/data/sandbox-policy.rego @@ -1127,5 +1127,5 @@ endpoint_has_extended_config(ep) if { } endpoint_has_extended_config(ep) if { - count(object.get(ep, "allowed_transports", [])) > 0 + object.get(ep, "transport", "") != "" } diff --git a/crates/openshell-supervisor-network/src/opa/raw_schema.rs b/crates/openshell-supervisor-network/src/opa/raw_schema.rs index e42652a219..7b76dd60bf 100644 --- a/crates/openshell-supervisor-network/src/opa/raw_schema.rs +++ b/crates/openshell-supervisor-network/src/opa/raw_schema.rs @@ -9,7 +9,7 @@ use miette::Result; use openshell_core::policy_l7::{ - network_tls_mode_from_str, network_transport_from_str, validate_allowed_transports, + network_tls_mode_from_str, network_transport_from_str, validate_endpoint_transport, }; use openshell_policy_schema::{ JsonRpcConfig, L7Allow, L7DenyRule, McpConfig, NetworkBinary, NetworkEndpoint, @@ -58,14 +58,10 @@ fn validate_endpoint(endpoint: &Value) -> Result<()> { fields.remove("mcp"); fields.remove("json_rpc"); let config = deserialize_known::(fields, diagnostic)?; - let transports: Option> = config - .allowed_transports - .iter() - .map(|label| network_transport_from_str(label).map(|transport| transport as i32)) - .collect(); - let transports = transports.ok_or_else(|| miette::miette!(diagnostic))?; + let transport = network_transport_from_str(&config.transport) + .ok_or_else(|| miette::miette!(diagnostic))? as i32; let tls = network_tls_mode_from_str(&config.tls).map_or(-1, |mode| mode as i32); - if validate_allowed_transports(&transports, &config.protocol, tls).is_some() { + if validate_endpoint_transport(transport, &config.protocol, tls).is_some() { return Err(miette::miette!(diagnostic)); } diff --git a/crates/openshell-supervisor-network/src/policy_local.rs b/crates/openshell-supervisor-network/src/policy_local.rs index 790ab9d1be..c25f826fcf 100644 --- a/crates/openshell-supervisor-network/src/policy_local.rs +++ b/crates/openshell-supervisor-network/src/policy_local.rs @@ -1311,7 +1311,7 @@ fn network_endpoint_from_json( protocol: endpoint.protocol, tls: openshell_policy::network_tls_mode_from_str(&endpoint.tls) .ok_or_else(|| format!("unknown tls value '{}'", endpoint.tls))? as i32, - allowed_transports: Vec::new(), + transport: 0, enforcement: openshell_policy::network_enforcement_mode_from_str(&endpoint.enforcement) .ok_or_else(|| format!("unknown enforcement value '{}'", endpoint.enforcement))? as i32, diff --git a/crates/openshell-supervisor-network/src/proxy.rs b/crates/openshell-supervisor-network/src/proxy.rs index 93df1ebcd8..bad8581967 100644 --- a/crates/openshell-supervisor-network/src/proxy.rs +++ b/crates/openshell-supervisor-network/src/proxy.rs @@ -4512,9 +4512,11 @@ fn query_allowed_transports(decision: &EgressDecision) -> Result Some(allowed), - Some(previous) => Some(previous.intersect(allowed).ok_or_else(|| { - miette::miette!("matched endpoints have disjoint allowed_transports") - })?), + Some(previous) => Some( + previous + .intersect(allowed) + .ok_or_else(|| miette::miette!("matched endpoints have disjoint transport"))?, + ), }; } Ok(effective) diff --git a/crates/openshell-supervisor-network/src/proxy/transport_tests.rs b/crates/openshell-supervisor-network/src/proxy/transport_tests.rs index c6a18be121..e3f5535d97 100644 --- a/crates/openshell-supervisor-network/src/proxy/transport_tests.rs +++ b/crates/openshell-supervisor-network/src/proxy/transport_tests.rs @@ -14,9 +14,8 @@ use tokio_rustls::TlsConnector; const HOST: &str = "host.openshell.internal"; const LOOPBACK: &str = "127.0.0.1:0"; const DEADLINE: Duration = Duration::from_secs(10); -const TLS_ONLY: &str = " allowed_transports: [tls]\n"; -const PLAINTEXT_ONLY: &str = " allowed_transports: [plaintext]\n"; -const BOTH_TRANSPORTS: &str = " allowed_transports: [tls, plaintext]\n"; +const TLS_ONLY: &str = " transport: tls\n"; +const PLAINTEXT_ONLY: &str = " transport: plaintext\n"; const CREDENTIALED: &str = " provider_credentialed: true\n"; const ORIGIN_RESPONSE: &[u8] = b"HTTP/1.1 200 OK\r\nContent-Length: 9\r\nConnection: close\r\n\r\norigin-ok"; @@ -210,7 +209,7 @@ async fn connect_enforces_plaintext_transport_before_sending_application_bytes() (443, TLS_ONLY, false), (8443, CREDENTIALED, false), (443, PLAINTEXT_ONLY, true), - (443, BOTH_TRANSPORTS, true), + (8443, "", true), ] { tokio::time::timeout(DEADLINE, async { let (listener, upstream) = upstream_listener().await; @@ -255,16 +254,15 @@ async fn connect_enforces_plaintext_transport_before_sending_application_bytes() #[tokio::test] async fn tls_connect_requires_an_allowed_transport_and_a_trusted_origin() { - for (endpoint_fields, origin_name, trusted) in [ - ("", HOST, true), - (TLS_ONLY, HOST, true), - (BOTH_TRANSPORTS, HOST, true), - (TLS_ONLY, "wrong.example.test", true), - (TLS_ONLY, HOST, false), - (PLAINTEXT_ONLY, HOST, true), + for (port, endpoint_fields, origin_name, trusted) in [ + (443, "", HOST, true), + (443, TLS_ONLY, HOST, true), + (8443, "", HOST, true), + (443, TLS_ONLY, "wrong.example.test", true), + (443, TLS_ONLY, HOST, false), + (443, PLAINTEXT_ONLY, HOST, true), ] { tokio::time::timeout(DEADLINE, async { - let port = 443; let plaintext_only = endpoint_fields == PLAINTEXT_ONLY; let origin_verified = trusted && origin_name == HOST; let (listener, upstream) = upstream_listener().await; @@ -375,8 +373,8 @@ async fn absolute_form_http_enforces_the_same_transport_policy() { #[tokio::test] async fn mixed_transports_never_fall_back_to_an_opaque_tunnel() { let (listener, upstream) = upstream_listener().await; - let (mut client, proxy) = proxy_connection(443, BOTH_TRANSPORTS, None, Some(upstream)).await; - start_connect(&mut client, 443).await; + let (mut client, proxy) = proxy_connection(8443, "", None, Some(upstream)).await; + start_connect(&mut client, 8443).await; client.write_all(b"SSH-2.0-test\r\n").await.unwrap(); client.shutdown().await.unwrap(); tokio::time::timeout(DEADLINE, proxy) @@ -483,7 +481,7 @@ fn raw_transparent_tcp_fails_closed_for_inspected_http_endpoints() { (8443, " protocol: rest\n access: full\n", true), ( 8443, - " protocol: rest\n access: full\n allowed_transports: [plaintext]\n", + " protocol: rest\n access: full\n transport: plaintext\n", true, ), (8443, " protocol: tcp\n", false), diff --git a/e2e/python/test_sandbox_providers.py b/e2e/python/test_sandbox_providers.py index 3240f1a33d..bc562ecac0 100644 --- a/e2e/python/test_sandbox_providers.py +++ b/e2e/python/test_sandbox_providers.py @@ -188,7 +188,7 @@ def _native_inference_profile( port=port, protocol="rest", tls=sandbox_pb2.NETWORK_TLS_MODE_UNSPECIFIED, - allowed_transports=[sandbox_pb2.NETWORK_TRANSPORT_PLAINTEXT], + transport=sandbox_pb2.NETWORK_TRANSPORT_PLAINTEXT, enforcement=sandbox_pb2.NETWORK_ENFORCEMENT_MODE_ENFORCE, rules=rules, allowed_ips=[ diff --git a/e2e/rust/tests/kubernetes_shared_supervisor.rs b/e2e/rust/tests/kubernetes_shared_supervisor.rs index 7a9b8c7184..ee6ecfef6a 100644 --- a/e2e/rust/tests/kubernetes_shared_supervisor.rs +++ b/e2e/rust/tests/kubernetes_shared_supervisor.rs @@ -293,7 +293,7 @@ endpoints: - host: {TEST_HOST} port: {port} protocol: rest - allowed_transports: [plaintext] + transport: plaintext access: full binaries: - path: /usr/bin/python* @@ -308,7 +308,7 @@ fn policy(ports: &[u16]) -> NamedTempFile { let endpoints = ports.iter().fold(String::new(), |mut endpoints, port| { let _ = write!( endpoints, - " - host: {TEST_HOST}\n port: {port}\n protocol: rest\n allowed_transports: [plaintext]\n access: full\n" + " - host: {TEST_HOST}\n port: {port}\n protocol: rest\n transport: plaintext\n access: full\n" ); endpoints }); diff --git a/e2e/rust/tests/kubernetes_shared_supervisor_spiffe.rs b/e2e/rust/tests/kubernetes_shared_supervisor_spiffe.rs index 1b60169cac..0df3ab8ffa 100644 --- a/e2e/rust/tests/kubernetes_shared_supervisor_spiffe.rs +++ b/e2e/rust/tests/kubernetes_shared_supervisor_spiffe.rs @@ -453,7 +453,7 @@ endpoints: port: {target_port} path: /** protocol: rest - allowed_transports: [plaintext] + transport: plaintext access: read-write enforcement: enforce allowed_ips: diff --git a/e2e/rust/tests/provider_readiness.rs b/e2e/rust/tests/provider_readiness.rs index bbe9cc59f1..5de164d5ff 100644 --- a/e2e/rust/tests/provider_readiness.rs +++ b/e2e/rust/tests/provider_readiness.rs @@ -890,7 +890,7 @@ fn write_policy( .map(|(host, port)| { json!({"host": host, "port": port, "path": "/**", "protocol": "rest", "access": "full", "enforcement": "enforce", - "allowed_transports": ["tls"], + "transport": "tls", "allowed_ips": [host]}) }) .collect::>(); diff --git a/e2e/rust/tests/stable_external_placeholders.rs b/e2e/rust/tests/stable_external_placeholders.rs index 67617303fa..19204f4b67 100644 --- a/e2e/rust/tests/stable_external_placeholders.rs +++ b/e2e/rust/tests/stable_external_placeholders.rs @@ -835,7 +835,7 @@ fn write_policy( .map(|(host, port)| { json!({"host": host, "port": port, "path": "/**", "protocol": "rest", "access": "full", "enforcement": "enforce", - "allowed_transports": ["tls"], + "transport": "tls", "allowed_ips": ["10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "fc00::/7"]}) }) .collect::>(); diff --git a/e2e/rust/tests/support/provider_refresh_handles.rs b/e2e/rust/tests/support/provider_refresh_handles.rs index 6dfcc89127..45a31a2e46 100644 --- a/e2e/rust/tests/support/provider_refresh_handles.rs +++ b/e2e/rust/tests/support/provider_refresh_handles.rs @@ -98,7 +98,7 @@ endpoints: port: {resource_port} path: /probe protocol: rest - allowed_transports: [{transport}] + transport: {transport} access: full enforcement: enforce allowed_ips: @@ -159,7 +159,7 @@ network_policies: port: {resource_port} path: /probe protocol: rest - allowed_transports: [{transport}] + transport: {transport} access: full enforcement: enforce allowed_ips: diff --git a/proto/sandbox.proto b/proto/sandbox.proto index b5e55b5fd5..8a76b84c44 100644 --- a/proto/sandbox.proto +++ b/proto/sandbox.proto @@ -148,13 +148,14 @@ enum NetworkTlsMode { NETWORK_TLS_MODE_PASSTHROUGH = 3 [deprecated = true]; } -// Transport accepted by an inspected HTTP-family endpoint. +// Wire transport policy for an inspected HTTP-family endpoint. enum NetworkTransport { - // Rejected in an explicit transport allowlist. + // Use the endpoint's default: TLS on port 443 and credentialed endpoints; + // either TLS or plaintext on other inspected HTTP endpoints. NETWORK_TRANSPORT_UNSPECIFIED = 0; - // TLS from the workload and verified TLS to the destination. + // Require TLS from the workload and verified TLS to the destination. NETWORK_TRANSPORT_TLS = 1; - // Inspected plaintext HTTP. + // Require inspected plaintext HTTP. NETWORK_TRANSPORT_PLAINTEXT = 2; } @@ -278,10 +279,11 @@ message NetworkEndpoint { // It binds the provider record and complete profile policy, or the active // global policy, to this endpoint. User-authored values are ignored. string token_grant_owner = 27; - // Allowed transports for an inspected HTTP-family endpoint. Empty selects - // the endpoint's default. Explicit values must be unique and cannot be - // combined with tls: skip. - repeated NetworkTransport allowed_transports = 28; + // Wire transport policy for an inspected HTTP-family endpoint. Unspecified + // selects the endpoint's default (TLS on port 443 and credentialed + // endpoints; either TLS or plaintext on other inspected HTTP endpoints). + // Cannot be combined with tls: skip or non-HTTP protocols. + NetworkTransport transport = 28; } // MCP options are grouped so MCP-specific policy can grow without adding more diff --git a/tests/suites/conformance/src/credential_gating.rs b/tests/suites/conformance/src/credential_gating.rs index d5d16191cf..c5c703876b 100644 --- a/tests/suites/conformance/src/credential_gating.rs +++ b/tests/suites/conformance/src/credential_gating.rs @@ -50,7 +50,7 @@ async fn profile_rest_endpoint_keeps_body_placeholder(cx: &mut Context) -> testk allow_host(&mut policy, "credential_gating", server.port) .rest(Access::Full) .request_body_credential_rewrite(false) - .allowed_transports = vec![PLAINTEXT]; + .transport = PLAINTEXT; let sandbox = create_sandbox(cx, "rest", policy, &[&provider]).await?; post_token_body(&sandbox, server.port).await?; expect_placeholder_body(&server).await @@ -128,7 +128,7 @@ async fn policy_binding_rest_body_keeps_placeholder_without_rewrite( .rest(Access::Full) .request_body_credential_rewrite(false) .credential_binding(&provider) - .allowed_transports = vec![PLAINTEXT]; + .transport = PLAINTEXT; let sandbox = create_sandbox(cx, "body", policy, &[&provider]).await?; post_token_body(&sandbox, server.port).await?; expect_placeholder_body(&server).await @@ -148,7 +148,7 @@ async fn policy_binding_rest_body_rewrite_sends_secret_upstream( .rest(Access::Full) .request_body_credential_rewrite(true) .credential_binding(&provider) - .allowed_transports = vec![PLAINTEXT]; + .transport = PLAINTEXT; let sandbox = create_sandbox(cx, "rw", policy, &[&provider]).await?; post_token_body(&sandbox, server.port).await?; let request = one_request(&server).await?; @@ -205,7 +205,7 @@ async fn profile_rest_endpoint_rewrites_header_and_body(cx: &mut Context) -> tes .path("/probe") .enforce() .request_body_credential_rewrite(true) - .allowed_transports = vec![PLAINTEXT]; + .transport = PLAINTEXT; }) .await?; let token = provider_token(&sandbox).await?; @@ -251,7 +251,7 @@ async fn profile_websocket_endpoint_rewrites_text_frames(cx: &mut Context) -> te let server = WebSocketRecorder::start().await?; let sandbox = profile_endpoint_sandbox(cx, "wstxt", server.port, |ep| { ep.websocket(Access::ReadWrite).path("/ws").enforce(); - ep.allowed_transports = vec![PLAINTEXT]; + ep.transport = PLAINTEXT; ep.websocket_credential_rewrite = true; }) .await?; @@ -300,7 +300,7 @@ async fn profile_endpoints_bind_static_credentials(cx: &mut Context) -> testkit: let endpoint = |port| { format!( "{{host: {TEST_HOST}, port: {port}, path: /**, protocol: rest, access: full, \ - enforcement: enforce, allowed_transports: [plaintext]}}" + enforcement: enforce, transport: plaintext}}" ) }; let policy = policy::base_with(&format!( @@ -363,7 +363,7 @@ async fn send_binary_frame( let mut policy = policy::base(); allow_host(&mut policy, "credential_gating", server.port) .websocket(Access::ReadWrite) - .allowed_transports = vec![PLAINTEXT]; + .transport = PLAINTEXT; let sandbox = create_sandbox(cx, suffix, policy, providers).await?; sandbox .run_python( @@ -386,10 +386,10 @@ async fn install_gating_provider(cx: &Context, endpoints: Option<(u16, u16)>) -> if let Some((rest, websocket)) = endpoints { profile = profile .endpoint(TEST_HOST, rest, |ep| { - ep.rest(Access::Full).allowed_transports = vec![PLAINTEXT]; + ep.rest(Access::Full).transport = PLAINTEXT; }) .endpoint(TEST_HOST, websocket, |ep| { - ep.websocket(Access::ReadWrite).allowed_transports = vec![PLAINTEXT]; + ep.websocket(Access::ReadWrite).transport = PLAINTEXT; }); } install_gating_profile(cx, &profile).await @@ -427,7 +427,7 @@ async fn install_bound_provider( ep.rest(Access::Full) .path("/allowed/**") .enforce() - .allowed_transports = vec![PLAINTEXT]; + .transport = PLAINTEXT; }) .binaries([BASH]) .to_yaml()?; diff --git a/tests/suites/features/provider-token-exchange/tests/token_exchange.rs b/tests/suites/features/provider-token-exchange/tests/token_exchange.rs index 1e8df3f0ef..87e166bdd1 100644 --- a/tests/suites/features/provider-token-exchange/tests/token_exchange.rs +++ b/tests/suites/features/provider-token-exchange/tests/token_exchange.rs @@ -550,10 +550,7 @@ fn grants_profile( }), ) .endpoint(TEST_HOST, target_port, |ep| { - ep.rest(Access::ReadWrite) - .enforce() - .path("/**") - .allowed_transports = vec![PLAINTEXT]; + ep.rest(Access::ReadWrite).enforce().path("/**").transport = PLAINTEXT; }) .binaries(["/**"]) } @@ -579,7 +576,7 @@ fn route_profile(profile_type: &str, token_port: u16, target_port: u16, route: & ep.rest(Access::ReadWrite) .enforce() .path(&format!("/{route}/**")) - .allowed_transports = vec![PLAINTEXT]; + .transport = PLAINTEXT; }) .binaries(["/**"]) } From 7c8126c0cfda5ece4310ee86857d9fa149d8bfbe Mon Sep 17 00:00:00 2001 From: freeqaz Date: Wed, 2 Dec 2026 09:16:07 +0000 Subject: [PATCH 09/11] fix(server): require endpoint transport capability only when transport is explicit - Gate POLICY_ENDPOINT_TRANSPORTS_V1 only on endpoints that explicitly set transport (tls or plaintext) in YAML/proto or Cedar provider rules. - Prevents gateway-first rolling upgrades (such as Helm/Docker deployments with long-lived sandboxes) from fail-closing existing sandboxes whose policies omit transport on port 443 or credentialed endpoints, while newly created/upgraded supervisors still enforce TLS by default and explicit transport policies still fail closed on incompatible supervisors. Signed-off-by: freeqaz --- crates/openshell-core/src/policy_l7.rs | 26 ++++++++++++------- .../openshell-policy-cedar-adapter/src/lib.rs | 20 +++++++++----- .../src/config_delivery/session.rs | 26 ++++++++++++++++--- crates/openshell-server/src/grpc/policy.rs | 18 ++++++++++--- 4 files changed, 67 insertions(+), 23 deletions(-) diff --git a/crates/openshell-core/src/policy_l7.rs b/crates/openshell-core/src/policy_l7.rs index e77f85fda7..a814090f89 100644 --- a/crates/openshell-core/src/policy_l7.rs +++ b/crates/openshell-core/src/policy_l7.rs @@ -156,15 +156,17 @@ pub fn endpoint_allowed_transports( .flatten() } -/// Whether `endpoint` requires a supervisor that enforces endpoint transport -/// restrictions (either an explicit `transport` or a TLS-only default on any -/// selected port). +/// Whether `endpoint` requires a supervisor that advertises +/// `POLICY_ENDPOINT_TRANSPORTS_V1`. +/// +/// Only explicit `transport` values trigger capability gating so that +/// gateway-first rolling upgrades (such as Helm/Docker deployments with +/// long-lived sandboxes) do not fail-close existing sandboxes whose policies +/// omit `transport`. Upgraded supervisors still enforce the TLS-by-default +/// rule on port 443 and credentialed endpoints automatically. #[must_use] pub fn endpoint_requires_transport_enforcement(endpoint: &NetworkEndpoint) -> bool { endpoint.transport != NetworkTransport::Unspecified as i32 - || selector_ports(endpoint).iter().any(|&port| { - endpoint_allowed_transports(endpoint, port) == Some(AllowedTransports::Tls) - }) } pub fn network_enforcement_mode_from_str(value: &str) -> Option { @@ -382,7 +384,7 @@ mod transport_tests { } #[test] - fn transport_enforcement_requirement_tracks_defaults_and_explicit_lists() { + fn transport_enforcement_requirement_tracks_explicit_transport_only() { let mut endpoint = NetworkEndpoint { protocol: "rest".into(), port: 8443, @@ -390,14 +392,20 @@ mod transport_tests { }; assert!(!endpoint_requires_transport_enforcement(&endpoint)); + // Omitted transport on port 443 or credentialed endpoints relies on + // supervisor defaults without fail-closing legacy supervisors during a + // gateway-first rolling upgrade. endpoint.port = 443; - assert!(endpoint_requires_transport_enforcement(&endpoint)); + assert!(!endpoint_requires_transport_enforcement(&endpoint)); endpoint.port = 8443; endpoint.provider_credentialed = true; - assert!(endpoint_requires_transport_enforcement(&endpoint)); + assert!(!endpoint_requires_transport_enforcement(&endpoint)); endpoint.provider_credentialed = false; + endpoint.transport = NetworkTransport::Tls as i32; + assert!(endpoint_requires_transport_enforcement(&endpoint)); + endpoint.transport = NetworkTransport::Plaintext as i32; assert!(endpoint_requires_transport_enforcement(&endpoint)); } diff --git a/crates/openshell-policy-cedar-adapter/src/lib.rs b/crates/openshell-policy-cedar-adapter/src/lib.rs index f672976424..d9e37e6888 100644 --- a/crates/openshell-policy-cedar-adapter/src/lib.rs +++ b/crates/openshell-policy-cedar-adapter/src/lib.rs @@ -95,9 +95,6 @@ pub fn analyze_engine_provider_transports( let mut requires_transport_support = false; for (port, cedar_entries) in &cedar_by_port { - if *port == 443 { - requires_transport_support = true; - } let mut inspected_providers: Vec<(&str, usize, &NetworkEndpoint, AllowedTransports)> = Vec::new(); for &(rule_name, endpoint_index, endpoint) in &providers { @@ -122,8 +119,8 @@ pub fn analyze_engine_provider_transports( u32::from(*port), ) { Ok(Some(transports)) => { - if endpoint.transport != openshell_core::proto::NetworkTransport::Unspecified as i32 - || transports == AllowedTransports::Tls + if endpoint.transport + != openshell_core::proto::NetworkTransport::Unspecified as i32 { requires_transport_support = true; } @@ -280,7 +277,18 @@ when { context.method == "GET" }; "#; let analysis = analyze_provider_transports(cedar_443, &HashMap::new()).unwrap(); assert!(analysis.conflicts.is_empty()); - assert!(analysis.requires_transport_support); + assert!(!analysis.requires_transport_support); + + let explicit_tls = NetworkEndpoint { + host: "api.example.com".to_string(), + port: 443, + transport: NetworkTransport::Tls as i32, + ..Default::default() + }; + let explicit_analysis = + analyze_provider_transports(cedar_443, &provider_rules(vec![explicit_tls])).unwrap(); + assert!(explicit_analysis.conflicts.is_empty()); + assert!(explicit_analysis.requires_transport_support); let partial_plaintext = NetworkEndpoint { host: "api.example.com".to_string(), diff --git a/crates/openshell-server/src/config_delivery/session.rs b/crates/openshell-server/src/config_delivery/session.rs index 6cff281b62..7a2a37afaf 100644 --- a/crates/openshell-server/src/config_delivery/session.rs +++ b/crates/openshell-server/src/config_delivery/session.rs @@ -2639,17 +2639,35 @@ BEGIN SELECT RAISE(ABORT, 'database unavailable'); END; #[tokio::test] async fn endpoint_transport_push_bootstrap_requires_a_capable_supervisor() { - let policy = openshell_policy::parse_sandbox_policy( + let sandbox_id = "sb-push-transports"; + + // Omitted transport on port 443 remains deliverable to older supervisors + // during gateway-first rolling upgrades. + let default_443 = openshell_policy::parse_sandbox_policy( "version: 1\nnetwork_policies:\n api:\n endpoints:\n - host: api.example.com\n port: 443\n protocol: rest\n access: full\n binaries:\n - path: /usr/bin/curl\n", ) .unwrap(); - let sandbox_id = "sb-push-transports"; - let state = push_state_with_policy(sandbox_id, policy.clone()).await; + let state = push_state_with_policy(sandbox_id, default_443).await; + let legacy_default = accepted_bootstrap( + &state, + sandbox_id, + StreamFeatures::ApplyWithoutEndpointTransports, + ) + .await; + assert!(legacy_default.configuration_admitted, "{legacy_default:?}"); + assert!(legacy_default.policy.is_some()); + + // Explicit transport requires POLICY_ENDPOINT_TRANSPORTS_V1. + let explicit_tls = openshell_policy::parse_sandbox_policy( + "version: 1\nnetwork_policies:\n api:\n endpoints:\n - host: api.example.com\n port: 443\n transport: tls\n protocol: rest\n access: full\n binaries:\n - path: /usr/bin/curl\n", + ) + .unwrap(); + let state = push_state_with_policy(sandbox_id, explicit_tls.clone()).await; let capable = accepted_bootstrap(&state, sandbox_id, StreamFeatures::Apply).await; assert!(capable.configuration_admitted, "{capable:?}"); assert!(capable.policy.is_some()); - let state = push_state_with_policy(sandbox_id, policy).await; + let state = push_state_with_policy(sandbox_id, explicit_tls).await; let incapable = accepted_bootstrap( &state, sandbox_id, diff --git a/crates/openshell-server/src/grpc/policy.rs b/crates/openshell-server/src/grpc/policy.rs index 3ac503db41..bc24866caf 100644 --- a/crates/openshell-server/src/grpc/policy.rs +++ b/crates/openshell-server/src/grpc/policy.rs @@ -13694,7 +13694,9 @@ mod tests { let state = test_server_state().await; for (port, explicit, requires_support) in [ - (443, NetworkTransport::Unspecified as i32, true), + (443, NetworkTransport::Unspecified as i32, false), + (443, NetworkTransport::Tls as i32, true), + (8443, NetworkTransport::Tls as i32, true), (8443, NetworkTransport::Plaintext as i32, true), (8443, NetworkTransport::Unspecified as i32, false), ] { @@ -13755,6 +13757,7 @@ mod tests { endpoint.protocol = "rest".to_string(); endpoint.access = openshell_core::proto::NetworkAccessPreset::Full as i32; endpoint.port = 443; + endpoint.transport = openshell_core::proto::NetworkTransport::Tls as i32; let snapshot = SandboxConfigSnapshot { policy: Some(policy), configuration_admitted: false, @@ -13808,9 +13811,15 @@ mod tests { #[cfg(feature = "experimental")] #[test] fn cedar_endpoint_transport_detection_uses_derived_inspection() { - for (port, credentialed, requires_support) in - [(443, false, true), (8443, true, true), (8443, false, false)] - { + use openshell_core::proto::NetworkTransport; + + for (port, credentialed, explicit_transport, requires_support) in [ + (443, false, NetworkTransport::Unspecified as i32, false), + (8443, true, NetworkTransport::Unspecified as i32, false), + (8443, true, NetworkTransport::Tls as i32, true), + (443, true, NetworkTransport::Plaintext as i32, true), + (8443, false, NetworkTransport::Unspecified as i32, false), + ] { let mut policy = ProtoSandboxPolicy { cedar_policy: Some(openshell_core::proto::CedarPolicy { source: format!( @@ -13832,6 +13841,7 @@ when {{ context.method == "GET" }};"# .endpoints[0]; endpoint.port = port; endpoint.provider_credentialed = true; + endpoint.transport = explicit_transport; policy.provider_credential_rules = provider.network_policies; } assert_eq!( From 30229380c782eb1086cb9967bb04ac2d1912eb58 Mon Sep 17 00:00:00 2001 From: freeqaz Date: Wed, 2 Dec 2026 09:16:55 +0000 Subject: [PATCH 10/11] docs(policy): document scalar transport field and explicit-only capability gating Signed-off-by: freeqaz --- docs/how-it-works/policies/network-rules.mdx | 65 ++++++++++---------- docs/how-it-works/policies/schema.mdx | 11 ++-- 2 files changed, 37 insertions(+), 39 deletions(-) diff --git a/docs/how-it-works/policies/network-rules.mdx b/docs/how-it-works/policies/network-rules.mdx index b7d5db4d3f..e0026f7261 100644 --- a/docs/how-it-works/policies/network-rules.mdx +++ b/docs/how-it-works/policies/network-rules.mdx @@ -121,57 +121,54 @@ protocol combine. Rules using another protocol cannot authorize the request; for example, a broader REST rule cannot allow a method excluded by a JSON-RPC route. Matching deny rules still take precedence over allows. -### Allowed Transports +### Transport -Use `allowed_transports` to choose how a client connects to an inspected HTTP -endpoint. Use `protocol` and `rules` to choose which requests it can send. +Use `transport` to require TLS or plaintext HTTP on an inspected HTTP endpoint. +Use `protocol` and `rules` to choose which requests the client can send. ```yaml endpoints: - host: api.example.com port: 8443 - allowed_transports: [tls] + transport: tls protocol: rest access: read-only enforcement: enforce - - host: legacy.example.com - port: 443 - allowed_transports: [tls, plaintext] + - host: internal.example.com + port: 8080 + transport: plaintext protocol: rest access: read-only enforcement: enforce ``` -| `allowed_transports` | Accepted connections | +| `transport` | Accepted connections | |---|---| -| `[tls]` | The client must use TLS. OpenShell terminates it and verifies the upstream server over a separate TLS connection. | -| `[plaintext]` | The client must send plaintext HTTP. | -| `[tls, plaintext]` | The client can use either. OpenShell still inspects the request. | +| `tls` | The client must use TLS. OpenShell terminates it and verifies the upstream server over a separate TLS connection. | +| `plaintext` | The client must send plaintext HTTP, which OpenShell forwards over plaintext HTTP (no upstream TLS origination). | -If you omit the field, inspected HTTP endpoints require TLS on port 443 and +If you omit `transport`, inspected HTTP endpoints require TLS on port 443 and on any port where the endpoint uses provider credentials, a credential binding, -or request signing. Other inspected HTTP endpoints accept both transports. -The default applies separately to each port in `ports`. - -Upgrade supervisors before upgrading the gateway. The default TLS-only rule on -port 443 and credentialed endpoints requires supervisor transport enforcement -even when `allowed_transports` is omitted. During a gateway-first rolling -upgrade, any sandbox whose effective policy contains an inspected HTTP endpoint -on port 443, a credentialed inspected HTTP endpoint, or an explicit -`allowed_transports` list receives a fail-closed unadmitted configuration until -its supervisor is upgraded. Older gateways also cannot preserve explicit -`allowed_transports` fields. - -When upgrading, check clients that send plaintext to those endpoints. Allow -`plaintext` explicitly only if the route is trusted to carry the request and -any credentials it uses without encryption. A failed TLS handshake never -retries in plaintext. Transport restrictions apply even in `audit` mode, and -inspected HTTP endpoints fail closed on the raw transparent TCP path instead of -bypassing HTTP/TLS inspection. - -Use this field with `rest`, `graphql`, `websocket`, `json-rpc`, or `mcp`. +or request signing. Other inspected HTTP endpoints continue to accept either +TLS or plaintext. The default applies separately to each port in `ports`. + +An older gateway cannot preserve an explicit `transport` field, and an upgraded +gateway refuses to deliver a policy with an explicit `transport` value to an +older supervisor (returning a fail-closed unadmitted configuration). Policies +that omit `transport` remain compatible with older supervisors during a +gateway-first rolling upgrade; newly created or upgraded supervisors enforce +the TLS-by-default rule on port 443 and credentialed endpoints automatically. + +When upgrading supervisors, check clients that send plaintext to port 443 or +credentialed endpoints. Set `transport: plaintext` only when the route is +trusted to carry the request and any credentials it uses without encryption. A +failed TLS handshake never retries in plaintext. Transport restrictions apply +even in `audit` mode, and inspected HTTP endpoints fail closed on the raw +transparent TCP path instead of bypassing HTTP/TLS inspection. + +Use `transport` with `rest`, `graphql`, `websocket`, `json-rpc`, or `mcp`. Native TCP and opaque `tls: skip` rules keep their existing behavior and do -not accept `allowed_transports`. +not accept `transport`. ### HTTP Connection Failures @@ -224,7 +221,7 @@ request access. Endpoints that can match the same host and port must also agree on settings such as `tls` and `allowed_ips`. Inspected HTTP endpoints that overlap on the same host and port intersect their effective transports (for example, a credentialed or `tls`-only endpoint tightens a shared port to TLS), -while disjoint transport sets (`[tls]` versus `[plaintext]`) and mixing `sql` +while disjoint effective transports (`tls` versus `plaintext`) and mixing `sql` with inspected HTTP on the same host and port are rejected. For example, suppose one rule allows `GET /repos/**` on a host and another rule diff --git a/docs/how-it-works/policies/schema.mdx b/docs/how-it-works/policies/schema.mdx index 6bd1522567..7b0ea4105b 100644 --- a/docs/how-it-works/policies/schema.mdx +++ b/docs/how-it-works/policies/schema.mdx @@ -159,7 +159,7 @@ the gateway host. | Field | Type | Default | Description | |---|---|---|---| | `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). | -| `allowed_transports` | list of strings | [By port and credentials](/how-it-works/policies/network-rules#allowed-transports) | Accept `tls`, `plaintext`, or both on an inspected HTTP endpoint. An explicit list must be nonempty and contain no duplicates. | +| `transport` | string | [By port and credentials](/how-it-works/policies/network-rules#transport) | Require `tls` or `plaintext` on an inspected HTTP endpoint. Omit to use port and credential defaults. | | `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. | | `access` | string | None | Access preset: `read-only`, `read-write`, or `full`. Refer to [Access Presets](#access-presets). | @@ -228,10 +228,11 @@ 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 HTTP endpoints that overlap on the same host and port must have - compatible effective transports (their intersection applies; disjoint `[tls]` - and `[plaintext]` sets are rejected), and `sql` cannot share a host and port - with inspected HTTP endpoints. Inspected endpoints that can match the same - request must also agree on `protocol`, `enforcement`, and credential settings. + compatible effective transports (their intersection applies; disjoint `tls` + and `plaintext` requirements are rejected), and `sql` cannot share a host and + port with inspected HTTP endpoints. Inspected endpoints that can match the + same request must also agree on `protocol`, `enforcement`, and credential + settings. Without `protocol`, `access` and `rules` have no effect. From d8b9d0a029791e5a1c89b4af1f37ed9d9354d02a Mon Sep 17 00:00:00 2001 From: Free Wortley Date: Wed, 2 Dec 2026 22:40:53 +0000 Subject: [PATCH 11/11] fix(cedar): reject conflicting transports on settings-derived routes Account for scoped endpoint settings when checking the transport shared by Cedar and provider routes. Use the same host matching at admission and runtime, and keep compatible provider paths available. Signed-off-by: Free Wortley --- .../openshell-policy-cedar-adapter/src/lib.rs | 226 +++++++++++++----- .../src/cedar_only/routes.rs | 12 +- .../src/cedar_only/tests.rs | 136 ++++++++++- crates/openshell-policy-cedar/src/lib.rs | 6 +- crates/openshell-server/src/grpc/policy.rs | 66 ++++- 5 files changed, 364 insertions(+), 82 deletions(-) diff --git a/crates/openshell-policy-cedar-adapter/src/lib.rs b/crates/openshell-policy-cedar-adapter/src/lib.rs index d9e37e6888..06047c055c 100644 --- a/crates/openshell-policy-cedar-adapter/src/lib.rs +++ b/crates/openshell-policy-cedar-adapter/src/lib.rs @@ -3,15 +3,14 @@ //! Adapts Cedar analysis to sandbox policy messages for gateway and runtime composition. -use std::collections::{BTreeMap, HashMap}; -use std::hash::BuildHasher; +use std::collections::BTreeMap; use miette::Result; use openshell_core::policy_l7::{ AllowedTransports, EffectiveFilesystem, L7Protocol, effective_allowed_transports, effective_endpoint_ports, endpoint_is_credentialed, }; -use openshell_core::proto::{FilesystemPolicy, NetworkEndpoint, NetworkPolicyRule, NetworkTlsMode}; +use openshell_core::proto::{FilesystemPolicy, NetworkEndpoint, NetworkTlsMode, SandboxPolicy}; use openshell_policy_cedar::CedarEngine; pub mod endpoint_status; @@ -71,16 +70,17 @@ pub struct CedarTransportAnalysis { /// Analyze effective transport constraints of a Cedar policy and attached /// provider rules using an already-parsed [`CedarEngine`]. #[must_use] -pub fn analyze_engine_provider_transports( +pub fn analyze_engine_provider_transports( engine: &CedarEngine, - provider_rules: &HashMap, + policy: &SandboxPolicy, ) -> CedarTransportAnalysis { let mut cedar_by_port: BTreeMap> = BTreeMap::new(); for (host, port, path, _) in engine.configured_l7_endpoints() { cedar_by_port.entry(port).or_default().push((host, path)); } - let mut providers: Vec<(&str, usize, &NetworkEndpoint)> = provider_rules + let mut providers: Vec<(&str, usize, &NetworkEndpoint)> = policy + .provider_credential_rules .iter() .flat_map(|(name, rule)| { rule.endpoints @@ -150,37 +150,82 @@ pub fn analyze_engine_provider_transports( } } - if *port == 443 { - for &(rule_name, endpoint_index, endpoint, transports) in &inspected_providers { - if transports != AllowedTransports::Plaintext { - continue; + // A Cedar-only route on 443 defaults to TLS. The runtime creates one + // for each inspected path (including paths introduced by settings) + // unless a matching provider already supplies that exact path. + if *port == 443 + && inspected_providers + .iter() + .any(|p| p.3 == AllowedTransports::Plaintext) + { + let mut by_path: BTreeMap<&str, Vec<&str>> = BTreeMap::new(); + for (_, _, provider, _) in &inspected_providers { + by_path + .entry(&provider.path) + .or_default() + .push(&provider.host); + } + let scoped_settings = policy + .endpoint_settings + .iter() + .filter(|s| { + !s.path.is_empty() + && !s.host.is_empty() + && effective_endpoint_ports(s).contains(&443) + }) + .collect::>(); + // Only retain the settings for one inspection at a time. Report + // at most one conflicting default route per plaintext provider. + let mut plaintext = inspected_providers + .iter() + .filter(|p| p.3 == AllowedTransports::Plaintext) + .collect::>(); + for (host, path) in cedar_entries { + if plaintext.is_empty() { + break; } - for (cedar_host, cedar_path) in cedar_entries { - if !openshell_core::host_pattern::host_patterns_overlap( - &endpoint.host, - cedar_host, - ) - .unwrap_or(false) - { - continue; - } - let path_covered_for_provider = - inspected_providers.iter().any(|(_, _, q, _)| { - q.path == *cedar_path - && (q.host.eq_ignore_ascii_case(&endpoint.host) - || openshell_core::host_pattern::host_matches( - &q.host, - &endpoint.host, - ) - .unwrap_or(false)) - }); - if !path_covered_for_provider { - conflicts.push(format!( - "provider policy '{rule_name}' endpoint[{endpoint_index}] ({}:443) allows plaintext, conflicting with Cedar-inspected endpoint '{cedar_host}:443' (default TLS)", - endpoint.host - )); + let settings = scoped_settings + .iter() + .copied() + .filter(|s| { + s.path != *path + && hosts_overlap(&s.host, host) + && openshell_core::endpoint_path::matches(path, &s.path) + }) + .collect::>(); + plaintext.retain(|&&(rule_name, endpoint_index, endpoint, _)| { + if !hosts_overlap(&endpoint.host, host) { + return true; } - } + let covered = |route: &str, setting_host: Option<&str>| { + by_path.get(route).is_some_and(|providers| { + providers.iter().any(|provider| { + covers_hosts(provider, &endpoint.host) + || covers_hosts(provider, host) + || setting_host.is_some_and(|s| covers_hosts(provider, s)) + }) + }) + }; + let conflict = if !covered(path, None) { + Some(path.as_str()) + } else { + settings + .iter() + .find(|s| { + hosts_overlap(&s.host, &endpoint.host) + && !covered(&s.path, Some(&s.host)) + }) + .map(|s| s.path.as_str()) + }; + let Some(uncovered) = conflict else { + return true; + }; + conflicts.push(format!( + "provider policy '{rule_name}' endpoint[{endpoint_index}] ({}:443) allows plaintext, conflicting with Cedar-inspected endpoint '{host}:443' path '{uncovered}' (default TLS)", + endpoint.host + )); + false + }); } } } @@ -191,18 +236,82 @@ pub fn analyze_engine_provider_transports( } } +/// Match a provider or endpoint setting exactly as the Cedar route planner does. +#[must_use] +pub fn endpoint_host_matches(pattern: &str, host: &str) -> bool { + if pattern.contains('*') { + openshell_core::host_pattern::host_matches(pattern, host).unwrap_or(false) + } else { + pattern.eq_ignore_ascii_case(host) + } +} + +fn hosts_overlap(left: &str, right: &str) -> bool { + if !left.contains('*') { + return endpoint_host_matches(right, left); + } + if !right.contains('*') { + return endpoint_host_matches(left, right); + } + if left.contains(['?', '[']) || right.contains(['?', '[']) { + return openshell_core::host_pattern::host_patterns_overlap(left, right).unwrap_or(false); + } + openshell_policy_cedar::host_patterns_overlap( + &left.to_ascii_lowercase(), + &right.to_ascii_lowercase(), + ) +} + +// A provider covering any one of the selectors covers their intersection. +// A leading ** consumes at least one label. Treat other glob containment +// conservatively rather than matching a glob string as a concrete host. +fn covers_hosts(provider: &str, selector: &str) -> bool { + if !selector.contains('*') { + return endpoint_host_matches(provider, selector); + } + let mut outer = provider.rsplit('.').peekable(); + let mut inner = selector.rsplit('.'); + while let Some(label) = outer.next() { + let Some(selected) = inner.next() else { + return false; + }; + if label == "**" && outer.peek().is_none() { + return true; + } + if label.eq_ignore_ascii_case(selected) { + continue; + } + if selected == "**" { + return false; + } + // A single star covers a label if its fixed prefix and suffix are + // guaranteed by the selected label (e.g. a* covers ab*). + let Some((prefix, suffix)) = label.split_once('*') else { + return false; + }; + if prefix.contains(['?', '[']) || suffix.contains(['*', '?', '[']) { + return false; + } + let selected = selected.to_ascii_lowercase(); + if selected.len() < prefix.len() + suffix.len() + || !selected.starts_with(&prefix.to_ascii_lowercase()) + || !selected.ends_with(&suffix.to_ascii_lowercase()) + { + return false; + } + } + inner.next().is_none() +} + /// Parse Cedar source once and analyze transport compatibility and capability /// requirements with attached provider rules. /// /// # Errors /// Returns an error if the Cedar policy cannot be loaded. -pub fn analyze_provider_transports( - source: &str, - provider_rules: &HashMap, -) -> Result { - let engine = - CedarEngine::from_policy_str(source).map_err(|error| miette::miette!("{error}"))?; - Ok(analyze_engine_provider_transports(&engine, provider_rules)) +pub fn analyze_provider_transports(policy: &SandboxPolicy) -> Result { + let engine = CedarEngine::from_policy_str(policy.cedar_source()) + .map_err(|error| miette::miette!("{error}"))?; + Ok(analyze_engine_provider_transports(&engine, policy)) } /// Returns the first inspected `host:port` that `endpoint` selects when it @@ -255,15 +364,22 @@ mod tests { use super::*; use openshell_core::proto::NetworkTransport; - fn provider_rules(endpoints: Vec) -> HashMap { - HashMap::from([( - "provider".to_string(), - NetworkPolicyRule { - name: "provider".to_string(), - endpoints, - ..Default::default() - }, - )]) + fn provider_policy(source: &str, endpoints: Vec) -> SandboxPolicy { + use openshell_core::proto::{CedarPolicy, NetworkPolicyRule}; + SandboxPolicy { + cedar_policy: Some(CedarPolicy { + source: source.into(), + }), + provider_credential_rules: std::collections::HashMap::from([( + "provider".to_string(), + NetworkPolicyRule { + name: "provider".to_string(), + endpoints, + ..Default::default() + }, + )]), + ..Default::default() + } } #[test] @@ -275,7 +391,7 @@ permit (principal, action == Sandbox::Action::"HttpRequest", resource == Sandbox::NetworkEndpoint::"api.example.com:443") when { context.method == "GET" }; "#; - let analysis = analyze_provider_transports(cedar_443, &HashMap::new()).unwrap(); + let analysis = analyze_provider_transports(&provider_policy(cedar_443, vec![])).unwrap(); assert!(analysis.conflicts.is_empty()); assert!(!analysis.requires_transport_support); @@ -286,7 +402,7 @@ when { context.method == "GET" }; ..Default::default() }; let explicit_analysis = - analyze_provider_transports(cedar_443, &provider_rules(vec![explicit_tls])).unwrap(); + analyze_provider_transports(&provider_policy(cedar_443, vec![explicit_tls])).unwrap(); assert!(explicit_analysis.conflicts.is_empty()); assert!(explicit_analysis.requires_transport_support); @@ -298,7 +414,7 @@ when { context.method == "GET" }; ..Default::default() }; let conflict = - analyze_provider_transports(cedar_443, &provider_rules(vec![partial_plaintext])) + analyze_provider_transports(&provider_policy(cedar_443, vec![partial_plaintext])) .unwrap(); assert_eq!(conflict.conflicts.len(), 1); assert!(conflict.requires_transport_support); @@ -318,7 +434,7 @@ permit (principal, action == Sandbox::Action::"NetworkConnect", ..Default::default() }; let uninspected = - analyze_provider_transports(l4_only, &provider_rules(vec![provider_ep])).unwrap(); + analyze_provider_transports(&provider_policy(l4_only, vec![provider_ep])).unwrap(); assert!(uninspected.conflicts.is_empty()); assert!(!uninspected.requires_transport_support); } diff --git a/crates/openshell-policy-cedar-runtime/src/cedar_only/routes.rs b/crates/openshell-policy-cedar-runtime/src/cedar_only/routes.rs index d2fbdc7666..0f4f64ec1e 100644 --- a/crates/openshell-policy-cedar-runtime/src/cedar_only/routes.rs +++ b/crates/openshell-policy-cedar-runtime/src/cedar_only/routes.rs @@ -128,10 +128,8 @@ impl LoadedPolicy { .build() ); } - let transport_analysis = openshell_policy_cedar_adapter::analyze_engine_provider_transports( - &cedar, - &policy.provider_credential_rules, - ); + let transport_analysis = + openshell_policy_cedar_adapter::analyze_engine_provider_transports(&cedar, policy); if !transport_analysis.conflicts.is_empty() { return Err(miette::miette!( "provider credential rules have conflicting endpoint transports with Cedar policy: {}", @@ -866,11 +864,7 @@ fn selector_matches(host_pattern: &str, ports: &[u16], host: &str, port: u16) -> if !ports.contains(&port) || host_pattern.is_empty() { return false; } - if host_pattern.contains('*') { - openshell_core::host_pattern::host_matches(host_pattern, host).unwrap_or(false) - } else { - host_pattern == host - } + openshell_policy_cedar_adapter::endpoint_host_matches(host_pattern, host) } /// One `endpoint_settings` entry: an endpoint selector and its settings. diff --git a/crates/openshell-policy-cedar-runtime/src/cedar_only/tests.rs b/crates/openshell-policy-cedar-runtime/src/cedar_only/tests.rs index cf624297b3..562d84d094 100644 --- a/crates/openshell-policy-cedar-runtime/src/cedar_only/tests.rs +++ b/crates/openshell-policy-cedar-runtime/src/cedar_only/tests.rs @@ -1931,18 +1931,20 @@ fn provider_plaintext_conflicting_with_cedar_443_default_fails_at_load_time() { ); } -#[test] -fn provider_plaintext_covering_entire_cedar_443_route_loads_cleanly() { - use openshell_core::policy_l7::AllowedTransports; - use openshell_core::proto::NetworkTransport; - - let cedar = r#" +const SINGLE_HTTP_AUTHORITY: &str = r#" permit (principal, action == Sandbox::Action::"NetworkConnect", resource == Sandbox::NetworkEndpoint::"api.example.com:443"); permit (principal, action == Sandbox::Action::"HttpRequest", resource == Sandbox::NetworkEndpoint::"api.example.com:443") when { context.method == "GET" }; "#; + +#[test] +fn provider_plaintext_covering_entire_cedar_443_route_loads_cleanly() { + use openshell_core::policy_l7::AllowedTransports; + use openshell_core::proto::NetworkTransport; + + let cedar = SINGLE_HTTP_AUTHORITY; let mut provider = credentialed_endpoint(); provider.path.clear(); provider.port = 443; @@ -1959,6 +1961,128 @@ when { context.method == "GET" }; ); } +#[test] +fn scoped_setting_transport_conflict_is_rejected_before_connect() { + use openshell_core::proto::NetworkTransport; + + let mut provider = credentialed_endpoint(); + provider.path.clear(); + provider.transport = NetworkTransport::Plaintext as i32; + let mut policy = provider_policy(SINGLE_HTTP_AUTHORITY, vec![provider.clone()]); + let mut scoped = setting("api.example.com", "/v1/**"); + scoped.allow_encoded_slash = true; + policy.endpoint_settings = vec![scoped.clone()]; + let error = CedarOnlyEngine::from_proto(&policy) + .expect_err("a settings-only route defaults to TLS on the shared port"); + assert!( + error + .to_string() + .contains("conflicting endpoint transports"), + "{error:?}" + ); + + // A different host, a different port, or a host-wide setting does not add + // an inspected path on this authority. + for (host, port, path) in [ + ("other.example.com", 443, "/v1/**"), + ("api.example.com", 8443, "/v1/**"), + ("api.example.com", 443, ""), + ] { + let mut other = setting(host, path); + other.port = port; + other.allow_encoded_slash = true; + policy.endpoint_settings = vec![other]; + CedarOnlyEngine::from_proto(&policy).expect("unrelated settings must not conflict"); + } + + // An explicit Provider route at the setting's exact path prevents a + // settings-only route. A wildcard Provider still covers the exact host. + let mut nested = provider.clone(); + nested.path.clone_from(&scoped.path); + provider.host = "*.example.com".into(); + let mut covered = provider_policy(SINGLE_HTTP_AUTHORITY, vec![provider, nested]); + covered.endpoint_settings = vec![scoped]; + let engine = + CedarOnlyEngine::from_proto(&covered).expect("both paths explicitly select plaintext"); + let configs = engine.credential_guards("api.example.com", 443).unwrap(); + assert_eq!(configs.len(), 2); + assert!(configs.iter().all(|c| c.allowed_transports_for_port(443) + == Ok(Some( + openshell_core::policy_l7::AllowedTransports::Plaintext + )))); +} + +#[test] +fn setting_transport_coverage_follows_runtime_host_matching() { + use openshell_core::proto::NetworkTransport; + let mut base = credentialed_endpoint(); + base.path.clear(); + base.transport = NetworkTransport::Plaintext as i32; + let mut scoped = setting("api.example.com", "/v1/**"); + scoped.allow_encoded_slash = true; + let mut nested = base.clone(); + nested.path.clone_from(&scoped.path); + for host in ["ap?.example.com", "ap[i].example.com"] { + nested.host = host.into(); + let mut policy = provider_policy(SINGLE_HTTP_AUTHORITY, vec![base.clone(), nested.clone()]); + policy.endpoint_settings = vec![scoped.clone()]; + let error = CedarOnlyEngine::from_proto(&policy).expect_err("non-star selector is literal"); + assert!( + error + .to_string() + .contains("conflicting endpoint transports"), + "{error:?}" + ); + } + base.host = "*.example.com".into(); + scoped.host = base.host.clone(); + nested.host = "**.example.com".into(); + let mut covered = provider_policy(GLOB_INSPECTED, vec![base.clone(), nested.clone()]); + covered.endpoint_settings = vec![scoped.clone()]; + CedarOnlyEngine::from_proto(&covered) + .expect("recursive wildcard covers every one-label subdomain"); + + let deeper = GLOB_INSPECTED.replace("*.example.com", "*.sub.example.com"); + base.host = "*.sub.example.com".into(); + scoped.host = base.host.clone(); + nested.host = "*.example.com".into(); + let mut uncovered = provider_policy(&deeper, vec![base, nested]); + uncovered.endpoint_settings = vec![scoped]; + let error = + CedarOnlyEngine::from_proto(&uncovered).expect_err("one label cannot cover a deeper host"); + assert!( + error + .to_string() + .contains("conflicting endpoint transports"), + "{error:?}" + ); +} + +#[test] +fn setting_transport_distinguishes_disjoint_and_nested_host_globs() { + use openshell_core::proto::NetworkTransport; + let mut base = credentialed_endpoint(); + base.path.clear(); + base.transport = NetworkTransport::Plaintext as i32; + base.host = "a*.example.com".into(); + let mut scoped = setting("b*.example.com", "/v1/**"); + scoped.allow_encoded_slash = true; + let mut disjoint = provider_policy(GLOB_INSPECTED, vec![base.clone()]); + disjoint.endpoint_settings = vec![scoped.clone()]; + CedarOnlyEngine::from_proto(&disjoint).expect("disjoint host globs share no connection"); + + let mut nested = base.clone(); + nested.path.clone_from(&scoped.path); + base.host = "*.example.com".into(); + scoped.host = "ab*.example.com".into(); + let mut covered = provider_policy(GLOB_INSPECTED, vec![base, nested]); + covered.endpoint_settings = vec![scoped.clone()]; + CedarOnlyEngine::from_proto(&covered).expect("a* covers the entire ab* setting"); + covered.endpoint_settings[0].host = "b*.example.com".into(); + CedarOnlyEngine::from_proto(&covered) + .expect_err("b* has no plaintext provider for the scoped path"); +} + #[test] fn credentialed_provider_plaintext_on_8443_does_not_stamp_tls_on_cedar_siblings() { use openshell_core::policy_l7::AllowedTransports; diff --git a/crates/openshell-policy-cedar/src/lib.rs b/crates/openshell-policy-cedar/src/lib.rs index c886b24ddb..cd3de3e9a6 100644 --- a/crates/openshell-policy-cedar/src/lib.rs +++ b/crates/openshell-policy-cedar/src/lib.rs @@ -21,7 +21,9 @@ mod error; mod limits; mod token_grants; -pub use analysis::{AnalysisWarning, L7Endpoint, L7Enforcement, L7Protocol, NetworkTransport}; +pub use analysis::{ + AnalysisWarning, L7Endpoint, L7Enforcement, L7Protocol, NetworkTransport, host_patterns_overlap, +}; pub use error::CedarEngineError; pub use limits::{ MAX_POLICY_EXPRESSION_DEPTH, MAX_POLICY_NESTING, MAX_POLICY_SOURCE_BYTES, @@ -894,7 +896,7 @@ fn graphql_exclusions( .get(port) .into_iter() .flatten() - .filter(|permit_host| analysis::host_patterns_overlap(permit_host, host)) + .filter(|permit_host| host_patterns_overlap(permit_host, host)) .map(|permit_host| (*permit_host).to_string()) .collect(), ); diff --git a/crates/openshell-server/src/grpc/policy.rs b/crates/openshell-server/src/grpc/policy.rs index bc24866caf..3bf9771ee5 100644 --- a/crates/openshell-server/src/grpc/policy.rs +++ b/crates/openshell-server/src/grpc/policy.rs @@ -2143,11 +2143,8 @@ fn validate_effective_policy_ambiguities(policy: &ProtoSandboxPolicy) -> Result< validate_endpoint_ambiguities(policy)?; #[cfg(feature = "experimental")] if policy.is_cedar() { - let cedar = openshell_policy::cedar_analyze_provider_transports( - policy.cedar_source(), - &policy.provider_credential_rules, - ) - .map_err(|_| Status::failed_precondition("stored Cedar policy is invalid"))?; + let cedar = openshell_policy::cedar_analyze_provider_transports(policy) + .map_err(|_| Status::failed_precondition("stored Cedar policy is invalid"))?; if !cedar.conflicts.is_empty() { return Err(Status::failed_precondition(format!( "network endpoint ambiguity validation failed:\n{}", @@ -3002,11 +2999,8 @@ fn compute_effective_policy_analysis( if policy.is_cedar() { #[cfg(feature = "experimental")] { - let cedar = openshell_policy::cedar_analyze_provider_transports( - policy.cedar_source(), - &policy.provider_credential_rules, - ) - .map_err(|_| Status::failed_precondition("stored Cedar policy is invalid"))?; + let cedar = openshell_policy::cedar_analyze_provider_transports(policy) + .map_err(|_| Status::failed_precondition("stored Cedar policy is invalid"))?; let ambiguity_error = (!cedar.conflicts.is_empty()).then(|| { format!( "network endpoint ambiguity validation failed:\n{}", @@ -13853,6 +13847,58 @@ when {{ context.method == "GET" }};"# } } + #[cfg(feature = "experimental")] + #[test] + fn cedar_settings_transport_conflict_is_rejected_at_both_admission_checks() { + use openshell_core::proto::NetworkTransport; + let mut policy = ProtoSandboxPolicy { + cedar_policy: Some(openshell_core::proto::CedarPolicy { + source: r#"permit (principal, action == Sandbox::Action::"NetworkConnect", + resource == Sandbox::NetworkEndpoint::"api.example.com:443"); + permit (principal, action == Sandbox::Action::"HttpRequest", + resource == Sandbox::NetworkEndpoint::"api.example.com:443") + when { context.method == "GET" };"# + .into(), + }), + ..Default::default() + }; + let mut provider = test_policy_with_rule("provider", "api.example.com"); + let ep = &mut provider + .network_policies + .get_mut("provider") + .unwrap() + .endpoints[0]; + ep.transport = NetworkTransport::Plaintext as i32; + policy.provider_credential_rules = provider.network_policies; + validate_effective_policy_ambiguities(&policy).unwrap(); + assert!( + compute_effective_policy_analysis(&policy) + .unwrap() + .ambiguity_error + .is_none() + ); + policy.endpoint_settings.push(NetworkEndpoint { + host: "api.example.com".into(), + port: 443, + path: "/v1/**".into(), + allow_encoded_slash: true, + ..Default::default() + }); + assert!( + validate_effective_policy_ambiguities(&policy) + .unwrap_err() + .message() + .contains("/v1/**") + ); + assert!( + compute_effective_policy_analysis(&policy) + .unwrap() + .ambiguity_error + .unwrap() + .contains("/v1/**") + ); + } + #[cfg(feature = "experimental")] #[test] fn cedar_uninspected_l4_endpoint_with_provider_does_not_require_transport_support() {