diff --git a/crates/openshell-ocsf/src/builders/http.rs b/crates/openshell-ocsf/src/builders/http.rs index e2f85bdab2..ae0a1ab2e3 100644 --- a/crates/openshell-ocsf/src/builders/http.rs +++ b/crates/openshell-ocsf/src/builders/http.rs @@ -171,6 +171,22 @@ impl<'a, Context> HttpActivityBuilder<'a, Context> { self.firewall_rule = Some(FirewallRule::new(name, rule_type)); self } + + /// Set the firewall rule and the policy generation that evaluated it. + /// + /// Use this for allow and deny decisions so the event names the exact + /// policy generation, not only the rule name. + #[must_use] + pub fn firewall_rule_at_generation( + mut self, + name: &str, + rule_type: &str, + generation: u64, + ) -> Self { + self.firewall_rule = + Some(FirewallRule::new(name, rule_type).with_policy_generation(generation)); + self + } } impl_activity_setter!(HttpActivityBuilder); @@ -272,4 +288,27 @@ mod tests { assert_eq!(json["unmapped"]["cached"], true); assert_eq!(json["action_id"], 2); // Denied } + + #[test] + fn test_http_decision_records_policy_generation() { + let ctx = test_sandbox_context(); + let event = HttpActivityBuilder::new(&ctx) + .activity(ActivityId::Other) + .action(ActionId::Allowed) + .disposition(DispositionId::Allowed) + .severity(SeverityId::Informational) + .dst_endpoint(Endpoint::from_domain("api.github.com", 443)) + .http_request(HttpRequest::new( + "GET", + Url::new("https", "api.github.com", "/zen", 443), + )) + .firewall_rule_at_generation("github_api", "l7", 12) + .build(); + + let json = event.to_json().unwrap(); + assert_eq!(json["firewall_rule"]["name"], "github_api"); + assert_eq!(json["firewall_rule"]["version"], "12"); + openshell_ocsf_validate::validate_event(&json) + .unwrap_or_else(|e| panic!("firewall_rule.version must stay schema-valid: {e}")); + } } diff --git a/crates/openshell-ocsf/src/builders/network.rs b/crates/openshell-ocsf/src/builders/network.rs index 950cc7e1c8..a5a5684997 100644 --- a/crates/openshell-ocsf/src/builders/network.rs +++ b/crates/openshell-ocsf/src/builders/network.rs @@ -203,6 +203,22 @@ impl<'a, EndpointState> NetworkActivityBuilder<'a, EndpointState> { self.firewall_rule = Some(FirewallRule::new(name, rule_type)); self } + + /// Set the firewall rule and the policy generation that evaluated it. + /// + /// Use this for allow and deny decisions so the event names the exact + /// policy generation, not only the rule name. + #[must_use] + pub fn firewall_rule_at_generation( + mut self, + name: &str, + rule_type: &str, + generation: u64, + ) -> Self { + self.firewall_rule = + Some(FirewallRule::new(name, rule_type).with_policy_generation(generation)); + self + } } impl_activity_setter!(NetworkActivityBuilder); @@ -292,5 +308,30 @@ mod tests { assert_eq!(json["device"]["container"]["name"], "my-sandbox"); assert_eq!(json["device"]["hostname"], "sandbox-abc123"); assert_eq!(json["is_src_dst_assignment_known"], true); + assert!( + json["firewall_rule"].get("version").is_none(), + "decisions built without a generation leave firewall_rule.version unset" + ); + } + + #[test] + fn test_network_decision_records_policy_generation() { + let ctx = test_sandbox_context(); + let event = NetworkActivityBuilder::new(&ctx) + .activity(ActivityId::Open) + .action(ActionId::Denied) + .disposition(DispositionId::Blocked) + .severity(SeverityId::Medium) + .dst_endpoint(Endpoint::from_domain("httpbin.org", 443)) + .firewall_rule_at_generation("-", "opa", 4) + .message("CONNECT denied httpbin.org:443") + .build(); + + let json = event.to_json().unwrap(); + assert_eq!(json["firewall_rule"]["name"], "-"); + assert_eq!(json["firewall_rule"]["type"], "opa"); + assert_eq!(json["firewall_rule"]["version"], "4"); + openshell_ocsf_validate::validate_event(&json) + .unwrap_or_else(|e| panic!("firewall_rule.version must stay schema-valid: {e}")); } } diff --git a/crates/openshell-ocsf/src/objects/firewall_rule.rs b/crates/openshell-ocsf/src/objects/firewall_rule.rs index 2e242225b7..1ed42d2c60 100644 --- a/crates/openshell-ocsf/src/objects/firewall_rule.rs +++ b/crates/openshell-ocsf/src/objects/firewall_rule.rs @@ -17,6 +17,16 @@ pub struct FirewallRule { /// (not OCSF-enumerated) with runtime-dynamic values from the policy engine. #[serde(rename = "type")] pub rule_type: String, + + /// Version of the policy the rule belongs to, as evaluated for this event. + /// + /// `OpenShell` sets this to the supervisor's policy engine generation: a + /// counter the engine advances whenever it replaces its active + /// configuration. Policy activation events record the same counter in + /// `unmapped.active_generation`, so a consumer can resolve the policy + /// behind each decision without relying on timestamps. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub version: Option, } impl FirewallRule { @@ -26,8 +36,16 @@ impl FirewallRule { Self { name: name.to_string(), rule_type: rule_type.to_string(), + version: None, } } + + /// Record the policy generation under which the rule was evaluated. + #[must_use] + pub fn with_policy_generation(mut self, generation: u64) -> Self { + self.version = Some(generation.to_string()); + self + } } #[cfg(test)] @@ -40,5 +58,20 @@ mod tests { let json = serde_json::to_value(&rule).unwrap(); assert_eq!(json["name"], "default-egress"); assert_eq!(json["type"], "mechanistic"); + assert!( + json.get("version").is_none(), + "version is omitted when no generation is recorded" + ); + } + + #[test] + fn test_firewall_rule_policy_generation_serializes_as_version() { + let rule = FirewallRule::new("github_api", "opa").with_policy_generation(7); + let json = serde_json::to_value(&rule).unwrap(); + assert_eq!(json["name"], "github_api"); + assert_eq!(json["version"], "7"); + + let round_trip: FirewallRule = serde_json::from_value(json).unwrap(); + assert_eq!(round_trip, rule); } } diff --git a/crates/openshell-policy-cedar-runtime/src/backend.rs b/crates/openshell-policy-cedar-runtime/src/backend.rs index dd80adb051..f49c242135 100644 --- a/crates/openshell-policy-cedar-runtime/src/backend.rs +++ b/crates/openshell-policy-cedar-runtime/src/backend.rs @@ -96,8 +96,10 @@ impl PolicyBackend for CedarOnlyEngine { fn middleware_runner(&self) -> Result { self.middleware().runner() } - fn replace_middleware_registry(&self, registry: MiddlewareRegistry) -> Result<()> { - self.middleware().replace_registry(registry) + fn replace_middleware_registry(&self, registry: MiddlewareRegistry) -> Result { + // A registry swap advances the middleware generation, not Cedar's. + self.middleware().replace_registry(registry)?; + Ok(PolicyBackend::current_generation(self)) } fn passthrough_snapshot(&self) -> Result> { self.middleware().snapshot().map(Some) diff --git a/crates/openshell-policy-runtime-interface/src/runtime.rs b/crates/openshell-policy-runtime-interface/src/runtime.rs index e6652c9f2f..68cbee7e47 100644 --- a/crates/openshell-policy-runtime-interface/src/runtime.rs +++ b/crates/openshell-policy-runtime-interface/src/runtime.rs @@ -133,7 +133,10 @@ pub trait PolicyBackend: Send + Sync { input: &NetworkInput, ) -> Result<(Vec, u64)>; fn middleware_runner(&self) -> Result; - fn replace_middleware_registry(&self, registry: MiddlewareRegistry) -> Result<()>; + /// Install a new middleware registry and return the policy generation in + /// force afterwards. Engines that advance the policy generation on a + /// registry change return the generation the change activated. + fn replace_middleware_registry(&self, registry: MiddlewareRegistry) -> Result; fn passthrough_snapshot(&self) -> Result>; fn tunnel_engine(&self, expected: u64) -> Result; fn effective_filesystem( diff --git a/crates/openshell-supervisor-network/src/l7/relay.rs b/crates/openshell-supervisor-network/src/l7/relay.rs index 4512dce4cb..7db0a14292 100644 --- a/crates/openshell-supervisor-network/src/l7/relay.rs +++ b/crates/openshell-supervisor-network/src/l7/relay.rs @@ -401,6 +401,7 @@ where "l7-mcp", &reason, summary.as_deref(), + None, ); if let Some(correlation) = correlation { correlation.record_rejection(400, HttpOutcome::Denied, None); @@ -503,6 +504,7 @@ where "l7-mcp", &reason, summary.as_deref(), + None, ); if let Some(correlation) = correlation { let status = match error { @@ -1718,7 +1720,16 @@ where let Some(config) = select_l7_config_for_path(configs, &route_target) else { let reason = "no L7 endpoint path matched request"; correlation.record_rejection(403, HttpOutcome::Denied, None); - emit_l7_request_log(ctx, &req.action, &route_target, "deny", "l7", reason, None); + emit_l7_request_log( + ctx, + &req.action, + &route_target, + "deny", + "l7", + reason, + None, + engine.captured_generation(), + ); crate::l7::rest::RestProvider::default() .deny_with_redacted_target( &req, @@ -1959,6 +1970,7 @@ where engine_type, &reason, protocol_summary.as_deref(), + engine.captured_generation(), ); if allowed || (config.enforcement == EnforcementMode::Audit && !force_deny) { @@ -2273,6 +2285,7 @@ pub(crate) fn select_l7_config_for_path<'a>( openshell_core::endpoint_path::select_most_specific(configs, path, |config| &config.path) } +#[allow(clippy::too_many_arguments)] fn emit_l7_request_log( ctx: &L7EvalContext, action: &str, @@ -2281,6 +2294,7 @@ fn emit_l7_request_log( engine_type: &str, reason: &str, protocol_summary: Option<&str>, + policy_generation: u64, ) { let event = build_l7_request_event( ctx, @@ -2290,11 +2304,16 @@ fn emit_l7_request_log( engine_type, reason, protocol_summary, + Some(policy_generation), ); egress_emit!(event); emit_activity(ctx, decision_str == "deny", "l7_policy"); } +/// `policy_generation` is the policy engine generation that produced the +/// decision. Protocol validation rejections that happen before policy +/// evaluation pass `None`. +#[allow(clippy::too_many_arguments)] fn build_l7_request_event( ctx: &L7EvalContext, action: &str, @@ -2303,6 +2322,7 @@ fn build_l7_request_event( engine_type: &str, reason: &str, protocol_summary: Option<&str>, + policy_generation: Option, ) -> openshell_ocsf::OcsfEvent { let (action_id, disposition_id, severity) = match decision_str { "deny" => (ActionId::Denied, DispositionId::Blocked, SeverityId::Medium), @@ -2323,16 +2343,20 @@ fn build_l7_request_event( "L7_REQUEST {decision_str} {action} {}:{}{}{protocol_suffix} reason={reason}", ctx.host, ctx.port, redacted_target, ); - HttpActivityBuilder::new(openshell_ocsf::ctx::ctx()) + let builder = HttpActivityBuilder::new(openshell_ocsf::ctx::ctx()) .activity(ActivityId::Other) .action(action_id) .disposition(disposition_id) .severity(severity) .http_request(HttpRequest::new(action, ctx.ocsf_url(redacted_target))) - .dst_endpoint(Endpoint::from_domain(&ctx.host, ctx.port)) - .firewall_rule(&ctx.policy_name, engine_type) - .message(message) - .build() + .dst_endpoint(Endpoint::from_domain(&ctx.host, ctx.port)); + let builder = match policy_generation { + Some(generation) => { + builder.firewall_rule_at_generation(&ctx.policy_name, engine_type, generation) + } + None => builder.firewall_rule(&ctx.policy_name, engine_type), + }; + builder.message(message).build() } fn l7_protocol_log_summary( @@ -2847,7 +2871,7 @@ where ctx.ocsf_url(&redacted_target), )) .dst_endpoint(Endpoint::from_domain(&ctx.host, ctx.port)) - .firewall_rule(&ctx.policy_name, "l7") + .firewall_rule_at_generation(&ctx.policy_name, "l7", engine.captured_generation()) .message(format!( "L7_REQUEST {decision_str} {} {}:{}{} reason={}", request_info.action, ctx.host, ctx.port, redacted_target, reason, @@ -3156,7 +3180,7 @@ pub(crate) fn emit_policy_reload( .severity(SeverityId::Medium) .status(StatusId::Failure) .dst_endpoint(Endpoint::from_domain(host, port)) - .firewall_rule(policy_name, "l7") + .firewall_rule_at_generation(policy_name, "l7", guard.captured_generation()) .message(format!( "L7 tunnel closed after policy reload [host:{} port:{} captured_generation:{} current_generation:{}]", host, @@ -3421,7 +3445,11 @@ where ctx.ocsf_url(&redacted_target), )) .dst_endpoint(Endpoint::from_domain(&ctx.host, ctx.port)) - .firewall_rule(&ctx.policy_name, jsonrpc_engine_type(config.protocol)) + .firewall_rule_at_generation( + &ctx.policy_name, + jsonrpc_engine_type(config.protocol), + policy_version, + ) .message(jsonrpc_log_message( decision_str, &request_info.action, @@ -3803,7 +3831,11 @@ where ctx.ocsf_url(&redacted_target), )) .dst_endpoint(Endpoint::from_domain(&ctx.host, ctx.port)) - .firewall_rule(&ctx.policy_name, "l7-graphql") + .firewall_rule_at_generation( + &ctx.policy_name, + "l7-graphql", + engine.captured_generation(), + ) .message(format!( "GRAPHQL_L7_REQUEST {decision_str} {} {}:{}{} {gql_summary} reason={}", request_info.action, ctx.host, ctx.port, redacted_target, reason, @@ -4279,6 +4311,7 @@ fn reevaluate_transformed_body( "deny", &reason, correlation, + engine.captured_generation(), ); return Ok(Some(reason)); } @@ -4304,10 +4337,19 @@ fn reevaluate_transformed_body( "audit", &reason, correlation, + engine.captured_generation(), ); return Ok(None); } - emit_transformed_body_decision(ctx, request_info, engine_type, "deny", &reason, correlation); + emit_transformed_body_decision( + ctx, + request_info, + engine_type, + "deny", + &reason, + correlation, + engine.captured_generation(), + ); Ok(Some(reason)) } @@ -4336,6 +4378,7 @@ fn emit_transformed_body_decision( decision_str: &str, reason: &str, correlation: Option<&RequestCorrelation>, + policy_generation: u64, ) { let (action_id, disposition_id, severity) = match decision_str { "deny" => (ActionId::Denied, DispositionId::Blocked, SeverityId::Medium), @@ -4355,7 +4398,7 @@ fn emit_transformed_body_decision( ctx.ocsf_url(&request_info.target), )) .dst_endpoint(Endpoint::from_domain(&ctx.host, ctx.port)) - .firewall_rule(&ctx.policy_name, engine_type) + .firewall_rule_at_generation(&ctx.policy_name, engine_type, policy_generation) .message(format!( "L7_REQUEST_TRANSFORMED {decision_str} {} {}:{}{} reason={}", request_info.action, ctx.host, ctx.port, request_info.target, reason @@ -4885,7 +4928,7 @@ mod trace_tests { ..Default::default() }; egress_emit!(build_l7_request_event( - &ctx, "GET", "/", "deny", "l7-rest", "denied", None + &ctx, "GET", "/", "deny", "l7-rest", "denied", None, None )); }) .await; @@ -11363,14 +11406,133 @@ network_policies: "l7", "no L7 endpoint path matched request", None, + Some(6), ); assert_eq!(event.class_uid(), 4002); assert_eq!(event.base().severity, SeverityId::Medium); + // The shorthand projection is unchanged; the generation is carried in + // the structured record. assert_eq!( event.format_shorthand(), "HTTP:GET [MED] DENIED GET https://gateway.example.test/other [policy:route_api engine:l7] [reason:L7_REQUEST deny GET gateway.example.test:443/other reason=no L7 endpoint path matched request]" ); + let json = event.to_json().unwrap(); + assert_eq!(json["firewall_rule"]["name"], "route_api"); + assert_eq!(json["firewall_rule"]["version"], "6"); + } + + #[test] + fn protocol_rejection_before_policy_evaluation_omits_generation() { + let ctx = L7EvalContext { + host: "gateway.example.test".into(), + port: 443, + policy_name: "route_api".into(), + ..Default::default() + }; + + let event = build_l7_request_event( + &ctx, + "POST", + "/mcp", + "deny", + "l7-mcp", + "unsupported MCP protocol version", + None, + None, + ); + + let json = event.to_json().unwrap(); + assert_eq!(json["firewall_rule"]["type"], "l7-mcp"); + assert!(json["firewall_rule"].get("version").is_none()); + } + + struct DecisionEventCapture(Arc>>); + + impl tracing_subscriber::Layer for DecisionEventCapture { + fn on_event(&self, _: &tracing::Event<'_>, _: tracing_subscriber::layer::Context<'_, S>) { + if let Some(event) = openshell_ocsf::tracing_layers::clone_current_event() { + self.0 + .lock() + .unwrap() + .push(serde_json::to_value(&event).unwrap()); + } + } + } + + #[tokio::test] + async fn route_selected_denial_records_the_evaluating_policy_generation() { + use tracing_subscriber::layer::SubscriberExt as _; + + const CHILD: &str = "OPENSHELL_TEST_L7_DECISION_GENERATION_CHILD"; + // Tracing callsite interest is process-wide, so run the capture in an + // isolated child process, as the policy DNS event tests do. + if std::env::var_os(CHILD).is_none() { + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + "l7::relay::tests::route_selected_denial_records_the_evaluating_policy_generation", + "--nocapture", + ]) + .env(CHILD, "1") + .output() + .unwrap(); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!( + output.status.success() && stdout.contains("1 passed"), + "{stdout}\n{}", + String::from_utf8_lossy(&output.stderr) + ); + return; + } + + let engine = OpaEngine::from_strings(TEST_POLICY, ENCODED_SLASH_SCOPING_POLICY).unwrap(); + // Advance past the initial generation so the test cannot pass by + // accident on a zero default. + engine + .reload(TEST_POLICY, ENCODED_SLASH_SCOPING_POLICY) + .unwrap(); + engine + .reload(TEST_POLICY, ENCODED_SLASH_SCOPING_POLICY) + .unwrap(); + let generation = engine.current_generation(); + assert_eq!(generation, 2); + let tunnel_engine = engine.clone_engine_for_tunnel(generation).unwrap(); + let configs = encoded_slash_scoping_configs(); + let ctx = encoded_slash_scoping_ctx(); + + let events = Arc::new(std::sync::Mutex::new(Vec::new())); + let _subscriber = tracing::subscriber::set_default( + tracing_subscriber::registry().with(DecisionEventCapture(Arc::clone(&events))), + ); + + let (mut app, mut relay_client) = tokio::io::duplex(8192); + let (mut relay_upstream, _upstream) = tokio::io::duplex(8192); + app.write_all( + b"GET /other HTTP/1.1\r\nHost: gateway.example.test\r\nConnection: close\r\n\r\n", + ) + .await + .unwrap(); + drop(app); + let _ = relay_with_route_selection( + &configs, + tunnel_engine, + &mut relay_client, + &mut relay_upstream, + &ctx, + ) + .await; + + let events = events.lock().unwrap(); + let denial = events + .iter() + .find(|event| { + event["class_uid"] == 4002 + && event["action"] == "Denied" + && event["firewall_rule"]["name"] == "route_api" + }) + .unwrap_or_else(|| panic!("expected an L7 denial event, got {events:?}")); + assert_eq!(denial["firewall_rule"]["version"], generation.to_string()); } #[test] @@ -11389,7 +11551,7 @@ network_policies: ..Default::default() }; - let event = build_l7_request_event(&ctx, "GET", "/v1", "allow", "l7", "ok", None); + let event = build_l7_request_event(&ctx, "GET", "/v1", "allow", "l7", "ok", None, None); let json = event.to_json().unwrap(); assert_eq!(json["http_request"]["url"]["scheme"], scheme); diff --git a/crates/openshell-supervisor-network/src/l7/websocket.rs b/crates/openshell-supervisor-network/src/l7/websocket.rs index dae95cf6d2..a99bd4bfc2 100644 --- a/crates/openshell-supervisor-network/src/l7/websocket.rs +++ b/crates/openshell-supervisor-network/src/l7/websocket.rs @@ -1396,6 +1396,7 @@ fn inspect_websocket_text_message( decision, &reason, None, + Some(inspector.engine.captured_generation()), ); if !allowed && inspector.enforcement == EnforcementMode::Enforce { return Err(terminate( @@ -1430,6 +1431,7 @@ fn inspect_graphql_websocket_message( "allow", &format!("GraphQL WebSocket control message {message_type}"), None, + None, ); Ok(()) } @@ -1470,6 +1472,7 @@ fn inspect_graphql_websocket_message( decision, &reason, Some(&graphql), + Some(inspector.engine.captured_generation()), ); if (!allowed && inspector.enforcement == EnforcementMode::Enforce) || force_deny { return Err(terminate( @@ -2043,6 +2046,9 @@ fn rewrite_event_message(host: &str, port: u16, replacements: usize) -> String { ) } +/// `policy_generation` is the tunnel policy generation that evaluated the +/// message, or `None` for messages passed without policy evaluation. +#[allow(clippy::too_many_arguments)] fn emit_websocket_l7_event( host: &str, port: u16, @@ -2051,6 +2057,7 @@ fn emit_websocket_l7_event( decision: &str, reason: &str, graphql: Option<&crate::l7::graphql::GraphqlRequestInfo>, + policy_generation: Option, ) { let policy_name = if policy_name.is_empty() { "-" @@ -2074,14 +2081,20 @@ fn emit_websocket_l7_event( .map(crate::l7::graphql::log_summary) .map(|summary| format!(" {summary}")) .unwrap_or_default(); - let event = NetworkActivityBuilder::new(openshell_ocsf::ctx::ctx()) + let builder = NetworkActivityBuilder::new(openshell_ocsf::ctx::ctx()) .activity(ActivityId::Other) .action(action_id) .disposition(disposition_id) .severity(severity) .status(StatusId::Success) - .dst_endpoint(Endpoint::from_domain(host, port)) - .firewall_rule(policy_name, "l7-websocket") + .dst_endpoint(Endpoint::from_domain(host, port)); + let builder = match policy_generation { + Some(generation) => { + builder.firewall_rule_at_generation(policy_name, "l7-websocket", generation) + } + None => builder.firewall_rule(policy_name, "l7-websocket"), + }; + let event = builder .message(format!( "WEBSOCKET_L7_REQUEST {decision} {} {host}:{port}{}{} reason={reason}", request_info.action, request_info.target, summary diff --git a/crates/openshell-supervisor-network/src/opa.rs b/crates/openshell-supervisor-network/src/opa.rs index 87eeffca9a..04d567b1af 100644 --- a/crates/openshell-supervisor-network/src/opa.rs +++ b/crates/openshell-supervisor-network/src/opa.rs @@ -1110,7 +1110,9 @@ impl OpaEngine { /// Replace the complete middleware service registry and invalidate /// existing tunnels so subsequent requests use the new service set. - pub fn replace_middleware_registry(&self, registry: MiddlewareRegistry) -> Result<()> { + /// Install a new middleware registry and return the policy generation it + /// activated. + pub fn replace_middleware_registry(&self, registry: MiddlewareRegistry) -> Result { // Generation changes serialize through the engine lock so guarded // publication cannot overlap any runtime generation transition. let engine = self @@ -1126,7 +1128,7 @@ impl OpaEngine { .fetch_add(1, Ordering::AcqRel); let generation = self.advance_generation(); self.record_generation(generation, &engine, self.fail_closed_reason()); - Ok(()) + Ok(generation) } /// Publish a new generation of the unchanged policy, so pinned relays wake @@ -8275,6 +8277,17 @@ network_policies: assert!(cloned.evaluate_request(&context, &request).unwrap().0); } + #[test] + fn replacing_the_middleware_registry_returns_the_activated_generation() { + let engine = test_engine(); + let before = engine.current_generation(); + let activated = engine + .replace_middleware_registry(MiddlewareRegistry::default()) + .unwrap(); + assert_eq!(activated, before + 1); + assert_eq!(engine.current_generation(), activated); + } + #[test] fn policy_generation_starts_at_zero_and_increments_on_successful_reload() { let engine = l7_engine(); diff --git a/crates/openshell-supervisor-network/src/policy_engine.rs b/crates/openshell-supervisor-network/src/policy_engine.rs index 1ec345d396..9c72e2a37d 100644 --- a/crates/openshell-supervisor-network/src/policy_engine.rs +++ b/crates/openshell-supervisor-network/src/policy_engine.rs @@ -107,7 +107,7 @@ impl PolicyBackend for OpaEngine { fn middleware_runner(&self) -> Result { self.middleware_runner() } - fn replace_middleware_registry(&self, registry: MiddlewareRegistry) -> Result<()> { + fn replace_middleware_registry(&self, registry: MiddlewareRegistry) -> Result { self.replace_middleware_registry(registry) } fn passthrough_snapshot(&self) -> Result> { diff --git a/crates/openshell-supervisor-network/src/proxy.rs b/crates/openshell-supervisor-network/src/proxy.rs index 5226f66d2c..01e5347878 100644 --- a/crates/openshell-supervisor-network/src/proxy.rs +++ b/crates/openshell-supervisor-network/src/proxy.rs @@ -754,6 +754,7 @@ async fn preauthorize_transparent_open( &binary_identity, "sandbox-local policy API requires port 80 and an active context", "transparent_tcp_policy_local_invalid_destination", + None, ); let _ = completion.send(TcpOpenDecision::Denied(TcpOpenDenial::InvalidDestination)); return None; @@ -778,6 +779,7 @@ async fn preauthorize_transparent_open( &binary_identity, "sandbox-local policy API requires a verified workload identity", "transparent_tcp_policy_local_identity_unavailable", + None, ); let _ = completion.send(TcpOpenDecision::Denied(denial)); return None; @@ -807,6 +809,7 @@ async fn preauthorize_transparent_open( &binary_identity, &error.to_string(), "transparent_tcp_mapping_denied", + None, ); let _ = completion.send(TcpOpenDecision::Denied(TcpOpenDenial::InvalidDestination)); return None; @@ -824,6 +827,7 @@ async fn preauthorize_transparent_open( ) }); let mut decision = supplied_authorization.decision; + let policy_generation = decision.policy_generation; if let NetworkAction::Deny { reason } = &decision.action { let (denial, status_detail) = supplied_authorization.denial.map_or( (TcpOpenDenial::PolicyDenied, "transparent_tcp_policy_denied"), @@ -845,6 +849,7 @@ async fn preauthorize_transparent_open( &binary_identity, reason, status_detail, + Some((decision.engine, policy_generation)), ); if supplied_authorization.denial.is_none() && !is_always_blocked_ip(destination.ip()) @@ -873,6 +878,7 @@ async fn preauthorize_transparent_open( &binary_identity, &denial.reason, "transparent_tcp_destination_denied", + Some((decision.engine, decision.policy_generation)), ); let _ = completion.send(TcpOpenDecision::Denied(TcpOpenDenial::InvalidDestination)); return None; @@ -914,6 +920,7 @@ async fn preauthorize_transparent_open( &binary_identity, &reason, status_detail, + Some((decision.engine, policy_generation)), ); let _ = completion.send(TcpOpenDecision::Denied(TcpOpenDenial::InvalidDestination)); @@ -948,6 +955,7 @@ async fn preauthorize_transparent_open( &binary_identity, &denial.reason, "transparent_tcp_destination_denied", + Some((decision.engine, policy_generation)), ); let _ = completion.send(TcpOpenDecision::Denied(TcpOpenDenial::InvalidDestination)); return None; @@ -1133,12 +1141,15 @@ pub(crate) fn connect_destination_outcome_for_test( .to_string() } +/// `decided_by` names the engine and generation of the egress decision that +/// denied the open, or is `None` when the open failed before policy evaluation. fn emit_staged_transparent_denial( destination: SocketAddr, mapped_host: Option<&str>, identity: &Result, reason: &str, status_detail: &'static str, + decided_by: Option<(&str, u64)>, ) { egress_emit!(build_staged_transparent_denial_event( destination, @@ -1146,6 +1157,7 @@ fn emit_staged_transparent_denial( identity, reason, status_detail, + decided_by, )); } @@ -1155,6 +1167,7 @@ fn build_staged_transparent_denial_event( identity: &Result, reason: &str, status_detail: &'static str, + decided_by: Option<(&str, u64)>, ) -> openshell_ocsf::OcsfEvent { let (binary, ancestors, cmdline, process) = identity.as_ref().map_or_else( |_| ("-".to_string(), "-".to_string(), "-".to_string(), None), @@ -1178,7 +1191,7 @@ fn build_staged_transparent_denial_event( }, ); let pid = process.map_or_else(|| "-".to_string(), |process| process.pid.to_string()); - NetworkActivityBuilder::new(openshell_ocsf::ctx::ctx()) + let mut builder = NetworkActivityBuilder::new(openshell_ocsf::ctx::ctx()) .activity(ActivityId::Open) .action(ActionId::Denied) .disposition(DispositionId::Blocked) @@ -1187,7 +1200,11 @@ fn build_staged_transparent_denial_event( .dst_endpoint(transparent_destination_endpoint(destination, mapped_host)) .actor_process(egress::actor_process( &binary, &pid, &ancestors, &cmdline, process, - )) + )); + if let Some((engine, generation)) = decided_by { + builder = builder.firewall_rule_at_generation("-", engine, generation); + } + builder .message(format!("Transparent TCP denied before relay: {reason}")) .status_detail(status_detail) .build() @@ -1434,7 +1451,13 @@ async fn handle_transparent_tcp_connection( Ok(mapping) => mapping, Err(error) => { warn!(%original, %error, "Denied transparent connection mapping"); - emit_transparent_mapping_denial(workload_addr, original, None, error.mapping_error()); + emit_transparent_mapping_denial( + workload_addr, + original, + None, + error.mapping_error(), + None, + ); emit_activity(&activity_tx, true, "transparent_tcp_mapping"); return Ok(()); } @@ -1478,6 +1501,7 @@ async fn handle_transparent_tcp_connection( original, Some(&host), MappingLookupError::EndpointMismatch, + Some((decision.engine, decision.policy_generation)), ); emit_activity(&activity_tx, true, "transparent_tcp_mapping"); return Ok(()); @@ -1501,12 +1525,19 @@ async fn handle_transparent_tcp_connection( original, Some(&host), MappingLookupError::InvalidMapping, + Some((decision.engine, decision.policy_generation)), ); emit_activity(&activity_tx, true, "transparent_tcp_mapping"); return Ok(()); } Err(TransparentPinRefusal::Mapping(error)) => { - emit_transparent_mapping_denial(workload_addr, original, Some(&host), error); + emit_transparent_mapping_denial( + workload_addr, + original, + Some(&host), + error, + Some((decision.engine, decision.policy_generation)), + ); emit_activity(&activity_tx, true, "transparent_tcp_mapping"); return Ok(()); } @@ -1606,7 +1637,14 @@ async fn handle_transparent_tcp_connection( } )); emit_activity(&activity_tx, false, "transparent_tcp"); - relay::relay_tcp(&mut client, &mut upstream, &generation_guard, &ctx).await + relay::relay_tcp( + &mut client, + &mut upstream, + &generation_guard, + &ctx, + decision.engine, + ) + .await } #[cfg(any(target_os = "linux", test))] @@ -1663,7 +1701,11 @@ fn build_transparent_tcp_allow_ocsf_event( )) .src_endpoint_addr(audit.workload.ip(), audit.workload.port()) .actor_process(Process::from_bypass(audit.binary, audit.pid, "")) - .firewall_rule(audit.policy_name, audit.engine) + .firewall_rule_at_generation( + audit.policy_name, + audit.engine, + audit.authorization_policy_generation, + ) .unmapped("matched_policy", audit.policy_name) .unmapped("normalized_domain", audit.normalized_domain) .unmapped("logical_destination", logical_destination) @@ -1771,7 +1813,28 @@ fn emit_transparent_mapping_denial( original: SocketAddr, mapped_host: Option<&str>, error: MappingLookupError, + decided_by: Option<(&str, u64)>, ) { + egress_emit!(build_transparent_mapping_denial_event( + workload, + original, + mapped_host, + error, + decided_by, + )); +} + +/// `decided_by` names the engine and generation of the egress decision made +/// before the mapping check, or is `None` when the open failed before policy +/// evaluation. +#[cfg(target_os = "linux")] +fn build_transparent_mapping_denial_event( + workload: SocketAddr, + original: SocketAddr, + mapped_host: Option<&str>, + error: MappingLookupError, + decided_by: Option<(&str, u64)>, +) -> openshell_ocsf::OcsfEvent { let detail = match error { MappingLookupError::Missing => "transparent_tcp_mapping_missing", MappingLookupError::Expired => "transparent_tcp_mapping_expired", @@ -1780,19 +1843,21 @@ fn emit_transparent_mapping_denial( | MappingLookupError::InvalidMapping | MappingLookupError::LockPoisoned => "transparent_tcp_destination_denied", }; - egress_emit!( - NetworkActivityBuilder::new(openshell_ocsf::ctx::ctx()) - .activity(ActivityId::Open) - .action(ActionId::Denied) - .disposition(DispositionId::Blocked) - .severity(SeverityId::Medium) - .status(StatusId::Failure) - .dst_endpoint(transparent_destination_endpoint(original, mapped_host)) - .src_endpoint_addr(workload.ip(), workload.port()) - .message(format!("Transparent TCP denied: {error}")) - .status_detail(detail) - .build() - ); + let mut builder = NetworkActivityBuilder::new(openshell_ocsf::ctx::ctx()) + .activity(ActivityId::Open) + .action(ActionId::Denied) + .disposition(DispositionId::Blocked) + .severity(SeverityId::Medium) + .status(StatusId::Failure) + .dst_endpoint(transparent_destination_endpoint(original, mapped_host)) + .src_endpoint_addr(workload.ip(), workload.port()); + if let Some((engine, generation)) = decided_by { + builder = builder.firewall_rule_at_generation("-", engine, generation); + } + builder + .message(format!("Transparent TCP denied: {error}")) + .status_detail(detail) + .build() } #[cfg(target_os = "linux")] @@ -1824,7 +1889,7 @@ fn emit_transparent_policy_denial( .dst_endpoint(Endpoint::from_domain(host, port)) .src_endpoint_addr(workload.ip(), workload.port()) .actor_process(Process::from_bypass(&binary, &pid, "-")) - .firewall_rule("-", decision.engine) + .firewall_rule_at_generation("-", decision.engine, decision.policy_generation) .message(format!("Transparent TCP denied {host}:{port}")) .status_detail(status_detail) .build() @@ -2237,6 +2302,7 @@ fn build_connect_allow_ocsf_event( port: u16, actor: &Process, policy: &str, + policy_generation: u64, l7_inspection: bool, engine: &str, ) -> openshell_ocsf::OcsfEvent { @@ -2254,7 +2320,7 @@ fn build_connect_allow_ocsf_event( .dst_endpoint(Endpoint::from_domain(host, port)) .src_endpoint_addr(peer_addr.ip(), peer_addr.port()) .actor_process(actor.clone()) - .firewall_rule(policy, engine) + .firewall_rule_at_generation(policy, engine, policy_generation) .message(format!("{connect_msg} allowed {host}:{port}")) .build() } @@ -2268,6 +2334,7 @@ fn build_forward_allow_ocsf_event( path: &str, actor: &Process, policy: &str, + policy_generation: u64, engine: &str, ) -> openshell_ocsf::OcsfEvent { HttpActivityBuilder::new(openshell_ocsf::ctx::ctx()) @@ -2283,7 +2350,7 @@ fn build_forward_allow_ocsf_event( .dst_endpoint(Endpoint::from_domain(host, port)) .src_endpoint(Endpoint::from_ip(peer_addr.ip(), peer_addr.port())) .actor_process(actor.clone()) - .firewall_rule(policy, engine) + .firewall_rule_at_generation(policy, engine, policy_generation) .message(format!("FORWARD allowed {method} {host}:{port}{path}")) .build() } @@ -2446,6 +2513,7 @@ fn build_forward_policy_deny_ocsf_event( path: &str, actor: &Process, reason: &str, + policy_generation: u64, engine: &str, ) -> openshell_ocsf::OcsfEvent { HttpActivityBuilder::new(openshell_ocsf::ctx::ctx()) @@ -2461,7 +2529,7 @@ fn build_forward_policy_deny_ocsf_event( .dst_endpoint(Endpoint::from_domain(host, port)) .src_endpoint(Endpoint::from_ip(peer_addr.ip(), peer_addr.port())) .actor_process(actor.clone()) - .firewall_rule("-", engine) + .firewall_rule_at_generation("-", engine, policy_generation) .message(format!("FORWARD denied {method} {host}:{port}{path}")) .status_detail(reason) .build() @@ -3100,7 +3168,7 @@ async fn handle_mediated_connection( .dst_endpoint(Endpoint::from_domain(&host_lc, port)) .src_endpoint_addr(workload_addr.ip(), workload_addr.port()) .actor_process(actor.clone()) - .firewall_rule("-", decision.engine) + .firewall_rule_at_generation("-", decision.engine, decision.policy_generation) .message(format!("CONNECT denied {host_lc}:{port}")) .status_detail(&deny_reason) .build(); @@ -3135,8 +3203,16 @@ async fn handle_mediated_connection( let connect_generation_guard = match connect_pin { Ok(guard) => guard, Err(error) => { - reject_stale_connect_policy(&mut client, &host_lc, port, activity_tx.as_ref(), error) - .await?; + reject_stale_connect_policy( + &mut client, + &host_lc, + port, + activity_tx.as_ref(), + decision.engine, + decision.policy_generation, + error, + ) + .await?; return Ok(()); } }; @@ -3344,8 +3420,16 @@ async fn handle_mediated_connection( decision.policy_generation, &connect_generation_guard, ) { - reject_stale_connect_policy(&mut client, &host_lc, port, activity_tx.as_ref(), error) - .await?; + reject_stale_connect_policy( + &mut client, + &host_lc, + port, + activity_tx.as_ref(), + decision.engine, + decision.policy_generation, + error, + ) + .await?; return Ok(()); } @@ -3404,6 +3488,8 @@ async fn handle_mediated_connection( &host_lc, port, activity_tx.as_ref(), + decision.engine, + decision.policy_generation, miette::miette!( "policy changed while CONNECT was dialing upstream \ [captured_generation:{} current_generation:{}]", @@ -3425,8 +3511,16 @@ async fn handle_mediated_connection( } }; if let Err(error) = connect_generation_guard.ensure_current() { - reject_stale_connect_policy(&mut client, &host_lc, port, activity_tx.as_ref(), error) - .await?; + reject_stale_connect_policy( + &mut client, + &host_lc, + port, + activity_tx.as_ref(), + decision.engine, + decision.policy_generation, + error, + ) + .await?; return Ok(()); } @@ -3445,6 +3539,7 @@ async fn handle_mediated_connection( port, &actor, policy_str, + decision.policy_generation, should_inspect_l7, decision.engine, )); @@ -3464,7 +3559,14 @@ async fn handle_mediated_connection( else { return Ok(()); }; - relay::relay_tcp(&mut client, &mut upstream, &generation_guard, &ctx).await?; + relay::relay_tcp( + &mut client, + &mut upstream, + &generation_guard, + &ctx, + decision.engine, + ) + .await?; return Ok(()); } @@ -3675,7 +3777,14 @@ async fn handle_mediated_connection( else { return Ok(()); }; - relay::relay_tcp(&mut client, &mut upstream, &generation_guard, &ctx).await?; + relay::relay_tcp( + &mut client, + &mut upstream, + &generation_guard, + &ctx, + decision.engine, + ) + .await?; } Ok(()) @@ -4245,19 +4354,43 @@ fn authorize_egress_intent_inner( } } -fn emit_l7_tunnel_close_after_policy_change(host: &str, port: u16, error: miette::Report) { - let event = NetworkActivityBuilder::new(openshell_ocsf::ctx::ctx()) +/// `pinned_generation` is the generation the connection was authorized under, +/// matching the L7 relay's stale-tunnel close event. +fn emit_l7_tunnel_close_after_policy_change( + host: &str, + port: u16, + engine: &str, + pinned_generation: u64, + error: miette::Report, +) { + egress_emit!(build_l7_tunnel_close_after_policy_change_event( + host, + port, + engine, + pinned_generation, + &error, + )); +} + +fn build_l7_tunnel_close_after_policy_change_event( + host: &str, + port: u16, + engine: &str, + pinned_generation: u64, + error: &miette::Report, +) -> openshell_ocsf::OcsfEvent { + 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(host, port)) + .firewall_rule_at_generation("-", engine, pinned_generation) .message(format!( "L7 tunnel closed before inspection because policy changed: {error}" )) - .build(); - egress_emit!(event); + .build() } async fn reject_stale_connect_policy( @@ -4265,6 +4398,8 @@ async fn reject_stale_connect_policy( host: &str, port: u16, activity_tx: Option<&ActivitySender>, + engine: &str, + pinned_generation: u64, error: miette::Report, ) -> Result<()> where @@ -4276,7 +4411,7 @@ where error = %error, "CONNECT rejected because policy changed after L4 authorization" ); - emit_l7_tunnel_close_after_policy_change(host, port, error); + emit_l7_tunnel_close_after_policy_change(host, port, engine, pinned_generation, error); emit_activity_simple(activity_tx, true, "policy_stale"); respond( client, @@ -5973,6 +6108,7 @@ async fn handle_forward_proxy_inner( &telemetry_path, &actor, reason, + decision.policy_generation, decision.engine, )], Some(&connect_span), @@ -6031,7 +6167,13 @@ async fn handle_forward_proxy_inner( error = %e, "Forward proxy rejected request because policy generation changed after L4 decision" ); - emit_l7_tunnel_close_after_policy_change(&host_lc, port, e); + emit_l7_tunnel_close_after_policy_change( + &host_lc, + port, + decision.engine, + decision.policy_generation, + e, + ); emit_activity_simple(activity_tx, true, "policy_stale"); respond( client, @@ -6181,6 +6323,8 @@ async fn handle_forward_proxy_inner( emit_l7_tunnel_close_after_policy_change( &host_lc, port, + decision.engine, + decision.policy_generation, miette::miette!( "policy changed before forward L7 evaluation [expected_generation:{} current_generation:{}]", forward_generation_guard.captured_generation(), @@ -6219,7 +6363,13 @@ async fn handle_forward_proxy_inner( error = %e, "Forward proxy rejected request because L7 tunnel engine could not be cloned" ); - emit_l7_tunnel_close_after_policy_change(&host_lc, port, e); + emit_l7_tunnel_close_after_policy_change( + &host_lc, + port, + decision.engine, + decision.policy_generation, + e, + ); emit_activity_simple(activity_tx, true, "policy_stale"); correlation.record_rejection(403, HttpOutcome::Denied, None); respond( @@ -6612,7 +6762,11 @@ async fn handle_forward_proxy_inner( .dst_endpoint(Endpoint::from_domain(&host_lc, port)) .src_endpoint(Endpoint::from_ip(workload_addr.ip(), workload_addr.port())) .actor_process(actor.clone()) - .firewall_rule(policy_str, engine_type) + .firewall_rule_at_generation( + policy_str, + engine_type, + tunnel_engine.captured_generation(), + ) .message(log_message) .build(); emit_forward_l7_decision(event, evaluation_error, &connect_span, request_correlation); @@ -6749,7 +6903,13 @@ async fn handle_forward_proxy_inner( error = %e, "Forward proxy rejected request because policy changed before upstream connect" ); - emit_l7_tunnel_close_after_policy_change(&host_lc, port, e); + emit_l7_tunnel_close_after_policy_change( + &host_lc, + port, + decision.engine, + decision.policy_generation, + e, + ); emit_activity_simple(activity_tx, true, "policy_stale"); correlation.record_rejection(403, HttpOutcome::Denied, None); respond( @@ -6772,6 +6932,8 @@ async fn handle_forward_proxy_inner( emit_l7_tunnel_close_after_policy_change( &host_lc, port, + decision.engine, + decision.policy_generation, miette::miette!( "policy changed before forward middleware evaluation [expected_generation:{middleware_expected_generation} current_generation:{generation}]", ), @@ -7230,7 +7392,13 @@ async fn handle_forward_proxy_inner( error = %e, "Forward proxy rejected request because policy changed before relay" ); - emit_l7_tunnel_close_after_policy_change(&host_lc, port, e); + emit_l7_tunnel_close_after_policy_change( + &host_lc, + port, + decision.engine, + decision.policy_generation, + e, + ); if let Some(session) = middleware_session.take() { session .end(openshell_core::proto::MiddlewareSessionEndReason::PolicyReload) @@ -7326,7 +7494,13 @@ async fn handle_forward_proxy_inner( error = %e, "Forward proxy rejected request because policy changed during upstream connect" ); - emit_l7_tunnel_close_after_policy_change(&host_lc, port, e); + emit_l7_tunnel_close_after_policy_change( + &host_lc, + port, + decision.engine, + decision.policy_generation, + e, + ); if let Some(session) = middleware_session.take() { session .end(openshell_core::proto::MiddlewareSessionEndReason::PolicyReload) @@ -7474,6 +7648,7 @@ async fn handle_forward_proxy_inner( &telemetry_path, &actor, policy_str, + decision.policy_generation, network_engine.label(), )); emit_forward_success_activity(activity_tx, l7_activity_pending); @@ -8029,6 +8204,7 @@ process: 443, &decision.actor_process(), "api", + decision.policy_generation, false, "opa", ); @@ -10101,6 +10277,63 @@ process: { run_as_user: sandbox, run_as_group: sandbox } assert_eq!(connector.addrs(), &["8.8.8.8:5432".parse().unwrap()]); } + #[test] + fn policy_change_close_records_the_pinned_generation() { + let event = build_l7_tunnel_close_after_policy_change_event( + "api.github.com", + 443, + "opa", + 1, + &miette::miette!( + "policy generation is stale [captured_generation:1 current_generation:2]" + ), + ); + let json = serde_json::to_value(event).unwrap(); + assert_eq!(json["action"], "Denied"); + assert_eq!( + json["firewall_rule"], + serde_json::json!({"name": "-", "type": "opa", "version": "1"}) + ); + } + + #[cfg(target_os = "linux")] + #[test] + fn mapping_denial_after_evaluation_records_the_decision_generation() { + let workload: SocketAddr = "10.0.0.5:40000".parse().unwrap(); + let original: SocketAddr = "198.18.0.2:443".parse().unwrap(); + + let stale = build_transparent_mapping_denial_event( + workload, + original, + Some("api.example.test"), + MappingLookupError::PolicyChanged, + Some(("opa", 5)), + ); + let stale = serde_json::to_value(stale).unwrap(); + assert_eq!( + stale["status_detail"], + "transparent_tcp_mapping_stale_policy" + ); + assert_eq!( + stale["firewall_rule"], + serde_json::json!({"name": "-", "type": "opa", "version": "5"}) + ); + + let before_evaluation = build_transparent_mapping_denial_event( + workload, + original, + None, + MappingLookupError::Missing, + None, + ); + let before_evaluation = serde_json::to_value(before_evaluation).unwrap(); + assert_eq!( + before_evaluation["status_detail"], + "transparent_tcp_mapping_missing" + ); + assert!(before_evaluation.get("firewall_rule").is_none()); + } + #[test] fn staged_denial_names_the_mapped_host_and_keeps_the_synthetic_address() { let (open, _) = staged_curl_open("198.18.0.2:80".parse().unwrap(), 1); @@ -10110,18 +10343,21 @@ process: { run_as_user: sandbox, run_as_group: sandbox } &open.binary_identity, "endpoint blocked.invalid:80 is not allowed by any policy", "transparent_tcp_policy_denied", + Some(("opa", 4)), ); assert_eq!( mapped.format_shorthand(), format!( - "NET:OPEN [MED] DENIED {}(0) -> blocked.invalid:80 [reason:transparent_tcp_policy_denied]", + "NET:OPEN [MED] DENIED {}(0) -> blocked.invalid:80 [policy:- engine:opa] [reason:transparent_tcp_policy_denied]", executable_path("/usr/bin/curl").display() ) ); + let mapped = serde_json::to_value(mapped).unwrap(); assert_eq!( - serde_json::to_value(mapped).unwrap()["dst_endpoint"], + mapped["dst_endpoint"], serde_json::json!({"domain": "blocked.invalid", "ip": "198.18.0.2", "port": 80}) ); + assert_eq!(mapped["firewall_rule"]["version"], "4"); let unmapped = build_staged_transparent_denial_event( "203.0.113.7:443".parse().unwrap(), @@ -10129,11 +10365,14 @@ process: { run_as_user: sandbox, run_as_group: sandbox } &open.binary_identity, "endpoint 203.0.113.7:443 is not allowed by any policy", "transparent_tcp_policy_denied", + None, ); + let unmapped = serde_json::to_value(unmapped).unwrap(); assert_eq!( - serde_json::to_value(unmapped).unwrap()["dst_endpoint"], + unmapped["dst_endpoint"], serde_json::json!({"ip": "203.0.113.7", "port": 443}) ); + assert!(unmapped.get("firewall_rule").is_none()); } #[tokio::test] @@ -13282,11 +13521,13 @@ network_policies: &Process::from_bypass("/usr/bin/curl", "42", "/usr/bin/bash") .with_cmd_line("curl http://api.example.com/v1/models"), reason, + 9, "opa", ); let json = event.to_json().unwrap(); assert_eq!(json["status_detail"], reason); + assert_eq!(json["firewall_rule"]["version"], "9"); assert_eq!(json["action"], "Denied"); assert_eq!(json["disposition"], "Blocked"); } @@ -13358,6 +13599,7 @@ network_policies: assert!(json["actor"]["process"].get("parent_process").is_none()); assert_eq!(json["dst_endpoint"]["domain"], "redis.openshell.demo"); assert_eq!(json["firewall_rule"]["name"], "redis"); + assert_eq!(json["firewall_rule"]["version"], "7"); assert_eq!(json["unmapped"]["synthetic_destination"], "198.18.0.7:6379"); assert_eq!( json["unmapped"]["connected_real_destination"], @@ -13475,6 +13717,7 @@ network_policies: &path, &Process::from_bypass("/usr/bin/curl", "42", "/usr/bin/bash").with_cmd_line("curl"), "allow_api", + 3, "opa", ) .to_json() @@ -13487,11 +13730,13 @@ network_policies: &path, &Process::from_bypass("/usr/bin/curl", "42", "/usr/bin/bash").with_cmd_line("curl"), "policy denied", + 3, "opa", ) .to_json() .unwrap(); for event in [&allowed, &denied] { + assert_eq!(event["firewall_rule"]["version"], "3"); assert_eq!(event["http_request"]["url"]["path"], "/v1/[CREDENTIAL]"); let serialized = event.to_string(); assert!(!serialized.contains("API_TOKEN"), "{serialized}"); @@ -13511,6 +13756,7 @@ network_policies: &forward_telemetry_path(target), &Process::from_bypass("/usr/bin/curl", "42", "/usr/bin/bash").with_cmd_line("curl"), "allow_api", + 3, "opa", ) .to_json() diff --git a/crates/openshell-supervisor-network/src/proxy/relay.rs b/crates/openshell-supervisor-network/src/proxy/relay.rs index 2a6eeab907..7c45504336 100644 --- a/crates/openshell-supervisor-network/src/proxy/relay.rs +++ b/crates/openshell-supervisor-network/src/proxy/relay.rs @@ -38,6 +38,8 @@ enum PreparedHttpPolicy<'a> { pub(super) struct RelayContext<'a> { request: &'a L7EvalContext, policy: PreparedHttpPolicy<'a>, + /// Engine that authorized the connection, for the stale-relay close event. + engine: &'static str, } /// Non-blocking observation channels attached to an authorized HTTP relay. @@ -214,6 +216,8 @@ pub(super) fn prepare_http_relay<'a>( emit_l7_tunnel_close_after_policy_change( &decision.intent.destination.host, decision.intent.destination.port, + decision.engine, + decision.policy_generation, error, ); }; @@ -250,6 +254,8 @@ pub(super) fn prepare_http_relay<'a>( emit_l7_tunnel_close_after_policy_change( &decision.intent.destination.host, decision.intent.destination.port, + decision.engine, + decision.policy_generation, error, ); return None; @@ -274,7 +280,11 @@ pub(super) fn prepare_http_relay<'a>( } }; - Some(RelayContext { request, policy }) + Some(RelayContext { + request, + policy, + engine: decision.engine, + }) } /// Pin the generation used by a raw relay so a policy change that affects the @@ -296,6 +306,8 @@ pub(super) fn prepare_raw_relay( emit_l7_tunnel_close_after_policy_change( &decision.intent.destination.host, decision.intent.destination.port, + decision.engine, + decision.policy_generation, error, ); None @@ -341,7 +353,7 @@ where upstream, context.request, ) => result, - () = close_stale_http_relay(context.request, &generation_guard) => Ok(()) + () = close_stale_http_relay(context.request, context.engine, &generation_guard) => Ok(()) } } PreparedHttpPolicy::Inspect { configs, evaluator } => { @@ -354,7 +366,7 @@ where upstream, context.request, ) => result, - () = close_stale_http_relay(context.request, &generation_guard) => Ok(()) + () = close_stale_http_relay(context.request, context.engine, &generation_guard) => Ok(()) } } PreparedHttpPolicy::Passthrough { @@ -369,19 +381,23 @@ where &generation_guard, Some(&middleware), ) => result, - () = close_stale_http_relay(context.request, &generation_guard) => Ok(()) + () = close_stale_http_relay(context.request, context.engine, &generation_guard) => Ok(()) } } } } -async fn close_stale_http_relay(request: &L7EvalContext, guard: &PolicyGenerationGuard) { +async fn close_stale_http_relay( + request: &L7EvalContext, + engine: &str, + guard: &PolicyGenerationGuard, +) { guard.wait_until_stale().await; crate::l7::correlation::record_current_failure( crate::l7::correlation::HttpOutcome::PlatformError, "policy_reloaded", ); - emit_stale_relay_close(request, guard); + emit_stale_relay_close(request, engine, guard); } // Exercise the production single/multiple-route dispatch from L7 fixtures. @@ -393,7 +409,7 @@ pub async fn relay_inspected_http_stream_for_test( evaluator: TunnelPolicyEngine, // An inspected tunnel selects middleware from `evaluator`'s snapshot; // kept so fixtures build the engine and the evaluator the same way. - _middleware_engine: &PolicyEngine, + middleware_engine: &PolicyEngine, request: &L7EvalContext, ) -> Result<()> where @@ -409,6 +425,7 @@ where configs, evaluator: Box::new(evaluator), }, + engine: middleware_engine.label(), }, ) .await @@ -420,6 +437,7 @@ pub(super) async fn relay_tcp( upstream: &mut U, generation_guard: &PolicyGenerationGuard, request: &L7EvalContext, + engine: &str, ) -> Result<()> where C: AsyncRead + AsyncWrite + Unpin, @@ -430,16 +448,18 @@ where result.into_diagnostic()?; } () = generation_guard.wait_until_stale() => { - emit_stale_relay_close(request, generation_guard); + emit_stale_relay_close(request, engine, generation_guard); } } Ok(()) } -fn emit_stale_relay_close(request: &L7EvalContext, guard: &PolicyGenerationGuard) { +fn emit_stale_relay_close(request: &L7EvalContext, engine: &str, guard: &PolicyGenerationGuard) { emit_l7_tunnel_close_after_policy_change( &request.host, request.port, + engine, + guard.captured_generation(), miette::miette!( "policy generation is stale [captured_generation:{} current_generation:{}]", guard.captured_generation(), @@ -713,7 +733,14 @@ mod tests { let (_upstream_peer, mut proxy_upstream) = tokio::io::duplex(64); let relay = tokio::spawn(async move { - relay_tcp(&mut proxy_client, &mut proxy_upstream, &guard, &request).await + relay_tcp( + &mut proxy_client, + &mut proxy_upstream, + &guard, + &request, + "opa", + ) + .await }); tokio::task::yield_now().await; @@ -909,7 +936,14 @@ network_policies: let (_client_peer, mut proxy_client) = tokio::io::duplex(64); let (_upstream_peer, mut proxy_upstream) = tokio::io::duplex(64); let relay = tokio::spawn(async move { - relay_tcp(&mut proxy_client, &mut proxy_upstream, &guard, &request).await + relay_tcp( + &mut proxy_client, + &mut proxy_upstream, + &guard, + &request, + "opa", + ) + .await }); tokio::task::yield_now().await; @@ -959,7 +993,14 @@ network_policies: let (mut client_peer, mut proxy_client) = tokio::io::duplex(64); let (mut upstream_peer, mut proxy_upstream) = tokio::io::duplex(64); let relay = tokio::spawn(async move { - relay_tcp(&mut proxy_client, &mut proxy_upstream, &guard, &request).await + relay_tcp( + &mut proxy_client, + &mut proxy_upstream, + &guard, + &request, + "opa", + ) + .await }); engine diff --git a/crates/openshell-supervisor-network/src/proxy/tests/compatibility.rs b/crates/openshell-supervisor-network/src/proxy/tests/compatibility.rs index a06cf90b05..46fe51c986 100644 --- a/crates/openshell-supervisor-network/src/proxy/tests/compatibility.rs +++ b/crates/openshell-supervisor-network/src/proxy/tests/compatibility.rs @@ -247,6 +247,7 @@ fn representative_adapter_allows_preserve_ocsf_fields() { 8443, &Process::from_bypass("/usr/bin/curl", "42", "/usr/bin/sh").with_cmd_line("curl --proxy"), "proxy_compatibility", + 5, true, "opa", )) @@ -262,6 +263,7 @@ fn representative_adapter_allows_preserve_ocsf_fields() { assert_eq!(connect["actor"]["process"]["name"], "/usr/bin/curl"); assert_eq!(connect["firewall_rule"]["name"], "proxy_compatibility"); assert_eq!(connect["firewall_rule"]["type"], "opa"); + assert_eq!(connect["firewall_rule"]["version"], "5"); assert_eq!(connect["message"], "CONNECT_L7 allowed target.example:8443"); let forward = serde_json::to_value(build_forward_allow_ocsf_event( @@ -272,6 +274,7 @@ fn representative_adapter_allows_preserve_ocsf_fields() { "/v1/items", &Process::from_bypass("/usr/bin/curl", "42", "/usr/bin/sh").with_cmd_line("curl --proxy"), "proxy_compatibility", + 5, "opa", )) .unwrap(); @@ -286,6 +289,7 @@ fn representative_adapter_allows_preserve_ocsf_fields() { assert_eq!(forward["http_request"]["http_method"], "GET"); assert_eq!(forward["firewall_rule"]["name"], "proxy_compatibility"); assert_eq!(forward["firewall_rule"]["type"], "opa"); + assert_eq!(forward["firewall_rule"]["version"], "5"); assert_eq!( forward["message"], "FORWARD allowed GET target.example:8080/v1/items" diff --git a/crates/openshell-supervisor/src/config_runtime.rs b/crates/openshell-supervisor/src/config_runtime.rs index 46c4f8751b..6ed1567d1b 100644 --- a/crates/openshell-supervisor/src/config_runtime.rs +++ b/crates/openshell-supervisor/src/config_runtime.rs @@ -468,6 +468,7 @@ impl ConfigRuntime { result.config_revision, generation.clone(), ); + let active_generation = generation.captured_generation(); self.policy_generation = Some(generation); let policy = result .policy @@ -485,6 +486,7 @@ impl ConfigRuntime { .status(StatusId::Success) .state(StateId::Enabled, "loaded") .unmapped("policy_hash", serde_json::json!(&result.policy_hash)) + .unmapped("active_generation", serde_json::json!(active_generation)) .unmapped("global_version", serde_json::json!(result.global_policy_version)) .message(format!( "Policy reloaded successfully (global) [policy_hash:{} global_version:{}]", @@ -499,6 +501,10 @@ impl ConfigRuntime { .status(StatusId::Success) .state(StateId::Enabled, "loaded") .unmapped("policy_hash", serde_json::json!(&result.policy_hash)) + .unmapped( + "active_generation", + serde_json::json!(active_generation) + ) .message(format!( "Policy reloaded successfully [policy_hash:{}]", result.policy_hash @@ -520,6 +526,7 @@ impl ConfigRuntime { .status(StatusId::Success) .state(StateId::Enabled, "loaded") .unmapped("policy_hash", serde_json::json!(&result.policy_hash)) + .unmapped("active_generation", serde_json::json!(active_generation)) .message(format!( "Policy reloaded successfully and fail-closed quarantine cleared [policy_hash:{}]", result.policy_hash @@ -539,6 +546,7 @@ impl ConfigRuntime { "supervisor_middleware_service_count", serde_json::json!(result.supervisor_middleware_services.len()) ) + .unmapped("active_generation", serde_json::json!(active_generation)) .message(format!( "Supervisor policy runtime reloaded atomically [service_count:{}]", result.supervisor_middleware_services.len() @@ -1352,7 +1360,10 @@ async fn run_policy_poll_loop_with_client( runtime.settings = result.settings; enqueue_policy_status( &status_sender, - PolicyStatusUpdate::initial_loaded(&candidate), + PolicyStatusUpdate::initial_loaded( + &candidate, + generation.captured_generation(), + ), ); debug!( config_revision = runtime.config_revision, diff --git a/crates/openshell-supervisor/src/lib.rs b/crates/openshell-supervisor/src/lib.rs index 3ec4035113..367c970a34 100644 --- a/crates/openshell-supervisor/src/lib.rs +++ b/crates/openshell-supervisor/src/lib.rs @@ -3896,18 +3896,27 @@ struct PolicyStatusUpdate { #[derive(Clone, Debug, PartialEq, Eq)] enum PolicyStatusSuccessEvent { - InitialAcknowledgement { policy_hash: String }, - UnchangedAcknowledgement { policy_hash: String }, + /// `active_generation` is the policy engine generation pinned when startup + /// installed the acknowledged policy. Decision events carry the same value + /// in `firewall_rule.version`. + InitialAcknowledgement { + policy_hash: String, + active_generation: u64, + }, + UnchangedAcknowledgement { + policy_hash: String, + }, } impl PolicyStatusUpdate { - fn initial_loaded(ack: &InitialPolicyAck) -> Self { + fn initial_loaded(ack: &InitialPolicyAck, active_generation: u64) -> Self { Self { version: ack.version, loaded: true, error: String::new(), success_event: Some(PolicyStatusSuccessEvent::InitialAcknowledgement { policy_hash: ack.policy_hash.clone(), + active_generation, }), } } @@ -4298,36 +4307,43 @@ async fn run_policy_status_reporter( } if let Some(event) = update.success_event { - let (policy_hash, message) = match event { - PolicyStatusSuccessEvent::InitialAcknowledgement { policy_hash } => ( - policy_hash, - format!( - "Acknowledged initial policy revision as loaded [version:{}]", - update.version - ), - ), - PolicyStatusSuccessEvent::UnchangedAcknowledgement { policy_hash } => ( - policy_hash, - format!( - "Acknowledged unchanged policy revision as loaded [version:{}]", - update.version - ), - ), - }; - ocsf_emit!( - ConfigStateChangeBuilder::new(ocsf_ctx()) - .severity(SeverityId::Informational) - .status(StatusId::Success) - .state(StateId::Enabled, "loaded") - .unmapped("version", serde_json::json!(update.version)) - .unmapped("policy_hash", serde_json::json!(policy_hash)) - .message(message) - .build() - ); + ocsf_emit!(policy_status_success_event(update.version, event)); } } } +/// Build the CONFIG event recorded when the gateway acknowledges a policy +/// revision as loaded. The initial acknowledgement also records the policy +/// engine generation that startup installed, so decision events can be joined +/// to this policy hash by `firewall_rule.version`. +fn policy_status_success_event(version: u32, event: PolicyStatusSuccessEvent) -> OcsfEvent { + let (policy_hash, active_generation, message) = match event { + PolicyStatusSuccessEvent::InitialAcknowledgement { + policy_hash, + active_generation, + } => ( + policy_hash, + Some(active_generation), + format!("Acknowledged initial policy revision as loaded [version:{version}]"), + ), + PolicyStatusSuccessEvent::UnchangedAcknowledgement { policy_hash } => ( + policy_hash, + None, + format!("Acknowledged unchanged policy revision as loaded [version:{version}]"), + ), + }; + let mut builder = ConfigStateChangeBuilder::new(ocsf_ctx()) + .severity(SeverityId::Informational) + .status(StatusId::Success) + .state(StateId::Enabled, "loaded") + .unmapped("version", serde_json::json!(version)) + .unmapped("policy_hash", serde_json::json!(policy_hash)); + if let Some(active_generation) = active_generation { + builder = builder.unmapped("active_generation", serde_json::json!(active_generation)); + } + builder.message(message).build() +} + fn enqueue_policy_status(sender: &UnboundedSender, update: PolicyStatusUpdate) { let version = update.version; if let Err(error) = sender.send(update) { @@ -4484,7 +4500,7 @@ async fn install_builtin_middleware_registry(engine: &PolicyEngine) -> Result<() Vec::new(), ) .await?; - engine.replace_middleware_registry(registry) + engine.replace_middleware_registry(registry).map(|_| ()) } /// Wait the configured poll interval, but never past the point at which an @@ -4530,6 +4546,25 @@ struct MiddlewareRegistryReconciliation<'a> { status: &'a mut MiddlewareRegistryStatus, } +/// Build the CONFIG event recorded when a new middleware registry is +/// installed. Installing it advances the policy engine generation, so the +/// event records the generation it activated. +fn middleware_registry_reloaded_event(service_count: usize, active_generation: u64) -> OcsfEvent { + ConfigStateChangeBuilder::new(ocsf_ctx()) + .severity(SeverityId::Informational) + .status(StatusId::Success) + .state(StateId::Enabled, "loaded") + .unmapped( + "supervisor_middleware_service_count", + serde_json::json!(service_count), + ) + .unmapped("active_generation", serde_json::json!(active_generation)) + .message(format!( + "Supervisor middleware registry reloaded [service_count:{service_count}]" + )) + .build() +} + async fn reconcile_middleware_registry( engine: &PolicyEngine, middleware_connector: &MiddlewareConnector, @@ -4546,7 +4581,7 @@ async fn reconcile_middleware_registry( .await .and_then(|registry| engine.replace_middleware_registry(registry)) { - Ok(()) => { + Ok(active_generation) => { retain_extension_credentials( reconciliation.extension_credentials, reconciliation.desired_services, @@ -4557,21 +4592,10 @@ async fn reconcile_middleware_registry( .current_services .extend_from_slice(reconciliation.desired_services); *reconciliation.status = MiddlewareRegistryStatus::Synchronized; - ocsf_emit!( - ConfigStateChangeBuilder::new(ocsf_ctx()) - .severity(SeverityId::Informational) - .status(StatusId::Success) - .state(StateId::Enabled, "loaded") - .unmapped( - "supervisor_middleware_service_count", - serde_json::json!(reconciliation.current_services.len()) - ) - .message(format!( - "Supervisor middleware registry reloaded [service_count:{}]", - reconciliation.current_services.len() - )) - .build() - ); + ocsf_emit!(middleware_registry_reloaded_event( + reconciliation.current_services.len(), + active_generation, + )); } Err(error) => { // Emit only on the transition into the failed state to avoid @@ -8229,6 +8253,51 @@ permit (principal, action == Sandbox::Action::"NetworkConnect", .contains("previous policy IS active") ); } + + #[test] + fn initial_policy_acknowledgement_records_active_generation() { + let ack = InitialPolicyAck { + version: 4, + policy_hash: "sha256:initial".to_string(), + config_revision: 11, + }; + let update = PolicyStatusUpdate::initial_loaded(&ack, 3); + let event = policy_status_success_event( + update.version, + update.success_event.expect("initial acknowledgement event"), + ); + let json = event.to_json().unwrap(); + assert_eq!(json["unmapped"]["policy_hash"], "sha256:initial"); + assert_eq!(json["unmapped"]["version"], 4); + assert_eq!(json["unmapped"]["active_generation"], 3); + } + + #[test] + fn unchanged_policy_acknowledgement_omits_active_generation() { + let update = PolicyStatusUpdate::unchanged_loaded(5, "sha256:same".to_string()); + let event = policy_status_success_event( + update.version, + update + .success_event + .expect("unchanged acknowledgement event"), + ); + let json = event.to_json().unwrap(); + assert_eq!(json["unmapped"]["policy_hash"], "sha256:same"); + assert!(json["unmapped"].get("active_generation").is_none()); + } + + #[test] + fn middleware_registry_reload_records_active_generation() { + let json = middleware_registry_reloaded_event(2, 7).to_json().unwrap(); + assert_eq!(json["unmapped"]["supervisor_middleware_service_count"], 2); + assert_eq!(json["unmapped"]["active_generation"], 7); + assert!( + json["message"] + .as_str() + .unwrap() + .contains("Supervisor middleware registry reloaded [service_count:2]") + ); + } } #[cfg(test)] diff --git a/docs/observability/ocsf-json-export.mdx b/docs/observability/ocsf-json-export.mdx index 26ef0fbff8..e992a9f5cc 100644 --- a/docs/observability/ocsf-json-export.mdx +++ b/docs/observability/ocsf-json-export.mdx @@ -223,7 +223,8 @@ Each JSONL file line, or the payload after the stderr marker, is a complete OCSF }, "firewall_rule": { "name": "github_api", - "type": "opa" + "type": "opa", + "version": "3" } } ``` @@ -292,6 +293,11 @@ And a denied connection, produced when `curl https://github.com` runs in a sandb "cmd_line": "curl https://github.com" } }, + "firewall_rule": { + "name": "-", + "type": "opa", + "version": "3" + }, "action_id": 2, "action": "Denied", "disposition_id": 2, @@ -417,6 +423,31 @@ control is tracked in Leave supervisor trace export disabled if your deployment requires a denial-only volume bound. OCSF records and request receipts still work without it. +## Policy Generation on Decisions + +Allow, audit, and deny decisions record the policy engine generation they were made under in `firewall_rule.version`. The sandbox supervisor keeps this counter and advances it whenever the policy engine replaces its active configuration: when a policy is installed or reloaded, when the supervisor middleware registry or provider credentials are reinstalled, and when fail-closed quarantine starts or ends. + +Policy activation events record the generation they activated in `unmapped.active_generation`. Successful policy loads also carry `unmapped.policy_hash`: + +```json +{ + "class_uid": 5019, + "message": "Policy reloaded successfully [policy_hash:0cc0c2b525573c07]", + "unmapped": { + "policy_hash": "0cc0c2b525573c07", + "active_generation": 3 + } +} +``` + +To find the policy behind a decision, take the events from the same supervisor lifetime and select the most recent event that carries `unmapped.policy_hash` and whose `active_generation` is less than or equal to the decision's `firewall_rule.version`. Some reinstalls advance the generation without changing the policy and without emitting a load event, so an exact match is not always available. Startup does not emit a load event for every policy source. When no such event precedes a decision, the event stream alone does not identify its policy. Do not join on timestamps. Lines from different emitters can be written out of order, and the generation records the policy a decision was actually made under, not the one that was current when the line was written. + +Policy validation failures emit a `CONFIG` event with `active_generation` and `candidate_policy_hash`, the hash of the rejected candidate. Its state is `fail_closed` when every request is denied under that generation, or `retained_last_valid` when the previous policy stays active. + +The generation starts at zero when the supervisor starts. Use the `LIFECYCLE` start event as the boundary between supervisor lifetimes. + +Layer 4 decisions (CONNECT, forward proxy, and transparent TCP) and layer 7 decisions for REST, JSON-RPC, MCP, GraphQL, and inspected WebSocket messages carry the generation. Denials made without matching a rule, such as when the calling process cannot be identified, carry the generation that was active when the denial was made. Events that are not policy decisions, such as MCP protocol version rejections and credential binding failures, leave `firewall_rule.version` unset. Policy DNS refusals also leave it unset. When the workload then connects anyway, the transparent TCP denial that follows carries the generation. A transparent TCP connection that passes policy but fails the DNS mapping check, for example because the policy changed in between, carries the generation of that policy decision. Connections closed because the policy changed carry the generation they were authorized under. + ## OCSF Event Classes in JSON The `class_uid` field identifies the event type: