diff --git a/crates/openshell-cli/src/commands/provider.rs b/crates/openshell-cli/src/commands/provider.rs index b619cfb96e..9535b39fd9 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,25 @@ 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.transport == 0 { + " (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, " Transport on {port}: {label}{source}"); + } let _ = writeln!( rendered, " Allow uninspected credentials: {}", @@ -3167,6 +3190,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("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("Transport on 443: plaintext\n")); + assert!(text.contains("Transport 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-core/src/extension_protocol.rs b/crates/openshell-core/src/extension_protocol.rs index 1d6d57960b..94205a5879 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 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. +#[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..a814090f89 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,141 @@ 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, +} + +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 { + "" => Some(NetworkTransport::Unspecified), + "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::Unspecified => Some(""), + NetworkTransport::Tls => Some("tls"), + NetworkTransport::Plaintext => Some("plaintext"), + } +} + +/// 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 `transport` without assigning defaults to an omitted field. +pub fn validate_endpoint_transport( + transport: i32, + protocol: &str, + tls: i32, +) -> Option<&'static str> { + parse_endpoint_transport(transport, inspected_l7_protocol(protocol, tls)).err() +} + +fn parse_endpoint_transport( + explicit: i32, + protocol: Option, +) -> Result, &'static str> { + 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( + "transport requires an inspected HTTP protocol and cannot be combined with tls: skip", + ); + } + Ok(Some(transport)) +} + +/// Resolve once for the destination port. An opaque connection has no HTTP +/// transport policy. Invalid values 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_endpoint_transport(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.transport, + inspected_l7_protocol(&endpoint.protocol, endpoint.tls), + endpoint_is_credentialed(endpoint), + port, + ) + .ok() + .flatten() +} + +/// 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 +} + pub fn network_enforcement_mode_from_str(value: &str) -> Option { match value { "" => Some(NetworkEnforcementMode::Unspecified), @@ -114,6 +251,16 @@ impl L7Protocol { } } + /// 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 + ) + } + /// Returns `true` for protocols in the JSON-RPC family (`json-rpc`, /// `mcp`). pub fn is_jsonrpc_family(self) -> bool { @@ -169,6 +316,101 @@ 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.transport = NetworkTransport::Plaintext as i32; + assert_eq!( + endpoint_allowed_transports(&endpoint, 443), + Some(AllowedTransports::Plaintext) + ); + endpoint.transport = NetworkTransport::Tls as i32; + assert_eq!( + endpoint_allowed_transports(&endpoint, 8443), + Some(AllowedTransports::Tls) + ); + } + + #[test] + fn invalid_transport_values_and_opaque_protocols_are_rejected() { + let tls = NetworkTransport::Tls as i32; + 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_endpoint_transport(tls, protocol, 0).is_some()); + assert_eq!( + effective_allowed_transports(0, inspected_l7_protocol(protocol, 0), false, 443), + Ok(None) + ); + } + assert!(validate_endpoint_transport(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_explicit_transport_only() { + let mut endpoint = NetworkEndpoint { + protocol: "rest".into(), + port: 8443, + ..Default::default() + }; + 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)); + + endpoint.port = 8443; + endpoint.provider_credentialed = true; + 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)); + } +} + #[cfg(test)] mod agent_transport_tests { use super::agent_authored_transport_rejection; @@ -756,7 +998,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 +1009,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..06047c055c 100644 --- a/crates/openshell-policy-cedar-adapter/src/lib.rs +++ b/crates/openshell-policy-cedar-adapter/src/lib.rs @@ -3,9 +3,14 @@ //! Adapts Cedar analysis to sandbox policy messages for gateway and runtime composition. +use std::collections::BTreeMap; + 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, NetworkTlsMode, SandboxPolicy}; use openshell_policy_cedar::CedarEngine; pub mod endpoint_status; @@ -54,6 +59,261 @@ 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, + 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)> = policy + .provider_credential_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 { + 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.transport, + Some(L7Protocol::Rest), + endpoint_is_credentialed(endpoint), + u32::from(*port), + ) { + Ok(Some(transports)) => { + if endpoint.transport + != openshell_core::proto::NetworkTransport::Unspecified as i32 + { + 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 transport ({:?} vs {:?})", + left.0, left.1, left.2.host, right.0, right.1, right.2.host, left.3, right.3 + )); + } + } + } + + // 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; + } + 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 + }); + } + } + } + + CedarTransportAnalysis { + conflicts, + requires_transport_support, + } +} + +/// 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(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 /// sets `tls: skip`. /// @@ -98,3 +358,84 @@ 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_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] + 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(&provider_policy(cedar_443, vec![])).unwrap(); + assert!(analysis.conflicts.is_empty()); + 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(&provider_policy(cedar_443, 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(), + port: 443, + path: "/v1/**".to_string(), + transport: NetworkTransport::Plaintext as i32, + ..Default::default() + }; + let conflict = + analyze_provider_transports(&provider_policy(cedar_443, 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, + transport: NetworkTransport::Tls as i32, + ..Default::default() + }; + let uninspected = + 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 407f341486..0f4f64ec1e 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,10 @@ 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::policy_l7::AllowedTransports; +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, @@ -125,6 +128,14 @@ impl LoadedPolicy { .build() ); } + 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: {}", + transport_analysis.conflicts.join("; ") + )); + } let mut providers = Vec::new(); for rule in policy.provider_credential_rules.values() { for endpoint in &rule.endpoints { @@ -223,7 +234,38 @@ 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. + // 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) => { + if let Some(narrowed) = previous.intersect(allowed) { + authority_transports = Some(narrowed); + } else { + disjoint = true; + break; + } + } + } + } + } + if !disjoint && authority_transports == Some(AllowedTransports::Tls) { + for config in &mut configs { + if config.protocol.l7().is_some() + && config.transport == NetworkTransport::Unspecified as i32 + { + config.transport = NetworkTransport::Tls as i32; + } + } + } + configs } /// Plans the endpoint configs for `host:port`, in the order @@ -428,6 +470,9 @@ impl RoutePlan<'_> { ); if let Some(inspection) = inspection { apply_inspection(&mut config, inspection); + if let Some(provider) = route.provider { + config.transport = provider.transport; + } } // Every inspected protocol binds grant reporting to the policy // selected before credential acquisition, as the YAML engine does. @@ -756,6 +801,8 @@ struct ProviderEndpoint { ports: Vec, /// The endpoint's `allowed_ips`, empty for none, or why one is invalid. allowed_ips: ProviderRanges, + /// 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, @@ -784,6 +831,7 @@ impl ProviderEndpoint { host: endpoint.host.to_ascii_lowercase(), ports: connection_ports(endpoint), allowed_ips: parse_provider_allowed_ips(&endpoint.allowed_ips), + transport: endpoint.transport, config: provider_config(endpoint), } } @@ -816,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. @@ -979,6 +1023,7 @@ fn provider_config(endpoint: &openshell_core::proto::NetworkEndpoint) -> Endpoin .collect(), path: endpoint.path.clone(), tls: TlsSetting::from_proto(endpoint.tls), + 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..562d84d094 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,271 @@ 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 uninspected_cedar_provider_route_drops_explicit_transport() { + use openshell_core::proto::NetworkTransport; + + let mut unrelated = credentialed_endpoint(); + unrelated.path = "/elsewhere/**".to_string(); + unrelated.transport = 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_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). + 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.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_eq!( + l4_configs[0].transport, + NetworkTransport::Unspecified as i32 + ); + 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.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!( + error + .to_string() + .contains("conflicting endpoint transports"), + "{error:?}" + ); +} + +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; + 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 + .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 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; + use openshell_core::proto::NetworkTransport; + + let mut provider = credentialed_endpoint(); + provider.path = "/ws".to_string(); + provider.port = 8443; + 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"); + 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) | (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-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-policy-runtime-interface/src/policy_data.rs b/crates/openshell-policy-runtime-interface/src/policy_data.rs index 80e45db0ba..70a5a04b19 100644 --- a/crates/openshell-policy-runtime-interface/src/policy_data.rs +++ b/crates/openshell-policy-runtime-interface/src/policy_data.rs @@ -59,6 +59,11 @@ pub fn endpoint_policy_value( .map_or_else(|| format!("unknown({})", e.tls), str::to_owned) .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"] = 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 509e902975..3563c7e924 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,10 @@ pub struct EndpointConfig { pub path: String, pub protocol: EndpointProtocol, pub tls: TlsSetting, + /// 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, @@ -247,6 +253,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 +285,81 @@ 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.transport, + protocol, + self.is_credentialed(), + u32::from(port), + ) + } +} + +fn deserialize_transport<'de, D: Deserializer<'de>>( + deserializer: D, +) -> 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>>( + deserializer: D, +) -> std::result::Result { + 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, /// 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..d3b5c5025c 100644 --- a/crates/openshell-policy-schema/src/lib.rs +++ b/crates/openshell-policy-schema/src/lib.rs @@ -275,6 +275,9 @@ pub struct NetworkEndpoint { pub protocol: String, #[serde(default, skip_serializing_if = "String::is_empty")] pub tls: String, + /// 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")] @@ -835,6 +838,7 @@ fn inspect_endpoint(value: &serde_yml::Value, path: &str) -> InspectionResult { "ports", "protocol", "tls", + "transport", "enforcement", "access", "rules", diff --git a/crates/openshell-policy/src/ambiguity.rs b/crates/openshell-policy/src/ambiguity.rs index efb846a9a1..8c92bae25c 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::{L7Protocol, endpoint_allowed_transports, inspected_l7_protocol}; use openshell_core::proto::{ NetworkEndpoint, NetworkEnforcementMode, NetworkTlsMode, SandboxPolicy, }; @@ -91,6 +92,18 @@ 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 } @@ -775,6 +804,66 @@ mod tests { assert!(find_endpoint_ambiguities(&policy_with(left, right)).is_empty()); } + #[test] + fn transport_conflicts_allow_stricter_intersection_and_reject_disjoint_sets() { + use openshell_core::proto::NetworkTransport::{Plaintext, Tls}; + + // 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)).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.transport = 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.transport = 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("transport 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("transport 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] fn compatible_request_rules_may_overlap() { let mut left = endpoint("api.example.com", 443); diff --git a/crates/openshell-policy/src/lib.rs b/crates/openshell-policy/src/lib.rs index ff6cdd8d5a..53878b78d3 100644 --- a/crates/openshell-policy/src/lib.rs +++ b/crates/openshell-policy/src/lib.rs @@ -12,6 +12,11 @@ #[cfg(feature = "experimental")] mod cedar; +#[cfg(feature = "experimental")] +pub use openshell_policy_cedar_adapter::{ + CedarTransportAnalysis, analyze_provider_transports as cedar_analyze_provider_transports, +}; + mod compose; pub mod endpoint_status; mod l7_validate; @@ -35,6 +40,9 @@ use miette::{IntoDiagnostic, Result, WrapErr}; use openshell_core::mcp::{ DEFAULT_MCP_PROTOCOL_VERSION, McpProtocolVersion, canonicalize_mcp_versions, }; +use openshell_core::policy_l7::{ + network_transport_from_str, network_transport_to_str, validate_endpoint_transport, +}; use openshell_core::proto::{ FilesystemPolicy, GraphqlOperation, L7Allow, L7DenyRule, L7QueryMatcher, L7Rule, LandlockPolicy, McpOptions, NetworkBinary, NetworkEndpoint, NetworkPolicyRule, ProcessPolicy, @@ -504,6 +512,8 @@ fn endpoint_def_to_proto(e: NetworkEndpointDef) -> NetworkEndpoint { ports: normalized_ports, protocol: protocol.clone(), tls: network_tls_mode_from_str(&e.tls).expect("endpoint modes validated above") as i32, + 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") @@ -562,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}: {}", @@ -588,26 +604,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_endpoint_transport( + endpoint.transport, + &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 +676,10 @@ fn endpoint_setting_def_to_proto( index: usize, setting: NetworkEndpointDef, ) -> Result { + 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); if !errors.is_empty() { return Err(miette::miette!( @@ -771,6 +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(), + 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(), @@ -1185,10 +1222,18 @@ 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_endpoint_transport(endpoint.transport, &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 +1243,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.transport != 0 { + errors.push(RejectedSettingField::Access.reason("transport")); + } if !errors.is_empty() { return Err(miette::miette!( "endpoint_settings[{index}]: {}", @@ -1983,6 +2031,9 @@ fn validate_sandbox_policy_with_mcp_presence( ep.enforcement, ep.access, )); + l7_errors.extend( + validate_endpoint_transport(ep.transport, &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 +2196,7 @@ fn endpoint_setting_rejected_fields( mcp, // Access and inspection, which the Cedar policy decides. protocol, + transport, enforcement, access, rules, @@ -2179,6 +2231,7 @@ fn endpoint_setting_rejected_fields( !protocol.is_empty(), RejectedSettingField::Access, ), + ("transport", *transport != 0, RejectedSettingField::Access), ( "enforcement", *enforcement != 0, @@ -3122,6 +3175,7 @@ when { context.binary_path == "/usr/bin/curl" }; fn endpoint_settings_reject_access_and_credential_fields() { for (field, yaml) in [ ("protocol", "protocol: rest"), + ("transport", "transport: tls"), ("enforcement", "enforcement: enforce"), ("access", "access: read-only"), ("rules", "rules: [{ allow: { method: GET } }]"), @@ -3643,6 +3697,105 @@ 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 transport_round_trip_in_policy_yaml_and_json() { + use openshell_core::proto::NetworkTransport; + + for protocol in ["rest", "graphql", "websocket", "mcp", "json-rpc"] { + 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 transport"); + assert_eq!( + policy.network_policies["api"].endpoints[0].transport, + NetworkTransport::Unspecified as i32 + ); + let yaml = serialize_sandbox_policy(&policy).expect("serialize omitted transport"); + assert!(!yaml.contains("transport")); + } + + #[test] + 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, transport: {transport}" + )); + let error = parse_sandbox_policy(&source).expect_err(transport); + assert!( + error_chain(&error).contains("transport"), + "{transport}: {error:?}" + ); + } + for fields in [ + "protocol: rest, tls: skip, access: full", + "protocol: sql, access: full", + "protocol: tcp", + "protocol: ''", + ] { + let source = transport_endpoint_yaml(&format!("{fields}, transport: tls")); + let error = parse_sandbox_policy(&source).expect_err(fields); + assert!( + error_chain(&error).contains("transport"), + "{fields}: {error:?}" + ); + } + } + + #[test] + fn wire_policy_rejects_invalid_transport() { + use openshell_core::proto::{NetworkTlsMode, NetworkTransport}; + + let tls = NetworkTransport::Tls as i32; + 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.transport = transport; + endpoint.protocol = protocol.to_owned(); + endpoint.tls = tls_mode; + let errors = validate_sandbox_policy(&policy).expect_err("wire transport is invalid"); + assert!( + errors + .iter() + .any(|error| error.to_string().contains("transport")) + ); + 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..ebccfeb740 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.transport != NetworkTransport::Unspecified as i32 + { 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.transport = 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,13 @@ 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); +} + /// Binary authorization affected by an incremental L7 rule append. #[derive(Debug, Clone, PartialEq, Eq)] pub enum L7BinaryScope { @@ -407,6 +413,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 +562,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 transport at {host}:{port} without changing an endpoint transport contract" + ), Self::NewBinaryWouldInheritAuthorization { operation_index, rule_name, @@ -839,6 +859,11 @@ fn endpoint_attributes_cover(loaded: &NetworkEndpoint, proposed: &NetworkEndpoin if proposed.tls != NetworkTlsMode::Unspecified as i32 && loaded.tls != proposed.tls { return false; } + if proposed.transport != NetworkTransport::Unspecified as i32 + && loaded.transport != proposed.transport + { + return false; + } if proposed.enforcement != NetworkEnforcementMode::Unspecified as i32 && effective_enforcement(loaded.enforcement) != effective_enforcement(proposed.enforcement) { @@ -1459,10 +1484,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 +1604,26 @@ 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.transport == NetworkTransport::Unspecified as i32 { + existing.transport = incoming.transport; + } if existing.host.is_empty() { existing.host.clone_from(&incoming.host); @@ -1681,6 +1719,42 @@ fn merge_endpoint( Ok(()) } +fn transport_conflict_port( + existing: &NetworkEndpoint, + incoming: &NetworkEndpoint, + existing_ports: &[u32], + incoming_ports: &[u32], + overlapping_port: u32, +) -> Option { + let unspecified = NetworkTransport::Unspecified as i32; + match ( + existing.transport == unspecified, + incoming.transport == unspecified, + ) { + (true, true) => None, + (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 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 { + 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 +1948,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`, `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 /// cannot change it, so a declaration that leaves the field unset expresses no @@ -1903,6 +1978,9 @@ fn adopt_unset_retained_fields( if adopted.tls == NetworkTlsMode::Unspecified as i32 { adopted.tls = merged.tls; } + if adopted.transport == NetworkTransport::Unspecified as i32 { + adopted.transport = merged.transport; + } if adopted.enforcement == NetworkEnforcementMode::Unspecified as i32 { adopted.enforcement = merged.enforcement; } @@ -2420,7 +2498,7 @@ mod tests { proto::{ L7Allow, L7DenyRule, L7QueryMatcher, L7Rule, McpOptions, NetworkAccessPreset, NetworkBinary, NetworkEndpoint, NetworkEnforcementMode, NetworkPolicyRule, - NetworkTlsMode, SandboxPolicy, + NetworkTlsMode, NetworkTransport, SandboxPolicy, }, }; @@ -2647,7 +2725,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 +2744,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 +2761,10 @@ mod tests { NetworkAccessPreset::ReadOnly as i32 ); assert!(!canonical.endpoints[0].provider_credentialed); + assert_eq!( + canonical.endpoints[0].transport, + NetworkTransport::Tls as i32 + ); assert!(canonical.endpoints[0].advisor_proposed); assert!(canonical.endpoints[0].token_grant_owner.is_empty()); assert_eq!( @@ -2881,6 +2963,88 @@ mod tests { policy } + 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, + transport: transport as i32, + ..endpoint("api.example.com", ports[0]) + }], + &["/usr/bin/client"], + ) + } + + #[test] + fn merge_keeps_explicit_transport_and_coverage() { + let unspecified = NetworkTransport::Unspecified; + let tls = NetworkTransport::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, + &[PolicyMergeOp::AddRule { + rule_name: "api".to_owned(), + rule: explicit_tls.clone(), + }], + ) + .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)); + 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: same, + }], + ) + .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), + 443, + ), + ( + transport_rule(&[443, 8443], unspecified), + transport_rule(&[443], tls), + 8443, + ), + ( + transport_rule(&[8443], plaintext), + transport_rule(&[443, 8443], unspecified), + 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..86b8d18fe4 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.transport.is_empty() { + return Err(UnsupportedFeature::policy_shape(format!( + "{context} uses transport 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 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, transport: 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("transport") + ), + "{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..b869892180 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_endpoint_transport, +}; use openshell_core::proto::{ GraphqlOperation, L7Allow, L7DenyRule, L7QueryMatcher, L7Rule, McpOptions, NetworkBinary, NetworkEndpoint, NetworkPolicyRule, ProviderCredentialRefresh, @@ -339,6 +342,7 @@ pub struct EndpointProfile { pub port: u32, pub protocol: String, pub tls: String, + pub transport: String, pub access: String, pub enforcement: String, pub rules: Option>, @@ -385,6 +389,8 @@ struct EndpointProfileSerde { #[serde(default, skip_serializing_if = "String::is_empty")] tls: String, #[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")] enforcement: String, @@ -1657,6 +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), + 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), @@ -1709,6 +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), + 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( @@ -2819,6 +2828,18 @@ pub fn validate_catalog_profiles( )); } collect_mcp_profile_diagnostics(source, profile_id, index, endpoint, &mut diagnostics); + 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}].transport"), + message, + )); + } if endpoint.rules.as_ref().is_some_and(Vec::is_empty) { diagnostics.push(ProfileValidationDiagnostic::error( @@ -7058,6 +7079,59 @@ credentials: // -- L7 endpoint semantic validation (shared with runtime) ---------------- + #[test] + fn profile_transport_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 + transport: tls +"; + let profile = parse_profile_yaml(source).expect("profile should parse"); + let proto = profile.to_proto(); + 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].transport, "tls"); + + for entry in ["null", "[tls]"] { + assert!( + 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"); + let diagnostics = validate_profile_set(&[("restricted.yaml".to_owned(), skipped_tls)]); + assert!( + diagnostics + .iter() + .any(|diagnostic| diagnostic.field == "endpoints[0].transport") + ); + } + #[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..3d793dba44 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(state, &supported_capabilities, &snapshot) { 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), ) } @@ -2018,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 3441fdfac4..7a2a37afaf 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(state, &supported_capabilities, &sandbox_config) { - 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, @@ -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(); @@ -2637,6 +2637,57 @@ 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 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 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, explicit_tls).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..3bf9771ee5 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::endpoint_requires_transport_enforcement; #[cfg(test)] use openshell_core::proto::StaticCredentialBinding; use openshell_core::proto::policy_merge_operation; @@ -2135,6 +2139,22 @@ 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) + .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], @@ -2144,7 +2164,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( @@ -2608,7 +2628,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 { @@ -2893,35 +2914,178 @@ 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(state, &req.supported_capabilities, &snapshot) + && !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"; +const EFFECTIVE_POLICY_ANALYSIS_CACHE_CAPACITY: usize = 4_096; -/// 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. +/// Memoized effective-policy ambiguity and transport-capability analysis, +/// keyed by the canonical policy hash computed after credential stamping. +#[derive(Debug, Clone, PartialEq, Eq)] +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 struct EffectivePolicyAnalysisCache { + entries: std::sync::Mutex>, +} + +impl EffectivePolicyAnalysisCache { + pub 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) + .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( - supported_capabilities: Vec, - policy: Option<&ProtoSandboxPolicy>, + state: &ServerState, + supported_capabilities: &[String], + snapshot: &SandboxConfigSnapshot, ) -> 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) = 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)); } + // 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)); + } 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 +} + /// 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( @@ -3081,10 +3245,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 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); } - policy_hash = deterministic_policy_hash(effective_policy); } if let Some(policy) = policy.as_ref() { @@ -5216,9 +5385,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 +5404,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 +7854,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 { .. @@ -7832,7 +7998,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( @@ -9623,7 +9790,7 @@ mod tests { workspace_scope: Some(openshell_core::proto::workspace_selector( "default".to_string(), )), - ..Default::default() + supported_capabilities: policy_capabilities(false), }), sandbox_id, ), @@ -9938,7 +10105,7 @@ mod tests { Request::new(GetSandboxConfigRequest { name: sandbox_id.to_string(), workspace_scope: None, - ..Default::default() + supported_capabilities: policy_capabilities(false), }), sandbox_id, ), @@ -10003,7 +10170,7 @@ mod tests { Request::new(GetSandboxConfigRequest { name: sandbox_id.clone(), workspace_scope: None, - ..Default::default() + supported_capabilities: policy_capabilities(false), }), &sandbox_id, ), @@ -10272,7 +10439,7 @@ mod tests { Request::new(GetSandboxConfigRequest { name: sandbox_id.to_string(), workspace_scope: None, - ..Default::default() + supported_capabilities: policy_capabilities(false), }), sandbox_id, ), @@ -10342,7 +10509,7 @@ mod tests { Request::new(GetSandboxConfigRequest { name: sandbox_id.to_string(), workspace_scope: None, - ..Default::default() + supported_capabilities: policy_capabilities(false), }), sandbox_id, ), @@ -13465,7 +13632,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() @@ -13515,6 +13682,295 @@ 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, 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), + ] { + 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.transport = 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); + } + } + } + + #[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; + endpoint.transport = openshell_core::proto::NetworkTransport::Tls as i32; + 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() { + 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!( + 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; + endpoint.transport = explicit_transport; + policy.provider_credential_rules = provider.network_policies; + } + assert_eq!( + compute_effective_policy_analysis(&policy) + .unwrap() + .requires_endpoint_transport_support, + requires_support + ); + } + } + + #[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() { + 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.transport = 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.transport = 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() { @@ -14701,9 +15157,7 @@ mod tests { 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", @@ -24054,9 +24508,7 @@ mod tests { 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, }) } diff --git a/crates/openshell-server/src/storage_proto.rs b/crates/openshell-server/src/storage_proto.rs index 4c452c7cf3..4bac541151 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 scalar transport enum to both schemas. Legacy + // endpoint records decode as unspecified and select the endpoint default. const PUBLIC_RPC_SCHEMA_SHA256: &str = - "edfc80ad192e77e1a9d1e1d6e3342280e4438f8bf7cb49969f580060df9a056a"; + "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 = - "ca31950286327bc385fae933bbb9e34d3c9191214f9b549c558bba40957fcc65"; + "d28a01f623e82c759d0f8f72114ea6bb75b608a3cd0a7ff659d7a11ce93b6eec"; 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,21 @@ mod tests { ); } + #[test] + 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_eq!( + endpoint.transport, + openshell_core::proto::NetworkTransport::Unspecified as i32 + ); + 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..23512783d3 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 { + 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 02ae769034..7b76dd60bf 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_endpoint_transport, +}; use openshell_policy_schema::{ JsonRpcConfig, L7Allow, L7DenyRule, McpConfig, NetworkBinary, NetworkEndpoint, NetworkPolicyRule, @@ -54,7 +57,13 @@ 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 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_endpoint_transport(transport, &config.protocol, tls).is_some() { + return Err(miette::miette!(diagnostic)); + } validate_renamed::( endpoint, @@ -168,8 +177,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..c25f826fcf 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, + 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 46709329b6..bad8581967 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,10 @@ async fn handle_transparent_tcp_connection( return Ok(()); } + if reject_inspected_transparent_tcp(&decision, workload_addr, &activity_tx)? { + return Ok(()); + } + if mapping.record.is_observation() { emit_transparent_mapping_denial( workload_addr, @@ -1629,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<'_>, @@ -2055,33 +2076,96 @@ 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( tx: &Option, l7_route: Option<&L7RouteSnapshot>, @@ -3147,14 +3231,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 +3341,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 +3444,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 +3493,116 @@ async fn handle_mediated_connection( } } + 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?; + let mut stale_during_peek = false; + let peeked = tokio::select! { + peeked = peek_tunnel_protocol(&mut client) => peeked?, + () = 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(()); + }; + if let Some(detail) = transport_rejection(transports, protocol) { + 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(()); + } + 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); + Some(protocol) + } else { + None + }; + 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 +3613,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 +3654,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 +4483,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() { + // 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); + } + decision.endpoint.l7_route = route; +} + +/// 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: Option = 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; + }; + effective = match effective { + None => Some(allowed), + Some(previous) => Some( + previous + .intersect(allowed) + .ok_or_else(|| miette::miette!("matched endpoints have disjoint transport"))?, + ), + }; + } + Ok(effective) } fn hydrate_tls_mode(decision: &mut EgressDecision) { @@ -6074,7 +6296,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 @@ -7966,7 +8206,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 @@ -13642,6 +13882,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; @@ -13656,7 +13918,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..e3f5535d97 --- /dev/null +++ b/crates/openshell-supervisor-network/src/proxy/transport_tests.rs @@ -0,0 +1,545 @@ +// 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 = " 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"; + +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 (_, resolver) = SecretResolver::from_provider_env( + std::iter::once(( + "TRANSPORT_TEST_TOKEN".to_string(), + "test-origin-token".to_string(), + )) + .collect(), + ); + 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 + resolver.map(Arc::new), // 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\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(); +} + +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), + (8443, "", 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 (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 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(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) + .await + .unwrap() + .unwrap() + .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 transport: 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:?})" + ); + } +} diff --git a/crates/openshell-supervisor/src/lib.rs b/crates/openshell-supervisor/src/lib.rs index b9e6327d15..b246ad3496 100644 --- a/crates/openshell-supervisor/src/lib.rs +++ b/crates/openshell-supervisor/src/lib.rs @@ -2253,10 +2253,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..e0026f7261 100644 --- a/docs/how-it-works/policies/network-rules.mdx +++ b/docs/how-it-works/policies/network-rules.mdx @@ -121,6 +121,55 @@ 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. +### Transport + +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 + transport: tls + protocol: rest + access: read-only + enforcement: enforce + - host: internal.example.com + port: 8080 + transport: plaintext + protocol: rest + access: read-only + enforcement: enforce +``` + +| `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, which OpenShell forwards over plaintext HTTP (no upstream TLS origination). | + +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 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 `transport`. + ### HTTP Connection Failures When an HTTP upstream closes an idle connection, OpenShell closes the client @@ -169,7 +218,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`, or OpenShell rejects the policy. +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 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 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..7b0ea4105b 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). | +| `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). | @@ -226,8 +227,12 @@ 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 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` 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. 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/kubernetes_shared_supervisor.rs b/e2e/rust/tests/kubernetes_shared_supervisor.rs index a908b7eb8c..ee6ecfef6a 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 + transport: 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 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 b89f60fd90..0df3ab8ffa 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 + 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 b7d1256641..5de164d5ff 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", + "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 16002c21c2..19204f4b67 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", + "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 a8624c1edf..45a31a2e46 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 + transport: {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 + transport: {transport} access: full enforcement: enforce allowed_ips: diff --git a/proto/sandbox.proto b/proto/sandbox.proto index 4699ee244d..8a76b84c44 100644 --- a/proto/sandbox.proto +++ b/proto/sandbox.proto @@ -148,6 +148,17 @@ enum NetworkTlsMode { NETWORK_TLS_MODE_PASSTHROUGH = 3 [deprecated = true]; } +// Wire transport policy for an inspected HTTP-family endpoint. +enum NetworkTransport { + // 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; + // Require TLS from the workload and verified TLS to the destination. + NETWORK_TRANSPORT_TLS = 1; + // Require 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 +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; + // 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 3c39b99f45..06a6b98c13 100644 --- a/tests/suites/conformance/src/credential_gating.rs +++ b/tests/suites/conformance/src/credential_gating.rs @@ -24,6 +24,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) + .transport = 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) + .transport = 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) + .transport = 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) + .transport = PLAINTEXT; }) .await?; let token = sandbox.env_var(TOKEN_ENV).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.transport = 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, transport: 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) + .transport = 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).transport = PLAINTEXT; }) .endpoint(TEST_HOST, websocket, |ep| { - ep.websocket(Access::ReadWrite); + ep.websocket(Access::ReadWrite).transport = 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() + .transport = PLAINTEXT; }) .binaries([BASH]) .to_yaml()?; diff --git a/tests/suites/conformance/src/provider_credentials.rs b/tests/suites/conformance/src/provider_credentials.rs index 7bffa3422b..92e1b90c4f 100644 --- a/tests/suites/conformance/src/provider_credentials.rs +++ b/tests/suites/conformance/src/provider_credentials.rs @@ -106,6 +106,7 @@ async fn expect_placement(cx: &Context, suffix: &str, placement: &str) -> Result .credential(credential) .endpoint(TEST_HOST, server.port, |ep| { ep.rest(Access::Full).request_body_credential_rewrite(true); + ep.transport = proto::NetworkTransport::Plaintext as i32; }) .binaries(PYTHON_BINARIES.iter().copied()) .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 d36672f734..87e166bdd1 100644 --- a/tests/suites/features/provider-token-exchange/tests/token_exchange.rs +++ b/tests/suites/features/provider-token-exchange/tests/token_exchange.rs @@ -43,6 +43,7 @@ const IDENTITY_AUDIENCE: &str = "identity-proxy"; const IDENTITY_JWT_AUDIENCE: &str = "https://identity.openshell-e2e.test"; const IDENTITY_ASSERTION_TYPE: &str = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"; const SUBJECT_TOKEN_ENV: &str = "subject_token"; +const PLAINTEXT: i32 = proto::NetworkTransport::Plaintext as i32; /// Two sandboxes, each with its own provider, request the same host and /// port at the same time. Each request carries its provider's bearer token, @@ -549,7 +550,7 @@ fn grants_profile( }), ) .endpoint(TEST_HOST, target_port, |ep| { - ep.rest(Access::ReadWrite).enforce().path("/**"); + ep.rest(Access::ReadWrite).enforce().path("/**").transport = PLAINTEXT; }) .binaries(["/**"]) } @@ -574,7 +575,8 @@ fn route_profile(profile_type: &str, token_port: u16, target_port: u16, route: & .endpoint(TEST_HOST, target_port, |ep| { ep.rest(Access::ReadWrite) .enforce() - .path(&format!("/{route}/**")); + .path(&format!("/{route}/**")) + .transport = PLAINTEXT; }) .binaries(["/**"]) }