diff --git a/AGENTS.md b/AGENTS.md index 0133dd3de3..ecc9ea807e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -152,7 +152,7 @@ let event = NetworkActivityBuilder::new(crate::ocsf_ctx()) .status(StatusId::Failure) .dst_endpoint(Endpoint::from_domain(&host, port)) .actor_process(Process::new(&binary, pid)) - .firewall_rule(&policy_name, &engine_type) + .firewall_rule_at_generation(&policy_name, decision.engine, decision.policy_generation) .message(format!("CONNECT denied {host}:{port}")) .build(); ocsf_emit!(event); @@ -160,6 +160,7 @@ ocsf_emit!(event); ### Key points +- Allow, audit, and deny decision events must record the policy generation that made them (`firewall_rule_at_generation`, or a `FirewallRule` built with `with_policy_generation`), so consumers can join each decision to its policy. Use plain `firewall_rule` only for events that are not policy decisions, such as rejections made before policy evaluation. - `crate::ocsf_ctx()` returns the process-wide `EventContext`. It is always available (falls back to defaults in tests). - `ocsf_emit!()` is non-blocking and cannot panic. It stores the event in a thread-local and emits via `tracing::info!()`. - In `openshell-supervisor-network`, the inspected request scope automatically correlates all OCSF records at emission, including findings, and uses the request span without creating a denial-only span. Emit through `crate::telemetry::egress_emit!` or `crate::telemetry::emit_decision`; Clippy rejects direct `ocsf_emit!` calls there. diff --git a/crates/openshell-ocsf/src/builders/http.rs b/crates/openshell-ocsf/src/builders/http.rs index e2f85bdab2..50c92bb36c 100644 --- a/crates/openshell-ocsf/src/builders/http.rs +++ b/crates/openshell-ocsf/src/builders/http.rs @@ -171,6 +171,31 @@ 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 + } + + /// Set a prepared firewall rule, such as one built with + /// [`FirewallRule::with_policy_generation`] for a decision or without a + /// generation for a rejection made before policy evaluation. + #[must_use] + pub fn firewall_rule_value(mut self, rule: FirewallRule) -> Self { + self.firewall_rule = Some(rule); + self + } } impl_activity_setter!(HttpActivityBuilder); @@ -272,4 +297,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..3442bf5647 100644 --- a/crates/openshell-ocsf/src/builders/network.rs +++ b/crates/openshell-ocsf/src/builders/network.rs @@ -203,6 +203,31 @@ 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 + } + + /// Set a prepared firewall rule, such as one built with + /// [`FirewallRule::with_policy_generation`] for a decision or without a + /// generation for a rejection made before policy evaluation. + #[must_use] + pub fn firewall_rule_value(mut self, rule: FirewallRule) -> Self { + self.firewall_rule = Some(rule); + self + } } impl_activity_setter!(NetworkActivityBuilder); @@ -292,5 +317,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 fed0b9738c..0393b8cac4 100644 --- a/crates/openshell-policy-cedar-runtime/src/backend.rs +++ b/crates/openshell-policy-cedar-runtime/src/backend.rs @@ -63,6 +63,11 @@ impl PolicyBackend for CedarOnlyEngine { self.middleware() .generation_guard(self.middleware().current_generation()) } + fn decision_generation(&self, _guard: &PolicyGenerationGuard) -> u64 { + // The configuration guard pins the middleware generation; Cedar + // decisions report Cedar's own generation. + PolicyBackend::current_generation(self) + } fn binary_identity_required(&self) -> bool { true } @@ -96,8 +101,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-cedar-runtime/src/cedar_only/tests.rs b/crates/openshell-policy-cedar-runtime/src/cedar_only/tests.rs index 1c1b65ff62..f4016ad06a 100644 --- a/crates/openshell-policy-cedar-runtime/src/cedar_only/tests.rs +++ b/crates/openshell-policy-cedar-runtime/src/cedar_only/tests.rs @@ -508,6 +508,45 @@ fn middleware_only_reload_advances_the_cedar_generation_and_closes_tunnels() { ); } +/// Policy load events record `decision_generation` as `active_generation`, so +/// it must be the generation Cedar decisions report, not the middleware +/// generation the configuration guard pins. +#[test] +fn decision_generation_reports_the_cedar_generation_after_a_commit() { + let cedar = Arc::new( + CedarOnlyEngine::from_proto(&middleware_policy("api.example.com")).expect("policy loads"), + ); + let engine = openshell_policy_runtime_interface::PolicyEngine::from(Arc::clone(&cedar)); + // A registry swap advances only the middleware generation, so the two + // counters diverge. + engine + .replace_middleware_registry(MiddlewareRegistry::default()) + .expect("registry swap"); + let staged = cedar + .stage(&middleware_policy("other.example.com"), 0) + .expect("stage"); + let guard = cedar + .commit_configuration(staged, None, || {}) + .expect("commit"); + let decision = engine + .authorize_egress(&middleware_input("api.example.com")) + .expect("authorize"); + + assert_ne!( + guard.captured_generation(), + decision.generation, + "the configuration guard pins the middleware generation" + ); + assert_eq!(engine.decision_generation(&guard), decision.generation); + let startup_guard = engine + .configuration_generation_guard() + .expect("configuration guard"); + assert_eq!( + engine.decision_generation(&startup_guard), + decision.generation + ); +} + /// Existing Cedar guards become stale before credentials change, as the /// YAML reload guarantees. #[test] diff --git a/crates/openshell-policy-runtime-interface/src/runtime.rs b/crates/openshell-policy-runtime-interface/src/runtime.rs index bf40328922..973cd3f4a5 100644 --- a/crates/openshell-policy-runtime-interface/src/runtime.rs +++ b/crates/openshell-policy-runtime-interface/src/runtime.rs @@ -120,6 +120,17 @@ pub trait PolicyBackend: Send + Sync { operation: &mut dyn FnMut(u64), ) -> Result; fn configuration_generation_guard(&self) -> Result; + /// The generation decisions report in `firewall_rule.version` while the + /// configuration `guard` pins is active. Policy load events record it as + /// `active_generation`, so the two join. Call it right after the commit or + /// guard check that produced `guard`. + /// + /// The default suits backends whose configuration guard pins the decision + /// generation. A backend whose guard pins a separate counter, such as a + /// middleware generation, returns its current decision generation instead. + fn decision_generation(&self, guard: &PolicyGenerationGuard) -> u64 { + guard.captured_generation() + } fn binary_identity_required(&self) -> bool; fn websocket_assembly_budget(&self) -> WebSocketAssemblyBudget; fn policy_dns_eligibility_snapshot(&self) -> Result; @@ -133,7 +144,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/mod.rs b/crates/openshell-supervisor-network/src/l7/mod.rs index 9c313e2fcb..d656b12054 100644 --- a/crates/openshell-supervisor-network/src/l7/mod.rs +++ b/crates/openshell-supervisor-network/src/l7/mod.rs @@ -54,14 +54,23 @@ use std::sync::{Arc, Mutex}; use crate::policy_types::EndpointConfig; use crate::policy_types::PolicyGenerationGuard; -/// Records the policies that decided a request. +/// Firewall rule naming the policy that decided a request, or `-` when none or +/// several did. Add the generation with +/// [`openshell_ocsf::FirewallRule::with_policy_generation`] for a policy +/// decision; a rejection made before policy evaluation omits it. +pub(crate) fn request_rule(decision: &L7Decision, rule_type: &str) -> openshell_ocsf::FirewallRule { + openshell_ocsf::FirewallRule::new(decision.rule_name(), rule_type) +} + +/// Records the policies that decided a request. `rule` comes from +/// [`request_rule`]. pub(crate) fn with_request_decision<'a, C>( builder: openshell_ocsf::HttpActivityBuilder<'a, C>, decision: &L7Decision, - engine_type: &str, + rule: openshell_ocsf::FirewallRule, ) -> openshell_ocsf::HttpActivityBuilder<'a, C> { builder - .firewall_rule(decision.rule_name(), engine_type) + .firewall_rule_value(rule) .unmapped("matched_policies", decision.matched_policies.clone()) } diff --git a/crates/openshell-supervisor-network/src/l7/relay.rs b/crates/openshell-supervisor-network/src/l7/relay.rs index 5cba22b5c5..6bb0de9667 100644 --- a/crates/openshell-supervisor-network/src/l7/relay.rs +++ b/crates/openshell-supervisor-network/src/l7/relay.rs @@ -38,7 +38,8 @@ use openshell_core::endpoint_status::{EndpointObservationSender, EndpointResult} use openshell_core::secrets::{self, SecretResolver}; use openshell_ocsf::{ ActionId, ActivityId, DetectionFindingBuilder, DispositionId, Endpoint, FindingInfo, - HttpActivityBuilder, HttpRequest, NetworkActivityBuilder, SeverityId, StatusId, Url as OcsfUrl, + FirewallRule, HttpActivityBuilder, HttpRequest, NetworkActivityBuilder, SeverityId, StatusId, + Url as OcsfUrl, }; #[cfg(test)] use std::collections::BTreeMap; @@ -400,7 +401,7 @@ where &request.action, redacted_target, "deny", - "l7-mcp", + l7_rejection_rule(ctx, "l7-mcp"), &reason, summary.as_deref(), None, @@ -503,7 +504,7 @@ where &request.action, redacted_target, "deny", - "l7-mcp", + l7_rejection_rule(ctx, "l7-mcp"), &reason, summary.as_deref(), None, @@ -1721,14 +1722,16 @@ where }; let Some(config) = select_l7_config_for_path(configs, &route_target) else { let reason = "no L7 endpoint path matched request"; + let no_route = L7Decision::deny(reason, Vec::new()); correlation.record_rejection(403, HttpOutcome::Denied, None); emit_l7_request_log( ctx, &req.action, &route_target, "deny", - "l7", - &L7Decision::deny(reason, Vec::new()), + crate::l7::request_rule(&no_route, "l7") + .with_policy_generation(engine.captured_generation()), + &no_route, None, ); crate::l7::rest::RestProvider::default() @@ -1969,7 +1972,13 @@ where &request_info.action, &redacted_target, decision_str, - engine_type, + // A hard deny rejects the request before policy evaluation. + if force_deny { + crate::l7::request_rule(&decision, engine_type) + } else { + crate::l7::request_rule(&decision, engine_type) + .with_policy_generation(engine.captured_generation()) + }, &decision, protocol_summary.as_deref(), ); @@ -2286,12 +2295,19 @@ pub(crate) fn select_l7_config_for_path<'a>( openshell_core::endpoint_path::select_most_specific(configs, path, |config| &config.path) } +/// Firewall rule naming the connection's policy for an L7 record that no +/// request decision produced, such as a protocol rejection made before policy +/// evaluation. It records no generation. +fn l7_rejection_rule(ctx: &L7EvalContext, rule_type: &str) -> FirewallRule { + FirewallRule::new(&ctx.policy_name, rule_type) +} + fn emit_l7_request_log( ctx: &L7EvalContext, action: &str, redacted_target: &str, decision_str: &str, - engine_type: &str, + rule: FirewallRule, decision: &L7Decision, protocol_summary: Option<&str>, ) { @@ -2300,7 +2316,7 @@ fn emit_l7_request_log( action, redacted_target, decision_str, - engine_type, + rule, &decision.reason, protocol_summary, Some(decision), @@ -2309,13 +2325,16 @@ fn emit_l7_request_log( emit_activity(ctx, decision_str == "deny", "l7_policy"); } +/// `rule` names the policy behind the record and, for a policy decision, the +/// generation that made it. A rejection made before policy evaluation omits +/// the generation. #[allow(clippy::too_many_arguments)] fn build_l7_request_event( ctx: &L7EvalContext, action: &str, redacted_target: &str, decision_str: &str, - engine_type: &str, + rule: FirewallRule, reason: &str, protocol_summary: Option<&str>, decision: Option<&L7Decision>, @@ -2348,8 +2367,8 @@ fn build_l7_request_event( .dst_endpoint(Endpoint::from_domain(&ctx.host, ctx.port)) .message(message); match decision { - Some(decision) => crate::l7::with_request_decision(builder, decision, engine_type), - None => builder.firewall_rule(&ctx.policy_name, engine_type), + Some(decision) => crate::l7::with_request_decision(builder, decision, rule), + None => builder.firewall_rule_value(rule), } .build() } @@ -2875,7 +2894,13 @@ where "L7_REQUEST {decision_str} {} {}:{}{} reason={}", request_info.action, ctx.host, ctx.port, redacted_target, reason, )); - let event = crate::l7::with_request_decision(builder, &decision, "l7").build(); + let event = crate::l7::with_request_decision( + builder, + &decision, + crate::l7::request_rule(&decision, "l7") + .with_policy_generation(engine.captured_generation()), + ) + .build(); correlation.emit(event); } @@ -3179,7 +3204,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, @@ -3460,7 +3485,8 @@ where let event = crate::l7::with_request_decision( builder, &decision, - jsonrpc_engine_type(config.protocol), + crate::l7::request_rule(&decision, jsonrpc_engine_type(config.protocol)) + .with_policy_generation(policy_version), ) .build(); correlation.emit(event); @@ -3844,7 +3870,14 @@ where "GRAPHQL_L7_REQUEST {decision_str} {} {}:{}{} {gql_summary} reason={}", request_info.action, ctx.host, ctx.port, redacted_target, reason, )); - let event = crate::l7::with_request_decision(builder, &decision, "l7-graphql").build(); + let rule = crate::l7::request_rule(&decision, "l7-graphql"); + // A hard deny rejects the request before policy evaluation. + let rule = if force_deny { + rule + } else { + rule.with_policy_generation(engine.captured_generation()) + }; + let event = crate::l7::with_request_decision(builder, &decision, rule).build(); correlation.emit(event); } @@ -4354,6 +4387,7 @@ fn reevaluate_transformed_body( "deny", &decision, correlation, + engine.captured_generation(), ); return Ok(Some(decision.reason)); } @@ -4382,6 +4416,7 @@ fn reevaluate_transformed_body( "audit", &decision, correlation, + engine.captured_generation(), ); return Ok(None); } @@ -4392,6 +4427,7 @@ fn reevaluate_transformed_body( "deny", &decision, correlation, + engine.captured_generation(), ); Ok(Some(decision.reason)) } @@ -4421,6 +4457,7 @@ fn emit_transformed_body_decision( decision_str: &str, decision: &L7Decision, correlation: Option<&RequestCorrelation>, + policy_generation: u64, ) { let (action_id, disposition_id, severity) = match decision_str { "deny" => (ActionId::Denied, DispositionId::Blocked, SeverityId::Medium), @@ -4444,7 +4481,12 @@ fn emit_transformed_body_decision( "L7_REQUEST_TRANSFORMED {decision_str} {} {}:{}{} reason={}", request_info.action, ctx.host, ctx.port, request_info.target, decision.reason )); - let event = crate::l7::with_request_decision(builder, decision, engine_type).build(); + let event = crate::l7::with_request_decision( + builder, + decision, + crate::l7::request_rule(decision, engine_type).with_policy_generation(policy_generation), + ) + .build(); crate::l7::correlation::emit_request_events(correlation, [event]); } @@ -4969,7 +5011,14 @@ mod trace_tests { ..Default::default() }; egress_emit!(build_l7_request_event( - &ctx, "GET", "/", "deny", "l7-rest", "denied", None, None + &ctx, + "GET", + "/", + "deny", + l7_rejection_rule(&ctx, "l7-rest"), + "denied", + None, + None, )); }) .await; @@ -11638,26 +11687,142 @@ network_policies: ..Default::default() }; + let decision = L7Decision::deny("no L7 endpoint path matched request", Vec::new()); let event = build_l7_request_event( &ctx, "GET", "/other", "deny", - "l7", + crate::l7::request_rule(&decision, "l7").with_policy_generation(6), "no L7 endpoint path matched request", None, - Some(&L7Decision::deny( - "no L7 endpoint path matched request", - Vec::new(), - )), + Some(&decision), ); 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:- 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"], "-"); + 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_rejection_rule(&ctx, "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"] == "-" + }) + .unwrap_or_else(|| panic!("expected an L7 denial event, got {events:?}")); + assert_eq!(denial["firewall_rule"]["version"], generation.to_string()); } #[test] @@ -11676,7 +11841,16 @@ network_policies: ..Default::default() }; - let event = build_l7_request_event(&ctx, "GET", "/v1", "allow", "l7", "ok", None, None); + let event = build_l7_request_event( + &ctx, + "GET", + "/v1", + "allow", + l7_rejection_rule(&ctx, "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/relay/correlation_dispatch_tests.rs b/crates/openshell-supervisor-network/src/l7/relay/correlation_dispatch_tests.rs index 6526a42b13..a967a5f1ff 100644 --- a/crates/openshell-supervisor-network/src/l7/relay/correlation_dispatch_tests.rs +++ b/crates/openshell-supervisor-network/src/l7/relay/correlation_dispatch_tests.rs @@ -175,9 +175,18 @@ struct Exchange { forwarded: Vec, } +/// Policy generation the fixtures decide under. Two reloads move it past the +/// initial generation, so a decision that reports a zero default cannot pass. +const FIXTURE_GENERATION: &str = "2"; + fn fixture(data: &str, host: &str, policy_name: &str) -> Fixture { let middleware_engine = Arc::new(OpaEngine::from_strings(POLICY, data).expect("valid test policy")); + for _ in 0..2 { + middleware_engine + .reload(POLICY, data) + .expect("reload test policy"); + } let input = NetworkInput { host: host.into(), port: 8000, @@ -369,13 +378,23 @@ fn assert_control_records<'a>( exchange.events[..expected.len()].iter().collect() } +/// `generation` is the expected `firewall_rule.version`; `None` for a +/// rejection made before policy evaluation, which must omit it. fn assert_policy_record<'a>( exchange: &'a TracedOperation, engine_type: &str, action: &str, path: &str, + generation: Option<&str>, ) -> &'a serde_json::Value { let event = assert_control_records(exchange, &[(engine_type, action)], &[], path)[0]; + assert_eq!( + event["firewall_rule"] + .get("version") + .and_then(|v| v.as_str()), + generation, + "{event}" + ); assert_eq!(event["unmapped"]["http_event_kind"], "decision"); assert!(event.get("status").is_none()); assert!( @@ -550,6 +569,7 @@ async fn inspected_allow_creates_only_the_stages_that_run() { } } let records = assert_control_records(&evidence, &[("l7", "Allowed")], &[], "/item"); + assert_eq!(records[0]["firewall_rule"]["version"], FIXTURE_GENERATION); assert!(records[0].get("status").is_none()); assert!( records[0]["message"] @@ -1184,7 +1204,13 @@ async fn production_single_mcp_allow_correlates_record_and_response_receipt() { .starts_with(b"POST /mcp HTTP/1.1\r\n") ); assert!(exchange.output.response.starts_with(b"HTTP/1.1 200 OK\r\n")); - assert_policy_record(&exchange, "l7-mcp", "Allowed", "/mcp"); + assert_policy_record( + &exchange, + "l7-mcp", + "Allowed", + "/mcp", + Some(FIXTURE_GENERATION), + ); } #[tokio::test] @@ -1212,7 +1238,8 @@ async fn production_single_mcp_invalid_version_correlates_denial_and_receipt() { String::from_utf8_lossy(&exchange.output.response) .contains("unsupported_mcp_protocol_version") ); - assert_policy_record(&exchange, "l7-mcp", "Denied", "/mcp"); + // A protocol version rejection happens before policy evaluation. + assert_policy_record(&exchange, "l7-mcp", "Denied", "/mcp", None); } #[tokio::test] @@ -1236,7 +1263,13 @@ async fn production_single_mcp_policy_deny_correlates_record_and_receipt() { .response .starts_with(b"HTTP/1.1 403 Forbidden\r\n") ); - let event = assert_policy_record(&exchange, "l7-mcp", "Denied", "/mcp"); + let event = assert_policy_record( + &exchange, + "l7-mcp", + "Denied", + "/mcp", + Some(FIXTURE_GENERATION), + ); assert!( event["message"] .as_str() @@ -1282,5 +1315,11 @@ network_policies: .starts_with(b"POST /graphql HTTP/1.1\r\n") ); assert!(exchange.output.response.starts_with(b"HTTP/1.1 200 OK\r\n")); - assert_policy_record(&exchange, "l7-graphql", "Allowed", "/graphql"); + assert_policy_record( + &exchange, + "l7-graphql", + "Allowed", + "/graphql", + Some(FIXTURE_GENERATION), + ); } diff --git a/crates/openshell-supervisor-network/src/l7/websocket.rs b/crates/openshell-supervisor-network/src/l7/websocket.rs index 4adbc2d10e..9fe7f46e83 100644 --- a/crates/openshell-supervisor-network/src/l7/websocket.rs +++ b/crates/openshell-supervisor-network/src/l7/websocket.rs @@ -16,7 +16,8 @@ use miette::{IntoDiagnostic, Result, miette}; use openshell_core::provider_credentials::ProviderCredentialState; use openshell_core::secrets::{SecretResolver, contains_reserved_credential_marker}; use openshell_ocsf::{ - ActionId, ActivityId, DispositionId, Endpoint, NetworkActivityBuilder, SeverityId, StatusId, + ActionId, ActivityId, DispositionId, Endpoint, FirewallRule, NetworkActivityBuilder, + SeverityId, StatusId, }; use std::collections::HashMap; use std::future::Future; @@ -1392,7 +1393,8 @@ fn inspect_websocket_text_message( emit_websocket_l7_event( host, port, - policy_name, + websocket_rule(policy_name, Some(&l7_decision)) + .with_policy_generation(inspector.engine.captured_generation()), Some(&l7_decision), &request_info, decision, @@ -1427,7 +1429,7 @@ fn inspect_graphql_websocket_message( emit_websocket_l7_event( host, port, - policy_name, + websocket_rule(policy_name, None), None, &request_info, "allow", @@ -1469,7 +1471,13 @@ fn inspect_graphql_websocket_message( emit_websocket_l7_event( host, port, - policy_name, + // A parse error rejects the message before policy evaluation. + if force_deny { + websocket_rule(policy_name, Some(&l7_decision)) + } else { + websocket_rule(policy_name, Some(&l7_decision)) + .with_policy_generation(inspector.engine.captured_generation()) + }, Some(&l7_decision), &request_info, decision, @@ -2048,22 +2056,31 @@ fn rewrite_event_message(host: &str, port: u16, replacements: usize) -> String { ) } +/// Firewall rule for a WebSocket message event. It names the policy that +/// decided the message, or `-` when none or several did; without a decision it +/// names the connection's policy, or `-` when that is unnamed. Add the +/// generation with [`FirewallRule::with_policy_generation`] for a policy +/// decision; a rejection made before policy evaluation omits it. +fn websocket_rule(policy_name: &str, l7_decision: Option<&L7Decision>) -> FirewallRule { + let name = match l7_decision { + Some(l7_decision) => l7_decision.rule_name(), + None if policy_name.is_empty() => "-", + None => policy_name, + }; + FirewallRule::new(name, "l7-websocket") +} + #[allow(clippy::too_many_arguments)] fn emit_websocket_l7_event( host: &str, port: u16, - policy_name: &str, + rule: FirewallRule, l7_decision: Option<&L7Decision>, request_info: &L7RequestInfo, decision: &str, reason: &str, graphql: Option<&crate::l7::graphql::GraphqlRequestInfo>, ) { - let policy_name = match l7_decision { - Some(l7_decision) => l7_decision.rule_name(), - None if policy_name.is_empty() => "-", - None => policy_name, - }; let (action_id, disposition_id, severity) = match decision { "deny" => (ActionId::Denied, DispositionId::Blocked, SeverityId::Medium), "allow" | "audit" => ( @@ -2081,18 +2098,18 @@ 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") - .message(format!( - "WEBSOCKET_L7_REQUEST {decision} {} {host}:{port}{}{} reason={reason}", - request_info.action, request_info.target, summary - )); + .firewall_rule_value(rule); + let event = builder.message(format!( + "WEBSOCKET_L7_REQUEST {decision} {} {host}:{port}{}{} reason={reason}", + request_info.action, request_info.target, summary + )); let event = match l7_decision { Some(l7_decision) => event .unmapped("matched_policies", l7_decision.matched_policies.clone()) diff --git a/crates/openshell-supervisor-network/src/opa.rs b/crates/openshell-supervisor-network/src/opa.rs index 7b3610c4b0..c065d98d26 100644 --- a/crates/openshell-supervisor-network/src/opa.rs +++ b/crates/openshell-supervisor-network/src/opa.rs @@ -1141,9 +1141,10 @@ impl OpaEngine { Ok(Some(operation(current_generation))) } - /// 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<()> { + /// Replace the complete middleware service registry, invalidate existing + /// tunnels so subsequent requests use the new service set, and return the + /// policy generation the replacement 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 @@ -1159,7 +1160,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 @@ -8391,6 +8392,17 @@ network_policies: assert!(cloned.evaluate_request(&context, &request).unwrap().allowed); } + #[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 94c6ac02bd..2f757a8b48 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 93c8e48bc7..ece7c1a682 100644 --- a/crates/openshell-supervisor-network/src/proxy.rs +++ b/crates/openshell-supervisor-network/src/proxy.rs @@ -143,8 +143,8 @@ use self::destination::{ build_validation_plan, validate_destination, }; use self::egress::{ - EgressDecision, EgressIntent, EndpointDecision, IdentityUnavailableReason, L7ConfigSnapshot, - L7RouteSnapshot, ProcessIdentityEvidence, + DecisionProvenance, EgressDecision, EgressIntent, EndpointDecision, IdentityUnavailableReason, + L7ConfigSnapshot, L7RouteSnapshot, ProcessIdentityEvidence, }; const MAX_HEADER_BYTES: usize = 8192; @@ -755,6 +755,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; @@ -779,6 +780,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; @@ -808,6 +810,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; @@ -846,6 +849,7 @@ async fn preauthorize_transparent_open( &binary_identity, reason, status_detail, + Some(decision.provenance()), ); if supplied_authorization.denial.is_none() && !is_always_blocked_ip(destination.ip()) @@ -874,6 +878,7 @@ async fn preauthorize_transparent_open( &binary_identity, &denial.reason, "transparent_tcp_destination_denied", + Some(decision.provenance()), ); let _ = completion.send(TcpOpenDecision::Denied(TcpOpenDenial::InvalidDestination)); return None; @@ -915,6 +920,7 @@ async fn preauthorize_transparent_open( &binary_identity, &reason, status_detail, + Some(decision.provenance()), ); let _ = completion.send(TcpOpenDecision::Denied(TcpOpenDenial::InvalidDestination)); @@ -949,6 +955,7 @@ async fn preauthorize_transparent_open( &binary_identity, &denial.reason, "transparent_tcp_destination_denied", + Some(decision.provenance()), ); let _ = completion.send(TcpOpenDecision::Denied(TcpOpenDenial::InvalidDestination)); return None; @@ -1134,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, ) { egress_emit!(build_staged_transparent_denial_event( destination, @@ -1147,6 +1157,7 @@ fn emit_staged_transparent_denial( identity, reason, status_detail, + decided_by, )); } @@ -1156,6 +1167,7 @@ fn build_staged_transparent_denial_event( identity: &Result, reason: &str, status_detail: &'static str, + decided_by: Option, ) -> openshell_ocsf::OcsfEvent { let (binary, ancestors, cmdline, process) = identity.as_ref().map_or_else( |_| ("-".to_string(), "-".to_string(), "-".to_string(), None), @@ -1179,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) @@ -1188,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(provenance) = decided_by { + builder = builder.firewall_rule_value(provenance.rule("-")); + } + builder .message(format!("Transparent TCP denied before relay: {reason}")) .status_detail(status_detail) .build() @@ -1435,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(()); } @@ -1479,6 +1501,7 @@ async fn handle_transparent_tcp_connection( original, Some(&host), MappingLookupError::EndpointMismatch, + Some(decision.provenance()), ); emit_activity(&activity_tx, true, "transparent_tcp_mapping"); return Ok(()); @@ -1502,12 +1525,19 @@ async fn handle_transparent_tcp_connection( original, Some(&host), MappingLookupError::InvalidMapping, + Some(decision.provenance()), ); 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.provenance()), + ); emit_activity(&activity_tx, true, "transparent_tcp_mapping"); return Ok(()); } @@ -1607,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))] @@ -1664,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) @@ -1772,7 +1813,28 @@ fn emit_transparent_mapping_denial( original: SocketAddr, mapped_host: Option<&str>, error: MappingLookupError, + decided_by: Option, ) { + 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, +) -> openshell_ocsf::OcsfEvent { let detail = match error { MappingLookupError::Missing => "transparent_tcp_mapping_missing", MappingLookupError::Expired => "transparent_tcp_mapping_expired", @@ -1781,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(provenance) = decided_by { + builder = builder.firewall_rule_value(provenance.rule("-")); + } + builder + .message(format!("Transparent TCP denied: {error}")) + .status_detail(detail) + .build() } #[cfg(target_os = "linux")] @@ -1825,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_value(decision.provenance().rule("-")) .message(format!("Transparent TCP denied {host}:{port}")) .status_detail(status_detail) .build() @@ -2238,8 +2302,8 @@ fn build_connect_allow_ocsf_event( port: u16, actor: &Process, policy: &str, + provenance: DecisionProvenance, l7_inspection: bool, - engine: &str, ) -> openshell_ocsf::OcsfEvent { let connect_msg = if l7_inspection { "CONNECT_L7" @@ -2255,7 +2319,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_value(provenance.rule(policy)) .message(format!("{connect_msg} allowed {host}:{port}")) .build() } @@ -2269,7 +2333,7 @@ fn build_forward_allow_ocsf_event( path: &str, actor: &Process, policy: &str, - engine: &str, + provenance: DecisionProvenance, ) -> openshell_ocsf::OcsfEvent { HttpActivityBuilder::new(openshell_ocsf::ctx::ctx()) .activity(ActivityId::for_http_method(method)) @@ -2284,7 +2348,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_value(provenance.rule(policy)) .message(format!("FORWARD allowed {method} {host}:{port}{path}")) .build() } @@ -2447,7 +2511,7 @@ fn build_forward_policy_deny_ocsf_event( path: &str, actor: &Process, reason: &str, - engine: &str, + provenance: DecisionProvenance, ) -> openshell_ocsf::OcsfEvent { HttpActivityBuilder::new(openshell_ocsf::ctx::ctx()) .activity(ActivityId::Other) @@ -2462,7 +2526,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_value(provenance.rule("-")) .message(format!("FORWARD denied {method} {host}:{port}{path}")) .status_detail(reason) .build() @@ -2520,6 +2584,7 @@ fn build_connect_destination_deny_ocsf_event( host: &str, port: u16, actor: &Process, + policy_generation: u64, ) -> openshell_ocsf::OcsfEvent { let detail = destination_denial_detail(denial.kind); let message = if denial.kind == DestinationDenialKind::InternalAddress { @@ -2537,7 +2602,7 @@ fn build_connect_destination_deny_ocsf_event( .dst_endpoint(Endpoint::from_domain(host, port)) .src_endpoint_addr(peer_addr.ip(), peer_addr.port()) .actor_process(actor.clone()) - .firewall_rule("-", "ssrf") + .firewall_rule_at_generation("-", "ssrf", policy_generation) .message(message) .status_detail(&denial.reason) .build() @@ -2553,6 +2618,7 @@ fn build_forward_destination_deny_ocsf_event( path: &str, actor: &Process, policy: &str, + policy_generation: u64, ) -> openshell_ocsf::OcsfEvent { let detail = destination_denial_detail(denial.kind); let log_detail = if denial.kind == DestinationDenialKind::InternalAddress { @@ -2574,7 +2640,7 @@ fn build_forward_destination_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(policy, "ssrf") + .firewall_rule_at_generation(policy, "ssrf", policy_generation) .message(format!("FORWARD blocked: {log_detail} for {host}:{port}")) .status_detail(&denial.reason) .build() @@ -2598,7 +2664,12 @@ where { let detail = destination_denial_detail(denial.kind); egress_emit!(build_connect_destination_deny_ocsf_event( - denial, peer_addr, host, port, actor, + denial, + peer_addr, + host, + port, + actor, + decision.policy_generation, )); emit_denial( @@ -2650,7 +2721,15 @@ where { let detail = destination_denial_detail(denial.kind); let event = build_forward_destination_deny_ocsf_event( - denial, peer_addr, method, host, port, path, actor, policy, + denial, + peer_addr, + method, + host, + port, + path, + actor, + policy, + decision.policy_generation, ); if let Some(correlation) = correlation { correlation.record_rejection(403, HttpOutcome::Denied, None); @@ -3101,7 +3180,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_value(decision.provenance().rule("-")) .message(format!("CONNECT denied {host_lc}:{port}")) .status_detail(&deny_reason) .build(); @@ -3136,8 +3215,15 @@ 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.provenance(), + error, + ) + .await?; return Ok(()); } }; @@ -3345,8 +3431,15 @@ 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.provenance(), + error, + ) + .await?; return Ok(()); } @@ -3405,6 +3498,7 @@ async fn handle_mediated_connection( &host_lc, port, activity_tx.as_ref(), + decision.provenance(), miette::miette!( "policy changed while CONNECT was dialing upstream \ [captured_generation:{} current_generation:{}]", @@ -3426,8 +3520,15 @@ 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.provenance(), + error, + ) + .await?; return Ok(()); } @@ -3446,8 +3547,8 @@ async fn handle_mediated_connection( port, &actor, policy_str, + decision.provenance(), should_inspect_l7, - decision.engine, )); emit_connect_activity_if_l4_only(&activity_tx, l7_route); @@ -3465,7 +3566,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(()); } @@ -3676,7 +3784,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(()) @@ -4246,19 +4361,39 @@ 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()) +/// `provenance` carries the last generation that authorized the connection. +/// The L7 relay's stale-tunnel close event and the established relay's close +/// event record the same value: an unrelated reload that re-validated the +/// connection moves it forward. +fn emit_l7_tunnel_close_after_policy_change( + host: &str, + port: u16, + provenance: DecisionProvenance, + error: miette::Report, +) { + egress_emit!(build_l7_tunnel_close_after_policy_change_event( + host, port, provenance, &error, + )); +} + +fn build_l7_tunnel_close_after_policy_change_event( + host: &str, + port: u16, + provenance: DecisionProvenance, + 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_value(provenance.rule("-")) .message(format!( "L7 tunnel closed before inspection because policy changed: {error}" )) - .build(); - egress_emit!(event); + .build() } async fn reject_stale_connect_policy( @@ -4266,6 +4401,7 @@ async fn reject_stale_connect_policy( host: &str, port: u16, activity_tx: Option<&ActivitySender>, + provenance: DecisionProvenance, error: miette::Report, ) -> Result<()> where @@ -4277,7 +4413,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, provenance, error); emit_activity_simple(activity_tx, true, "policy_stale"); respond( client, @@ -5998,7 +6134,7 @@ async fn handle_forward_proxy_inner( &telemetry_path, &actor, reason, - decision.engine, + decision.provenance(), )], Some(&connect_span), ); @@ -6056,7 +6192,7 @@ 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.provenance(), e); emit_activity_simple(activity_tx, true, "policy_stale"); respond( client, @@ -6206,6 +6342,7 @@ async fn handle_forward_proxy_inner( emit_l7_tunnel_close_after_policy_change( &host_lc, port, + decision.provenance(), miette::miette!( "policy changed before forward L7 evaluation [expected_generation:{} current_generation:{}]", forward_generation_guard.captured_generation(), @@ -6244,7 +6381,7 @@ 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.provenance(), e); emit_activity_simple(activity_tx, true, "policy_stale"); correlation.record_rejection(403, HttpOutcome::Denied, None); respond( @@ -6643,8 +6780,13 @@ async fn handle_forward_proxy_inner( .src_endpoint(Endpoint::from_ip(workload_addr.ip(), workload_addr.port())) .actor_process(actor.clone()) .message(log_message); - let event = - crate::l7::with_request_decision(builder, &l7_decision, engine_type).build(); + let event = crate::l7::with_request_decision( + builder, + &l7_decision, + crate::l7::request_rule(&l7_decision, engine_type) + .with_policy_generation(tunnel_engine.captured_generation()), + ) + .build(); emit_forward_l7_decision(event, evaluation_error, &connect_span, request_correlation); } @@ -6779,7 +6921,7 @@ 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.provenance(), e); emit_activity_simple(activity_tx, true, "policy_stale"); correlation.record_rejection(403, HttpOutcome::Denied, None); respond( @@ -6802,6 +6944,7 @@ async fn handle_forward_proxy_inner( emit_l7_tunnel_close_after_policy_change( &host_lc, port, + decision.provenance(), miette::miette!( "policy changed before forward middleware evaluation [expected_generation:{middleware_expected_generation} current_generation:{generation}]", ), @@ -7250,7 +7393,7 @@ 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.provenance(), e); if let Some(session) = middleware_session.take() { session .end(openshell_core::proto::MiddlewareSessionEndReason::PolicyReload) @@ -7346,7 +7489,7 @@ 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.provenance(), e); if let Some(session) = middleware_session.take() { session .end(openshell_core::proto::MiddlewareSessionEndReason::PolicyReload) @@ -7494,7 +7637,7 @@ async fn handle_forward_proxy_inner( &telemetry_path, &actor, policy_str, - network_engine.label(), + decision.provenance(), )); emit_forward_success_activity(activity_tx, l7_activity_pending); @@ -8050,8 +8193,8 @@ process: 443, &decision.actor_process(), "api", + decision.provenance(), false, - "opa", ); let json = serde_json::to_value(&event).unwrap(); @@ -10122,6 +10265,62 @@ 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, + DecisionProvenance::new("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(DecisionProvenance::new("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); @@ -10131,18 +10330,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(DecisionProvenance::new("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(), @@ -10150,11 +10352,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] @@ -13303,11 +13508,12 @@ network_policies: &Process::from_bypass("/usr/bin/curl", "42", "/usr/bin/bash") .with_cmd_line("curl http://api.example.com/v1/models"), reason, - "opa", + DecisionProvenance::new("opa", 9), ); 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"); } @@ -13379,6 +13585,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"], @@ -13496,7 +13703,7 @@ network_policies: &path, &Process::from_bypass("/usr/bin/curl", "42", "/usr/bin/bash").with_cmd_line("curl"), "allow_api", - "opa", + DecisionProvenance::new("opa", 3), ) .to_json() .unwrap(); @@ -13508,11 +13715,12 @@ network_policies: &path, &Process::from_bypass("/usr/bin/curl", "42", "/usr/bin/bash").with_cmd_line("curl"), "policy denied", - "opa", + DecisionProvenance::new("opa", 3), ) .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}"); @@ -13532,7 +13740,7 @@ network_policies: &forward_telemetry_path(target), &Process::from_bypass("/usr/bin/curl", "42", "/usr/bin/bash").with_cmd_line("curl"), "allow_api", - "opa", + DecisionProvenance::new("opa", 3), ) .to_json() .unwrap(); diff --git a/crates/openshell-supervisor-network/src/proxy/egress.rs b/crates/openshell-supervisor-network/src/proxy/egress.rs index 2094953b52..6f5258378d 100644 --- a/crates/openshell-supervisor-network/src/proxy/egress.rs +++ b/crates/openshell-supervisor-network/src/proxy/egress.rs @@ -14,7 +14,7 @@ use super::destination::DestinationValidationPlan; use crate::policy_types::NetworkAction; use openshell_isolation_interface::contract::ProcessInstance; -use openshell_ocsf::Process; +use openshell_ocsf::{FirewallRule, Process}; use std::path::PathBuf; #[derive(Debug, Clone)] @@ -183,7 +183,31 @@ pub(super) struct EgressDecision { pub(super) cmdline_paths: Vec, } +/// The engine and policy generation behind a decision, recorded on its OCSF +/// events as `firewall_rule.type` and `firewall_rule.version`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) struct DecisionProvenance { + pub(super) engine: &'static str, + pub(super) generation: u64, +} + +impl DecisionProvenance { + pub(super) const fn new(engine: &'static str, generation: u64) -> Self { + Self { engine, generation } + } + + /// The firewall rule naming `policy`, decided under this provenance. + pub(super) fn rule(self, policy: &str) -> FirewallRule { + FirewallRule::new(policy, self.engine).with_policy_generation(self.generation) + } +} + impl EgressDecision { + /// The engine and generation that made this decision. + pub(super) fn provenance(&self) -> DecisionProvenance { + DecisionProvenance::new(self.engine, self.policy_generation) + } + /// The policy input this decision was evaluated with. /// /// Every adapter builds its OPA input from the intent destination and the diff --git a/crates/openshell-supervisor-network/src/proxy/relay.rs b/crates/openshell-supervisor-network/src/proxy/relay.rs index 2a6eeab907..85af4fc950 100644 --- a/crates/openshell-supervisor-network/src/proxy/relay.rs +++ b/crates/openshell-supervisor-network/src/proxy/relay.rs @@ -3,7 +3,9 @@ //! Shared relay primitives for authorized explicit-proxy egress. -use super::{EgressDecision, L7RouteSnapshot, emit_l7_tunnel_close_after_policy_change}; +use super::{ + DecisionProvenance, EgressDecision, L7RouteSnapshot, emit_l7_tunnel_close_after_policy_change, +}; use crate::l7::relay::L7EvalContext; use crate::policy_engine::{PassthroughMiddleware, PolicyEngine, TunnelPolicyEngine}; use crate::policy_types::{NetworkAction, PolicyGenerationGuard}; @@ -38,6 +40,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 +218,7 @@ pub(super) fn prepare_http_relay<'a>( emit_l7_tunnel_close_after_policy_change( &decision.intent.destination.host, decision.intent.destination.port, + decision.provenance(), error, ); }; @@ -250,6 +255,7 @@ pub(super) fn prepare_http_relay<'a>( emit_l7_tunnel_close_after_policy_change( &decision.intent.destination.host, decision.intent.destination.port, + decision.provenance(), 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,7 @@ pub(super) fn prepare_raw_relay( emit_l7_tunnel_close_after_policy_change( &decision.intent.destination.host, decision.intent.destination.port, + decision.provenance(), error, ); None @@ -341,7 +352,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 +365,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 +380,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: &'static 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. @@ -391,9 +406,9 @@ pub async fn relay_inspected_http_stream_for_test( upstream: &mut U, configs: Vec, 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, + // Supplies the engine label for the stale-relay close event; an inspected + // tunnel still selects middleware from `evaluator`'s snapshot. + engine: &PolicyEngine, request: &L7EvalContext, ) -> Result<()> where @@ -409,6 +424,7 @@ where configs, evaluator: Box::new(evaluator), }, + engine: engine.label(), }, ) .await @@ -420,6 +436,7 @@ pub(super) async fn relay_tcp( upstream: &mut U, generation_guard: &PolicyGenerationGuard, request: &L7EvalContext, + engine: &'static str, ) -> Result<()> where C: AsyncRead + AsyncWrite + Unpin, @@ -430,16 +447,23 @@ 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) { +/// The relay's guard carries the last generation that authorized it; an +/// unrelated reload that re-validated the relay moves it forward. +fn emit_stale_relay_close( + request: &L7EvalContext, + engine: &'static str, + guard: &PolicyGenerationGuard, +) { emit_l7_tunnel_close_after_policy_change( &request.host, request.port, + DecisionProvenance::new(engine, guard.captured_generation()), miette::miette!( "policy generation is stale [captured_generation:{} current_generation:{}]", guard.captured_generation(), @@ -713,7 +737,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 +940,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; @@ -955,16 +993,27 @@ network_policies: let decision = authorized_decision(&engine); let guard = prepare_raw_relay(None, &PolicyEngine::from(engine.clone()), &decision) .expect("current decision pins"); + // The stale-relay close event records the guard's captured generation. + let pin = guard.clone(); let request = request_context(); 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 .reload(POLICY_REGO, CURL_EXAMPLE_AND_OTHER_POLICY) .unwrap(); + let revalidated_generation = engine.current_generation(); + assert!(revalidated_generation > decision.policy_generation); client_peer.write_all(b"ping").await.unwrap(); let mut received = [0u8; 4]; tokio::time::timeout( @@ -975,6 +1024,9 @@ network_policies: .expect("bytes must keep flowing after the reload") .unwrap(); assert_eq!(&received, b"ping"); + // The unrelated reload re-validated the relay, so a later close + // reports that generation: the last one that authorized it. + assert_eq!(pin.captured_generation(), revalidated_generation); // The same relay still closes once its own endpoint is revoked. engine.reload(POLICY_REGO, EMPTY_POLICY_DATA).unwrap(); diff --git a/crates/openshell-supervisor-network/src/proxy/tests/compatibility.rs b/crates/openshell-supervisor-network/src/proxy/tests/compatibility.rs index a06cf90b05..454b18c5cb 100644 --- a/crates/openshell-supervisor-network/src/proxy/tests/compatibility.rs +++ b/crates/openshell-supervisor-network/src/proxy/tests/compatibility.rs @@ -189,6 +189,7 @@ fn representative_adapter_denials_preserve_ocsf_fields() { "target.example", 8443, &Process::from_bypass("/usr/bin/curl", "42", "/usr/bin/sh").with_cmd_line("curl --proxy"), + 7, )) .unwrap(); assert_eq!(connect["class_name"], "Network Activity"); @@ -203,6 +204,7 @@ fn representative_adapter_denials_preserve_ocsf_fields() { assert_eq!(connect["actor"]["process"]["pid"], 42); assert_eq!(connect["firewall_rule"]["name"], "-"); assert_eq!(connect["firewall_rule"]["type"], "ssrf"); + assert_eq!(connect["firewall_rule"]["version"], "7"); assert_eq!( connect["message"], "CONNECT blocked: internal address target.example:8443" @@ -218,6 +220,7 @@ fn representative_adapter_denials_preserve_ocsf_fields() { "/v1/items", &Process::from_bypass("/usr/bin/curl", "42", "/usr/bin/sh").with_cmd_line("curl --proxy"), "proxy_compatibility", + 7, )) .unwrap(); assert_eq!(forward["class_name"], "HTTP Activity"); @@ -231,6 +234,7 @@ fn representative_adapter_denials_preserve_ocsf_fields() { assert_eq!(forward["http_request"]["http_method"], "POST"); assert_eq!(forward["firewall_rule"]["name"], "proxy_compatibility"); assert_eq!(forward["firewall_rule"]["type"], "ssrf"); + assert_eq!(forward["firewall_rule"]["version"], "7"); assert_eq!( forward["message"], "FORWARD blocked: internal IP without allowed_ips for target.example:8080" @@ -247,8 +251,8 @@ 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", + DecisionProvenance::new("opa", 5), true, - "opa", )) .unwrap(); assert_eq!(connect["class_name"], "Network Activity"); @@ -262,6 +266,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,7 +277,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", - "opa", + DecisionProvenance::new("opa", 5), )) .unwrap(); assert_eq!(forward["class_name"], "HTTP Activity"); @@ -286,6 +291,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-network/src/proxy/tests/request_trace.rs b/crates/openshell-supervisor-network/src/proxy/tests/request_trace.rs index 52894778dd..b80cb55f10 100644 --- a/crates/openshell-supervisor-network/src/proxy/tests/request_trace.rs +++ b/crates/openshell-supervisor-network/src/proxy/tests/request_trace.rs @@ -394,6 +394,8 @@ network_policies: ) .unwrap(), ); + // Move past the initial generation so a zero default cannot pass. + let policy_generation = engine.publish_credential_change().unwrap().to_string(); let identity = Ok(ContractBinaryIdentity { executable: ContractExecutableIdentity { path: executable_path("/usr/bin/python3"), @@ -541,6 +543,7 @@ network_policies: .starts_with(&format!("FORWARD_L7 {decision} GET ")) ); assert_eq!(record["firewall_rule"]["type"], "l7"); + assert_eq!(record["firewall_rule"]["version"], policy_generation); assert!(record.get("status_id").is_none()); assert!(record.get("status_detail").is_none()); for (index, control) in records.iter().enumerate() { @@ -869,6 +872,8 @@ network_policies: ) .unwrap(), ); + // Move past the initial generation so a zero default cannot pass. + let policy_generation = engine.publish_credential_change().unwrap().to_string(); let capture = RequestTracing::new(Some(Sampler::AlwaysOn)); let subscriber = capture .subscriber() @@ -1066,6 +1071,7 @@ network_policies: }) ); assert_eq!(records[3]["firewall_rule"]["type"], "l7-websocket"); + assert_eq!(records[3]["firewall_rule"]["version"], policy_generation); assert_eq!(records[3]["action_id"], if allow_frame { 1 } else { 2 }); for record in &records[3..] { assert!(record["metadata"].get("correlation_uid").is_none()); diff --git a/crates/openshell-supervisor/src/config_runtime.rs b/crates/openshell-supervisor/src/config_runtime.rs index 46c4f8751b..7dbe177a99 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 = ctx.engine.decision_generation(&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, + ctx.engine.decision_generation(generation), + ), ); debug!( config_revision = runtime.config_revision, diff --git a/crates/openshell-supervisor/src/lib.rs b/crates/openshell-supervisor/src/lib.rs index da9258656e..0f49c5e23e 100644 --- a/crates/openshell-supervisor/src/lib.rs +++ b/crates/openshell-supervisor/src/lib.rs @@ -3908,18 +3908,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, }), } } @@ -4310,36 +4319,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) { @@ -4496,7 +4512,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 @@ -4542,6 +4558,26 @@ struct MiddlewareRegistryReconciliation<'a> { status: &'a mut MiddlewareRegistryStatus, } +/// Build the CONFIG event recorded when a new middleware registry is +/// installed. It records the policy generation in force afterwards; engines +/// that advance the generation on a registry swap (OPA) record the generation +/// the swap activated, and Cedar records its unchanged generation. +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, @@ -4558,7 +4594,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, @@ -4569,21 +4605,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 @@ -8238,6 +8263,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 7f5b21e8e3..cf9e57ea85 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, @@ -425,6 +431,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 provider credentials are reinstalled, when the supervisor middleware registry is replaced (the default OPA engine only; the experimental Cedar engine keeps its generation), 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 that carry `unmapped.policy_hash` and select the one with the greatest `active_generation` that is less than or equal to the decision's `firewall_rule.version`. Compare generations, not line order. `firewall_rule.version` is a string, as OCSF types it, and `active_generation` is a number, so convert the version to a number before comparing (for example, `tonumber` in jq). Compared as strings, `"10"` sorts before `"9"`. 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. A decision whose version is at or above a `fail_closed` event's `active_generation`, and below the next load event's, was a quarantine denial, not a decision of the policy found by the join. + +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. Rejections made before policy evaluation leave `firewall_rule.version` unset. These include malformed JSON-RPC, GraphQL, and GraphQL WebSocket requests, MCP protocol version rejections, and credential binding failures. 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 last generation that authorized them. An established connection that a later reload re-validated carries that later generation. + ## OCSF Event Classes in JSON The `class_uid` field identifies the event type: diff --git a/docs/observability/overview.mdx b/docs/observability/overview.mdx index d6b5cfe6bd..5c36fb64a5 100644 --- a/docs/observability/overview.mdx +++ b/docs/observability/overview.mdx @@ -89,7 +89,7 @@ OCSF events record security-relevant activity, such as network and HTTP policy d Shorthand logs are always on. Each event appears as a one-line summary in the gateway console, in the sandbox log stream that `openshell logs` and the TUI read, and in the supervisor's log file. For example, this policy denial is the event a sandbox produces when `curl https://github.com` runs without a network policy that allows `github.com`: ```text -[1791996125.789] [sandbox] [OCSF ] [ocsf] NET:OPEN [MED] DENIED /usr/bin/curl(2187) -> github.com:443 [reason:transparent_tcp_policy_denied] +[1791996125.789] [sandbox] [OCSF ] [ocsf] NET:OPEN [MED] DENIED /usr/bin/curl(2187) -> github.com:443 [policy:- engine:opa] [reason:transparent_tcp_policy_denied] ``` To read the format, refer to [Sandbox Logging](/observability/logging). To find logs for each compute driver, refer to [Accessing Logs](/observability/accessing-logs).