From f2eaa579063c891ef90903c279eb31784bed303e Mon Sep 17 00:00:00 2001 From: Kris Hicks Date: Fri, 4 Dec 2026 09:43:31 -0800 Subject: [PATCH] fix(observability): name the policy that decided each inspected request An inspected request's HTTP Activity record named the policy that allowed its TCP connection, even when a different policy allowed or denied the request itself. Requests that no policy allowed also named the connection's policy. Cedar connection records named whichever permitting policy Cedar happened to list first. Request evaluation now returns the policies that decided it: Rego names the entries that allowed the request or whose deny rules matched it, and Cedar passes through its determining permits or forbids. Each request decision record names its sole deciding policy, or - when none or several decided it, listing several in unmapped.matched_policies. Connection records keep the connection's policy, and Cedar now picks the least name, as Rego does. Allow and deny behavior is unchanged. Closes #5922 Signed-off-by: Kris Hicks --- .../openshell-policy-cedar-runtime/Cargo.toml | 1 + .../src/backend.rs | 4 +- .../src/cedar_only/l7.rs | 68 +- .../src/cedar_only/mod.rs | 2 +- .../src/cedar_only/tests.rs | 292 +++++++- .../src/l7/mod.rs | 48 +- .../src/runtime.rs | 6 +- .../data/sandbox-policy.rego | 48 +- .../src/l7/graphql.rs | 7 +- .../src/l7/mod.rs | 11 + .../src/l7/relay.rs | 655 ++++++++++++++---- .../l7/relay/token_grant_ownership_tests.rs | 2 +- .../src/l7/websocket.rs | 153 +++- .../openshell-supervisor-network/src/opa.rs | 152 +++- .../src/policy_engine.rs | 4 +- .../openshell-supervisor-network/src/proxy.rs | 24 +- .../src/proxy/tests/request_attribution.rs | 156 +++++ .../src/proxy/tests/token_grants.rs | 2 +- crates/openshell-supervisor/src/lib.rs | 4 +- docs/how-it-works/policies/cedar.mdx | 2 +- docs/observability/logging.mdx | 4 +- docs/observability/ocsf-json-export.mdx | 8 + .../src/cedar_integration.rs | 2 +- .../policy-conformance/src/conformance/mod.rs | 10 +- 24 files changed, 1415 insertions(+), 250 deletions(-) create mode 100644 crates/openshell-supervisor-network/src/proxy/tests/request_attribution.rs diff --git a/crates/openshell-policy-cedar-runtime/Cargo.toml b/crates/openshell-policy-cedar-runtime/Cargo.toml index 10d13093d0..2093d74315 100644 --- a/crates/openshell-policy-cedar-runtime/Cargo.toml +++ b/crates/openshell-policy-cedar-runtime/Cargo.toml @@ -29,4 +29,5 @@ ipnet = "2" workspace = true [dev-dependencies] +openshell-ocsf = { path = "../openshell-ocsf", features = ["test-support"] } tempfile = "3" diff --git a/crates/openshell-policy-cedar-runtime/src/backend.rs b/crates/openshell-policy-cedar-runtime/src/backend.rs index dd80adb051..fed0b9738c 100644 --- a/crates/openshell-policy-cedar-runtime/src/backend.rs +++ b/crates/openshell-policy-cedar-runtime/src/backend.rs @@ -11,8 +11,8 @@ use openshell_policy_runtime_interface::{ use openshell_supervisor_middleware::{ChainEntry, ChainRunner, MiddlewareRegistry}; use crate::cedar_only::{CedarL7TunnelEngine, CedarOnlyEngine, StagedCedarPolicy}; -use crate::l7::L7RequestInfo; use crate::l7::websocket::WebSocketAssemblyBudget; +use crate::l7::{L7Decision, L7RequestInfo}; use crate::network_middleware::{ActiveMiddleware, MiddlewareConfigs}; use crate::policy_types::{ EgressAuthorization, EndpointConfig, NetworkInput, PolicyDnsEligibilitySnapshot, @@ -157,7 +157,7 @@ impl RequestPolicy for CedarRequestPolicy { &self, ctx: &L7PolicyContext, request: &L7RequestInfo, - ) -> Result<(bool, String)> { + ) -> Result { self.l7.evaluate_request(ctx, request) } fn admitted_token_grant_owners( diff --git a/crates/openshell-policy-cedar-runtime/src/cedar_only/l7.rs b/crates/openshell-policy-cedar-runtime/src/cedar_only/l7.rs index ac02cfed0f..320fd2a494 100644 --- a/crates/openshell-policy-cedar-runtime/src/cedar_only/l7.rs +++ b/crates/openshell-policy-cedar-runtime/src/cedar_only/l7.rs @@ -15,6 +15,7 @@ use openshell_policy_cedar::{CedarEngine, CedarEngineError, Decision, HttpReques use super::routes::{RequestRoute, UNMATCHED_PATH}; use super::{LoadedPolicy, PLACEHOLDER_IDENTITY}; +use crate::l7::L7Decision; use crate::policy_types::GraphqlPersistedQuery; /// Per-tunnel L7 decision handle for a Cedar-sourced sandbox. @@ -32,7 +33,7 @@ pub struct CedarL7TunnelEngine { } impl CedarL7TunnelEngine { - /// Evaluates one L7 request and returns `(allowed, deny_reason)`. + /// Evaluates one L7 request and the Cedar policies that decided it. /// /// # Errors /// @@ -42,7 +43,7 @@ impl CedarL7TunnelEngine { &self, ctx: &crate::L7PolicyContext, request: &crate::l7::L7RequestInfo, - ) -> Result<(bool, String)> { + ) -> Result { let guard = self.read_pinned()?; Self::decide(&guard, ctx, request, StagedAudit::Log) } @@ -82,7 +83,9 @@ impl CedarL7TunnelEngine { // `evaluate_request` already logged any staged audit decision for // this request. for l7_request in &requests { - if !Self::evaluate_one(&guard.cedar, ctx, request, l7_request, StagedAudit::Skip)?.0 { + if !Self::evaluate_one(&guard.cedar, ctx, request, l7_request, StagedAudit::Skip)? + .allowed + { return Ok(none()); } } @@ -127,28 +130,46 @@ impl CedarL7TunnelEngine { Ok(guard) } - /// Decides one L7 request and returns `(allowed, deny_reason)`. + /// Decides one L7 request. /// /// Same as the YAML path: a GraphQL request is allowed only when every - /// operation is allowed. + /// operation is allowed, by the policies that allowed any operation. + /// Otherwise it is denied with the first denial's reason, naming every + /// policy that denied an operation. fn decide( policy: &LoadedPolicy, ctx: &crate::L7PolicyContext, request: &crate::l7::L7RequestInfo, staged_audit: StagedAudit, - ) -> Result<(bool, String)> { + ) -> Result { let requests = match Self::prepare(policy, ctx, request)? { - Prepared::Denied(reason) => return Ok((false, reason)), + Prepared::Denied(reason) => return Ok(L7Decision::deny(reason, Vec::new())), Prepared::Evaluate(requests) => requests, }; + let mut allowed = L7Decision::allow(Vec::new()); + let mut denied: Option = None; for l7_request in &requests { + // Operations after a denial only add attribution; the request is + // already blocked, so their staged outcomes are not logged. + let staged_audit = if denied.is_some() { + StagedAudit::Skip + } else { + staged_audit + }; let decision = - Self::evaluate_one(&policy.cedar, ctx, request, l7_request, staged_audit)?; - if !decision.0 { - return Ok(decision); + match Self::evaluate_one(&policy.cedar, ctx, request, l7_request, staged_audit) { + Ok(decision) => decision, + // An error after a denial ends attribution without changing it. + Err(_) if denied.is_some() => break, + Err(error) => return Err(error), + }; + match (&mut denied, decision.allowed) { + (_, true) => allowed.merge_policies(decision), + (Some(denied), false) => denied.merge_policies(decision), + (None, false) => denied = Some(decision), } } - Ok(Self::decision(true)) + Ok(denied.unwrap_or(allowed)) } /// Builds the Cedar evaluations of one L7 request, or the reason it is @@ -293,8 +314,8 @@ impl CedarL7TunnelEngine { )) } - /// Evaluates one Cedar request and returns `(allowed, deny_reason)`, - /// logging any staged audit decision when `staged_audit` asks for it. + /// Evaluates one Cedar request, logging any staged audit decision when + /// `staged_audit` asks for it. /// /// A query with too many value combinations to evaluate, or a request /// field over the engine's length cap, is denied with that reason. @@ -304,14 +325,14 @@ impl CedarL7TunnelEngine { request: &crate::l7::L7RequestInfo, l7_request: &HttpRequestInput, staged_audit: StagedAudit, - ) -> Result<(bool, String)> { + ) -> Result { let evaluation = match cedar.evaluate_l7(l7_request) { Ok(evaluation) => evaluation, Err( error @ (CedarEngineError::TooManyQueryCombinations { .. } | CedarEngineError::RequestFieldTooLong { .. }), ) => { - return Ok((false, error.to_string())); + return Ok(L7Decision::deny(error.to_string(), Vec::new())); } Err(error) => return Err(miette::miette!("{error}")), }; @@ -325,17 +346,12 @@ impl CedarL7TunnelEngine { staged )); } - Ok(Self::decision(evaluation.is_allow())) - } - - /// Returns the relay's `(allowed, deny_reason)` pair. - fn decision(allowed: bool) -> (bool, String) { - let reason = if allowed { - String::new() - } else { - "denied by Cedar HttpRequest policy".to_string() - }; - (allowed, reason) + Ok(match evaluation.decision { + Decision::Allow { matched_policies } => L7Decision::allow(matched_policies), + Decision::Deny { matched_policies } => { + L7Decision::deny("denied by Cedar HttpRequest policy", matched_policies) + } + }) } } diff --git a/crates/openshell-policy-cedar-runtime/src/cedar_only/mod.rs b/crates/openshell-policy-cedar-runtime/src/cedar_only/mod.rs index 3a2e5d25eb..4a98fff68c 100644 --- a/crates/openshell-policy-cedar-runtime/src/cedar_only/mod.rs +++ b/crates/openshell-policy-cedar-runtime/src/cedar_only/mod.rs @@ -799,7 +799,7 @@ impl CedarOnlyEngine { let action = match evaluation.decision.clone() { Decision::Allow { matched_policies } => NetworkAction::Allow { - matched_policy: matched_policies.into_iter().next(), + matched_policy: matched_policies.into_iter().min(), }, Decision::Deny { matched_policies } => NetworkAction::Deny { reason: if matched_policies.is_empty() { diff --git a/crates/openshell-policy-cedar-runtime/src/cedar_only/tests.rs b/crates/openshell-policy-cedar-runtime/src/cedar_only/tests.rs index 73bc919c0e..1c1b65ff62 100644 --- a/crates/openshell-policy-cedar-runtime/src/cedar_only/tests.rs +++ b/crates/openshell-policy-cedar-runtime/src/cedar_only/tests.rs @@ -8,7 +8,7 @@ use super::l7::{UNREGISTERED_PERSISTED_QUERY, staged_audit_event}; use super::routes::{AliasTarget, BinaryAliases, RequestRoute, UNMATCHED_PATH}; use super::*; use crate::L7PolicyContext as L7EvalContext; -use crate::l7::L7RequestInfo; +use crate::l7::{L7Decision, L7RequestInfo}; use crate::policy_types::{DnsRecord, EndpointProtocol, TlsSetting}; const POLICY: &str = r#" @@ -153,12 +153,102 @@ when { context.binary_path == "/usr/bin/curl" }; assert!(authorization.endpoint_configs.is_empty()); } +const ATTRIBUTION_POLICY: &str = r#" +@id("z_connect") +permit ( + principal is Sandbox::Process, + action == Sandbox::Action::"NetworkConnect", + resource == Sandbox::NetworkEndpoint::"api.example.com:443" +) +when { context.binary_path == "/usr/bin/curl" }; + +@id("a_connect") +permit ( + principal is Sandbox::Process, + action == Sandbox::Action::"NetworkConnect", + resource == Sandbox::NetworkEndpoint::"api.example.com:443" +) +when { context.binary_path == "/usr/bin/curl" }; + +@id("a_read") +permit ( + principal is Sandbox::Process, + action == Sandbox::Action::"HttpRequest", + resource == Sandbox::NetworkEndpoint::"api.example.com:443" +) +when { (context.method == "GET" && context.path == "/item") || context.path == "/shared" }; + +@id("b_write") +permit ( + principal is Sandbox::Process, + action == Sandbox::Action::"HttpRequest", + resource == Sandbox::NetworkEndpoint::"api.example.com:443" +) +when { (context.method == "PUT" && context.path == "/item") || context.path == "/shared" }; + +@id("no_delete") +forbid ( + principal is Sandbox::Process, + action == Sandbox::Action::"HttpRequest", + resource == Sandbox::NetworkEndpoint::"api.example.com:443" +) +when { context.method == "DELETE" }; +"#; + +#[test] +fn l7_decision_names_the_cedar_policies_that_decided_it() { + let engine = CedarOnlyEngine::from_policy_str(ATTRIBUTION_POLICY).expect("policy parses"); + let handle = engine.l7_handle(engine.current_generation()); + let decide = |method: &str, path: &str| { + handle + .evaluate_request(&ctx(), &request(method, path)) + .expect("request evaluates") + }; + + assert_eq!(decide("GET", "/item").matched_policies, ["a_read"]); + assert_eq!(decide("PUT", "/item").matched_policies, ["b_write"]); + assert_eq!( + decide("GET", "/shared").matched_policies, + ["a_read", "b_write"] + ); + let forbidden = decide("DELETE", "/shared"); + assert!(!forbidden.allowed); + assert_eq!(forbidden.matched_policies, ["no_delete"]); + let unmatched = decide("POST", "/item"); + assert!(!unmatched.allowed); + assert!(unmatched.matched_policies.is_empty()); +} + +#[test] +fn connection_names_the_least_cedar_policy_that_permits_it() { + let engine = CedarOnlyEngine::from_policy_str(ATTRIBUTION_POLICY).expect("policy parses"); + let input = NetworkInput { + host: "api.example.com".to_string(), + port: 443, + binary_path: "/usr/bin/curl".into(), + binary_sha256: "deadbeef".to_string(), + ancestors: Vec::new(), + cmdline_paths: Vec::new(), + }; + for _ in 0..32 { + let authorization = engine.authorize_egress(&input).expect("request evaluates"); + assert!( + matches!( + &authorization.action, + NetworkAction::Allow { matched_policy: Some(policy) } if policy == "a_connect" + ), + "{:?}", + authorization.action + ); + } +} + #[test] fn l7_override_allows_the_permitted_request() { let engine = CedarOnlyEngine::from_policy_str(POLICY).expect("policy parses"); let generation = engine.current_generation(); let handle = engine.l7_handle(generation); - let (allowed, _) = handle + let L7Decision { allowed, .. } = handle .evaluate_request(&ctx(), &request("GET", "/v1/status")) .expect("request evaluates"); assert!(allowed); @@ -169,7 +259,9 @@ fn l7_override_denies_a_different_path() { let engine = CedarOnlyEngine::from_policy_str(POLICY).expect("policy parses"); let generation = engine.current_generation(); let handle = engine.l7_handle(generation); - let (allowed, reason) = handle + let L7Decision { + allowed, reason, .. + } = handle .evaluate_request(&ctx(), &request("GET", "/v1/admin")) .expect("request evaluates"); assert!(!allowed); @@ -222,7 +314,7 @@ fn tunnel_engine_delegates_l7_decisions_to_cedar() { .tunnel_engine(cedar.current_generation()) .expect("tunnel builds"); - let (allowed, _) = tunnel + let L7Decision { allowed, .. } = tunnel .evaluate_request(&ctx(), &request("GET", "/v1/status")) .expect("request evaluates"); assert!(allowed, "Cedar must decide the request"); @@ -1084,12 +1176,14 @@ fn audit_endpoint_configs_use_audit_enforcement() { fn audit_endpoint_reports_the_policy_decision_for_the_relay_to_log() { let engine = CedarOnlyEngine::from_policy_str(AUDIT_POLICY).expect("policy parses"); let tunnel = engine.l7_handle(engine.current_generation()); - let (allowed, reason) = tunnel + let L7Decision { + allowed, reason, .. + } = tunnel .evaluate_request(&ctx(), &request("DELETE", "/v1/items/1")) .expect("request evaluates"); assert!(!allowed, "the relay logs and forwards an audit deny"); assert!(!reason.is_empty()); - let (allowed, _) = tunnel + let L7Decision { allowed, .. } = tunnel .evaluate_request(&ctx(), &request("GET", "/v1/items/1")) .expect("request evaluates"); assert!(allowed); @@ -1387,11 +1481,11 @@ fn host_glob_selects_inspection_for_every_matching_host() { host: host.to_string(), ..ctx() }; - let (allowed, _) = handle + let L7Decision { allowed, .. } = handle .evaluate_request(&ctx, &request("GET", "/x")) .expect("evaluates"); assert!(allowed, "{host}: GET is allowed"); - let (allowed, _) = handle + let L7Decision { allowed, .. } = handle .evaluate_request(&ctx, &request("DELETE", "/x")) .expect("evaluates"); assert!(!allowed, "{host}: DELETE is denied"); @@ -1662,6 +1756,140 @@ when { }; "#; +#[test] +fn graphql_decision_names_the_permits_that_allowed_each_operation() { + const POLICY: &str = r#" +permit (principal, action == Sandbox::Action::"NetworkConnect", + resource == Sandbox::NetworkEndpoint::"api.example.com:443"); +@id("viewer") @protocol("graphql") +permit (principal, action == Sandbox::Action::"HttpRequest", + resource == Sandbox::NetworkEndpoint::"api.example.com:443") +when { ["viewer"].containsAll(context.graphql_fields) }; +@id("repos") @protocol("graphql") +permit (principal, action == Sandbox::Action::"HttpRequest", + resource == Sandbox::NetworkEndpoint::"api.example.com:443") +when { ["repos"].containsAll(context.graphql_fields) }; +"#; + let engine = CedarOnlyEngine::from_policy_str(POLICY).expect("policy parses"); + let operation = |field: &str| crate::l7::graphql::GraphqlOperationInfo { + operation_type: "query".to_string(), + operation_name: None, + fields: vec![field.to_string()], + persisted_query: false, + persisted_query_hash: None, + persisted_query_id: None, + }; + let request = L7RequestInfo { + graphql: Some(crate::l7::graphql::GraphqlRequestInfo { + operations: vec![operation("viewer"), operation("repos")], + error: None, + }), + ..request("POST", "/graphql") + }; + + let decision = evaluate(&engine, &request); + + assert!(decision.allowed, "{}", decision.reason); + assert_eq!(decision.matched_policies, ["repos", "viewer"]); +} + +#[test] +fn graphql_attribution_after_a_denial_emits_no_staged_audit() { + const POLICY: &str = r#" +permit (principal, action == Sandbox::Action::"NetworkConnect", + resource == Sandbox::NetworkEndpoint::"api.example.com:443"); +@protocol("graphql") +permit (principal, action == Sandbox::Action::"HttpRequest", + resource == Sandbox::NetworkEndpoint::"api.example.com:443"); +@id("no_admin") +forbid (principal, action == Sandbox::Action::"HttpRequest", + resource == Sandbox::NetworkEndpoint::"api.example.com:443") +when { context.graphql_fields.contains("admin") }; +@id("staged_viewer") @enforcement("staged") +forbid (principal, action == Sandbox::Action::"HttpRequest", + resource == Sandbox::NetworkEndpoint::"api.example.com:443") +when { context.graphql_fields.contains("viewer") }; +"#; + let engine = CedarOnlyEngine::from_policy_str(POLICY).expect("policy parses"); + let graphql = |fields: &[&str]| L7RequestInfo { + graphql: Some(crate::l7::graphql::GraphqlRequestInfo { + operations: fields + .iter() + .map(|field| crate::l7::graphql::GraphqlOperationInfo { + operation_type: "query".to_string(), + operation_name: None, + fields: vec![(*field).to_string()], + persisted_query: false, + persisted_query_hash: None, + persisted_query_id: None, + }) + .collect(), + error: None, + }), + ..request("POST", "/graphql") + }; + let staged_records = |fields: &[&str]| { + let capture = openshell_ocsf::test_support::OcsfCapture::default(); + let decision = { + let _guard = capture.install(); + evaluate(&engine, &graphql(fields)) + }; + let staged = capture + .json_events() + .into_iter() + .filter(|event| event["unmapped"]["cedar_audit"].is_string()) + .count(); + (decision.allowed, staged) + }; + + assert_eq!(staged_records(&["viewer"]), (true, 1)); + assert_eq!(staged_records(&["admin", "viewer"]), (false, 0)); +} + +#[test] +fn graphql_decision_names_the_forbids_that_denied_each_operation() { + const POLICY: &str = r#" +permit (principal, action == Sandbox::Action::"NetworkConnect", + resource == Sandbox::NetworkEndpoint::"api.example.com:443"); +@protocol("graphql") +permit (principal, action == Sandbox::Action::"HttpRequest", + resource == Sandbox::NetworkEndpoint::"api.example.com:443"); +@id("no_admin") +forbid (principal, action == Sandbox::Action::"HttpRequest", + resource == Sandbox::NetworkEndpoint::"api.example.com:443") +when { context.graphql_fields.contains("admin") }; +@id("no_billing") +forbid (principal, action == Sandbox::Action::"HttpRequest", + resource == Sandbox::NetworkEndpoint::"api.example.com:443") +when { context.graphql_fields.contains("billing") }; +"#; + let engine = CedarOnlyEngine::from_policy_str(POLICY).expect("policy parses"); + let operation = |field: &str| crate::l7::graphql::GraphqlOperationInfo { + operation_type: "query".to_string(), + operation_name: None, + fields: vec![field.to_string()], + persisted_query: false, + persisted_query_hash: None, + persisted_query_id: None, + }; + let graphql = |fields: &[&str]| L7RequestInfo { + graphql: Some(crate::l7::graphql::GraphqlRequestInfo { + operations: fields.iter().map(|field| operation(field)).collect(), + error: None, + }), + ..request("POST", "/graphql") + }; + + for fields in [["admin", "billing"], ["billing", "admin"]] { + let first = evaluate(&engine, &graphql(&fields[..1])); + let decision = evaluate(&engine, &graphql(&fields)); + + assert!(!decision.allowed); + assert_eq!(decision.reason, first.reason); + assert_eq!(decision.matched_policies, ["no_admin", "no_billing"]); + } +} + fn registry_setting(mode: &str) -> openshell_core::proto::NetworkEndpoint { let mut registry = setting("api.example.com", ""); registry.persisted_queries = mode.to_string(); @@ -1701,7 +1929,7 @@ fn persisted(hash: Option<&str>, id: Option<&str>) -> L7RequestInfo { } } -fn evaluate(engine: &CedarOnlyEngine, request: &L7RequestInfo) -> (bool, String) { +fn evaluate(engine: &CedarOnlyEngine, request: &L7RequestInfo) -> L7Decision { engine .l7_handle(engine.current_generation()) .evaluate_request(&ctx(), request) @@ -1715,11 +1943,13 @@ fn hash_only_persisted_queries_resolve_through_the_registry() { vec![registry_setting("allow_registered")], )) .expect("policy loads"); - assert!(evaluate(&engine, &persisted(Some("abc123"), None)).0); + assert!(evaluate(&engine, &persisted(Some("abc123"), None)).allowed); // The registered operation, not an empty one, is what Cedar judges. - assert!(!evaluate(&engine, &persisted(None, Some("saved-admin"))).0); + assert!(!evaluate(&engine, &persisted(None, Some("saved-admin"))).allowed); // The hash is the key whenever it is present. - let (allowed, reason) = evaluate(&engine, &persisted(Some("missing"), Some("abc123"))); + let L7Decision { + allowed, reason, .. + } = evaluate(&engine, &persisted(Some("missing"), Some("abc123"))); assert!(!allowed); assert_eq!(reason, UNREGISTERED_PERSISTED_QUERY); } @@ -1729,7 +1959,9 @@ fn hash_only_persisted_queries_are_denied_without_allow_registered() { for settings in [vec![registry_setting("deny")], Vec::new()] { let engine = CedarOnlyEngine::from_proto(&settings_policy(GRAPHQL_POLICY, settings)) .expect("policy loads"); - let (allowed, reason) = evaluate(&engine, &persisted(Some("abc123"), None)); + let L7Decision { + allowed, reason, .. + } = evaluate(&engine, &persisted(Some("abc123"), None)); assert!(!allowed); assert_eq!(reason, UNREGISTERED_PERSISTED_QUERY); } @@ -1804,13 +2036,13 @@ fn requests_take_the_inspection_of_their_routed_path() { .evaluate_request(&ctx_for("api.example.com"), request) .expect("request evaluates") }; - assert!(evaluate(&request("GET", "/api/items")).0); + assert!(evaluate(&request("GET", "/api/items")).allowed); assert_eq!( evaluate(&request("GET", "/other")), - (false, UNMATCHED_PATH.to_string()), + L7Decision::deny(UNMATCHED_PATH, Vec::new()), "no inspected path matches, as the relay denies it" ); - assert!(evaluate(&request("GET", "/ws")).0, "the upgrade"); + assert!(evaluate(&request("GET", "/ws")).allowed, "the upgrade"); let message = |operation_type: &str| L7RequestInfo { graphql: Some(crate::l7::graphql::GraphqlRequestInfo { operations: vec![crate::l7::graphql::GraphqlOperationInfo { @@ -1825,15 +2057,15 @@ fn requests_take_the_inspection_of_their_routed_path() { }), ..request("WEBSOCKET_TEXT", "/ws") }; - assert!(evaluate(&message("subscription")).0); - assert!(!evaluate(&message("mutation")).0); + assert!(evaluate(&message("subscription")).allowed); + assert!(!evaluate(&message("mutation")).allowed); // Routed to the audit path, the denial is reported for the relay to // log and forward. let mutation = L7RequestInfo { graphql: message("mutation").graphql, ..request("POST", "/graphql") }; - assert!(!evaluate(&mutation).0); + assert!(!evaluate(&mutation).allowed); } fn ctx_for(host: &str) -> L7EvalContext { @@ -1947,9 +2179,9 @@ fn query_params_reach_cedar_decoded() { .evaluate_request(&ctx(), &with_query(query)) .expect("request evaluates") }; - assert!(decide(&[("tag", &["foo-a", "foo-b"])]).0); - assert!(!decide(&[("tag", &["foo-a", "evil"])]).0); - assert!(!decide(&[]).0); + assert!(decide(&[("tag", &["foo-a", "foo-b"])]).allowed); + assert!(!decide(&[("tag", &["foo-a", "evil"])]).allowed); + assert!(!decide(&[]).allowed); } #[test] @@ -1960,12 +2192,14 @@ fn query_over_the_combination_cap_is_denied_with_a_reason() { .map(|value| format!("foo-{value}")) .collect(); let values: Vec<&str> = values.iter().map(String::as_str).collect(); - let (allowed, reason) = tunnel + let L7Decision { + allowed, reason, .. + } = tunnel .evaluate_request(&ctx(), &with_query(&[("tag", &values)])) .expect("an over-cap query is a decision, not an error"); assert!(!allowed); assert!(reason.contains("value combinations"), "{reason}"); - let (allowed, _) = tunnel + let L7Decision { allowed, .. } = tunnel .evaluate_request(&ctx(), &with_query(&[("tag", &values[1..])])) .unwrap(); assert!(allowed, "the cap itself is evaluated"); @@ -2054,7 +2288,7 @@ fn requests_carry_the_aliases_of_their_binary() { .l7_handle(engine.current_generation()) .evaluate_request(&python_ctx, &request(method, "/v1/status")) .expect("evaluates") - .0 + .allowed }; assert!(evaluate("GET")); assert!(!evaluate("DELETE"), "the forbid reaches the alias"); @@ -2062,7 +2296,7 @@ fn requests_carry_the_aliases_of_their_binary() { .l7_handle(engine.current_generation()) .evaluate_request(&ctx(), &request("DELETE", "/v1/status")) .expect("evaluates") - .0; + .allowed; assert!(curl, "another binary has no alias"); } @@ -2136,7 +2370,7 @@ fn requests_carry_the_globs_matching_their_binary() { .l7_handle(engine.current_generation()) .evaluate_request(ctx, &request(method, "/v1/status")) .expect("evaluates") - .0 + .allowed }; assert!(evaluate(&tool_ctx, "GET")); assert!( @@ -2217,7 +2451,7 @@ when { context.path == "/graphql" && context.graphql_operation_type == "query" } .l7_handle(engine.current_generation()) .evaluate_request(&ctx(), request) .expect("evaluates") - .0 + .allowed }; let operation = |operation_type: &str| L7RequestInfo { graphql: Some(crate::l7::graphql::GraphqlRequestInfo { @@ -2286,7 +2520,7 @@ when { context.method == "POST" }; .l7_handle(engine.current_generation()) .evaluate_request(&ctx(), &request(method, target)) .expect("evaluates") - .0 + .allowed }; assert!(!evaluate("DELETE", "/api/item"), "the audit forbid decides"); assert!(evaluate("GET", "/api/item"), "the audit permit decides"); diff --git a/crates/openshell-policy-runtime-interface/src/l7/mod.rs b/crates/openshell-policy-runtime-interface/src/l7/mod.rs index 6334851b13..722a9363ee 100644 --- a/crates/openshell-policy-runtime-interface/src/l7/mod.rs +++ b/crates/openshell-policy-runtime-interface/src/l7/mod.rs @@ -120,11 +120,55 @@ pub struct L7EndpointConfig { } /// Result of an L7 policy decision for a single request. -#[derive(Debug, Clone)] +#[derive(Debug, Clone, PartialEq, Eq)] pub struct L7Decision { pub allowed: bool, pub reason: String, - pub matched_rule: Option, + /// Sorted policies that decided the request: those that allowed it, or + /// those whose deny rules matched. Empty when no policy decided it. + pub matched_policies: Vec, +} + +impl L7Decision { + #[must_use] + pub fn allow(matched_policies: Vec) -> Self { + Self { + allowed: true, + reason: String::new(), + matched_policies: sorted(matched_policies), + } + } + + #[must_use] + pub fn deny(reason: impl Into, matched_policies: Vec) -> Self { + Self { + allowed: false, + reason: reason.into(), + matched_policies: sorted(matched_policies), + } + } + + /// The policy to record as the request's rule: the sole deciding policy, + /// or `-` when none or several decided it. + #[must_use] + pub fn rule_name(&self) -> &str { + match self.matched_policies.as_slice() { + [policy] => policy, + _ => "-", + } + } + + /// Adds the policies that decided another part of the same request. + pub fn merge_policies(&mut self, other: Self) { + self.matched_policies.extend(other.matched_policies); + self.matched_policies = sorted(std::mem::take(&mut self.matched_policies)); + } +} + +fn sorted(mut policies: Vec) -> Vec { + policies.sort_unstable(); + policies.dedup(); + policies } /// Parsed L7 request metadata used for policy evaluation and logging. diff --git a/crates/openshell-policy-runtime-interface/src/runtime.rs b/crates/openshell-policy-runtime-interface/src/runtime.rs index e6652c9f2f..bf40328922 100644 --- a/crates/openshell-policy-runtime-interface/src/runtime.rs +++ b/crates/openshell-policy-runtime-interface/src/runtime.rs @@ -12,8 +12,8 @@ use miette::Result; use openshell_core::proto::SandboxPolicy; use openshell_supervisor_middleware::{ChainEntry, ChainRunner, MiddlewareRegistry}; -use crate::l7::L7RequestInfo; use crate::l7::websocket::WebSocketAssemblyBudget; +use crate::l7::{L7Decision, L7RequestInfo}; use crate::network_middleware::ActiveMiddleware; use crate::policy_types::{ EgressAuthorization, EndpointConfig, NetworkInput, PolicyDnsEligibilitySnapshot, @@ -89,7 +89,7 @@ pub trait RequestPolicy: Send + Sync { &self, ctx: &L7PolicyContext, request: &L7RequestInfo, - ) -> Result<(bool, String)>; + ) -> Result; fn admitted_token_grant_owners( &self, ctx: &L7PolicyContext, @@ -299,7 +299,7 @@ impl TunnelPolicyEngine { &self, ctx: &L7PolicyContext, request: &L7RequestInfo, - ) -> Result<(bool, String)> { + ) -> Result { self.generation_guard.ensure_current()?; self.evaluator.evaluate_request(ctx, request) } diff --git a/crates/openshell-supervisor-network/data/sandbox-policy.rego b/crates/openshell-supervisor-network/data/sandbox-policy.rego index 91d8e222e7..f4101acef6 100644 --- a/crates/openshell-supervisor-network/data/sandbox-policy.rego +++ b/crates/openshell-supervisor-network/data/sandbox-policy.rego @@ -252,19 +252,24 @@ endpoint_uses_selected_request_protocol(_) if { command != "" } -# Forwarding and credential selection share endpoint admission. A deny rule -# on any matching endpoint removes every otherwise admitted endpoint. -_admitted_l7_endpoints := {ep | +# Policies that allow this request. A deny rule on any matching endpoint +# empties it. +request_allowing_policies := sort({name | some name policy := data.network_policies[name] binary_allowed(policy, input.exec) - eps := _policy_allowed_l7_endpoints(policy) - ep := eps[_] + count(_policy_allowed_l7_endpoints(policy)) > 0 not deny_request -} +}) allow_request if { - count(_admitted_l7_endpoints) > 0 + count(request_allowing_policies) > 0 +} + +# Forwarding and credential selection share endpoint admission. +_admitted_l7_endpoints := {ep | + some name in request_allowing_policies + ep := _policy_allowed_l7_endpoints(data.network_policies[name])[_] } # Credentials require the admission of their own endpoint. A sibling endpoint's @@ -305,9 +310,30 @@ deny_request if { _policy_denies_l7(policy) } -# --- L7 deny rule matching: REST method + path + query --- +# Policies whose authored deny rules match this request. A fail-closed denial +# that no deny rule matched names no policy. +request_denying_policies := sort({name | + some name + policy := data.network_policies[name] + endpoint_allowed(policy, input.network) + binary_allowed(policy, input.exec) + _policy_deny_rule_matches_l7(policy) +}) + +_policy_deny_rule_matches_l7(policy) if { + some ep + ep := policy.endpoints[_] + endpoint_matches_l7_request(ep, input.network, input.request) + request_matches_deny_rule(input.request, ep) +} request_denied_for_endpoint(request, endpoint) if { + request_matches_deny_rule(request, endpoint) +} + +# --- L7 deny rule matching: REST method + path + query --- + +request_matches_deny_rule(request, endpoint) if { not jsonrpc_family_endpoint(endpoint) some deny_rule deny_rule := endpoint.deny_rules[_] @@ -319,7 +345,7 @@ request_denied_for_endpoint(request, endpoint) if { # --- L7 deny rule matching: SQL command --- -request_denied_for_endpoint(request, endpoint) if { +request_matches_deny_rule(request, endpoint) if { some deny_rule deny_rule := endpoint.deny_rules[_] deny_rule.command @@ -328,7 +354,7 @@ request_denied_for_endpoint(request, endpoint) if { # --- L7 deny rule matching: JSON-RPC method --- -request_denied_for_endpoint(request, endpoint) if { +request_matches_deny_rule(request, endpoint) if { jsonrpc_family_endpoint(endpoint) request.method == "POST" some deny_rule @@ -345,7 +371,7 @@ request_denied_for_endpoint(request, endpoint) if { # --- L7 deny rule matching: GraphQL operation --- -request_denied_for_endpoint(request, endpoint) if { +request_matches_deny_rule(request, endpoint) if { graphql_request_has_operations(request) some deny_rule deny_rule := endpoint.deny_rules[_] diff --git a/crates/openshell-supervisor-network/src/l7/graphql.rs b/crates/openshell-supervisor-network/src/l7/graphql.rs index 3ecf3f5a8f..70acfa04a2 100644 --- a/crates/openshell-supervisor-network/src/l7/graphql.rs +++ b/crates/openshell-supervisor-network/src/l7/graphql.rs @@ -694,9 +694,10 @@ network_policies: let tunnel_engine = engine .clone_engine_for_tunnel(engine.current_generation()) .expect("tunnel engine should clone"); - let (allowed, reason) = - crate::l7::relay::evaluate_l7_request(&tunnel_engine, &ctx, &request_info) - .expect("evaluation should complete"); + let crate::l7::L7Decision { + allowed, reason, .. + } = crate::l7::relay::evaluate_l7_request(&tunnel_engine, &ctx, &request_info) + .expect("evaluation should complete"); assert!(allowed, "expected query to be allowed, got {reason}"); } diff --git a/crates/openshell-supervisor-network/src/l7/mod.rs b/crates/openshell-supervisor-network/src/l7/mod.rs index e00d179c09..9c313e2fcb 100644 --- a/crates/openshell-supervisor-network/src/l7/mod.rs +++ b/crates/openshell-supervisor-network/src/l7/mod.rs @@ -54,6 +54,17 @@ use std::sync::{Arc, Mutex}; use crate::policy_types::EndpointConfig; use crate::policy_types::PolicyGenerationGuard; +/// Records the policies that decided a request. +pub(crate) fn with_request_decision<'a, C>( + builder: openshell_ocsf::HttpActivityBuilder<'a, C>, + decision: &L7Decision, + engine_type: &str, +) -> openshell_ocsf::HttpActivityBuilder<'a, C> { + builder + .firewall_rule(decision.rule_name(), engine_type) + .unmapped("matched_policies", decision.matched_policies.clone()) +} + pub(crate) fn build_credential_endpoint_mismatch_finding( policy_name: &str, host: &str, diff --git a/crates/openshell-supervisor-network/src/l7/relay.rs b/crates/openshell-supervisor-network/src/l7/relay.rs index 7f0fad468d..5cba22b5c5 100644 --- a/crates/openshell-supervisor-network/src/l7/relay.rs +++ b/crates/openshell-supervisor-network/src/l7/relay.rs @@ -22,7 +22,9 @@ use crate::l7::middleware::{ }; use crate::l7::provider::{L7Provider, RelayOutcome}; use crate::l7::rest::WebSocketExtensionMode; -use crate::l7::{EndpointObserver, EnforcementMode, L7EndpointConfig, L7Protocol, L7RequestInfo}; +use crate::l7::{ + EndpointObserver, EnforcementMode, L7Decision, L7EndpointConfig, L7Protocol, L7RequestInfo, +}; // Test fixtures in child modules build the engine their tunnels pin to. #[cfg(test)] use crate::policy_engine::PolicyEngine; @@ -401,6 +403,7 @@ where "l7-mcp", &reason, summary.as_deref(), + None, ); if let Some(correlation) = correlation { correlation.record_rejection(400, HttpOutcome::Denied, None); @@ -503,6 +506,7 @@ where "l7-mcp", &reason, summary.as_deref(), + None, ); if let Some(correlation) = correlation { let status = match error { @@ -1718,7 +1722,15 @@ 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", + &L7Decision::deny(reason, Vec::new()), + None, + ); crate::l7::rest::RestProvider::default() .deny_with_redacted_target( &req, @@ -1925,8 +1937,8 @@ where let hard_deny_reason = l7_request_hard_deny_reason(config.protocol, &request_info); let force_deny = hard_deny_reason.is_some(); - let (allowed, reason) = if let Some(reason) = hard_deny_reason { - (false, reason) + let decision = if let Some(reason) = hard_deny_reason { + L7Decision::deny(reason, Vec::new()) } else { correlation .run_stage_sync( @@ -1937,6 +1949,7 @@ where ) .map_err(&capture_error)? }; + let allowed = decision.allowed; if close_if_stale(engine.generation_guard(), ctx) { return Ok(()); @@ -1957,7 +1970,7 @@ where &redacted_target, decision_str, engine_type, - &reason, + &decision, protocol_summary.as_deref(), ); @@ -2254,7 +2267,7 @@ where .deny_with_redacted_target( &req, &ctx.policy_name, - &reason, + &decision.reason, client, Some(&redacted_target), Some(deny_context), @@ -2279,7 +2292,7 @@ fn emit_l7_request_log( redacted_target: &str, decision_str: &str, engine_type: &str, - reason: &str, + decision: &L7Decision, protocol_summary: Option<&str>, ) { let event = build_l7_request_event( @@ -2288,13 +2301,15 @@ fn emit_l7_request_log( redacted_target, decision_str, engine_type, - reason, + &decision.reason, protocol_summary, + Some(decision), ); egress_emit!(event); emit_activity(ctx, decision_str == "deny", "l7_policy"); } +#[allow(clippy::too_many_arguments)] fn build_l7_request_event( ctx: &L7EvalContext, action: &str, @@ -2303,6 +2318,7 @@ fn build_l7_request_event( engine_type: &str, reason: &str, protocol_summary: Option<&str>, + decision: Option<&L7Decision>, ) -> openshell_ocsf::OcsfEvent { let (action_id, disposition_id, severity) = match decision_str { "deny" => (ActionId::Denied, DispositionId::Blocked, SeverityId::Medium), @@ -2323,16 +2339,19 @@ 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() + .message(message); + match decision { + Some(decision) => crate::l7::with_request_decision(builder, decision, engine_type), + None => builder.firewall_rule(&ctx.policy_name, engine_type), + } + .build() } fn l7_protocol_log_summary( @@ -2788,7 +2807,7 @@ where } // Evaluate L7 policy via Rego (using redacted target) - let (allowed, reason) = correlation + let decision = correlation .run_stage_sync( RequestStage::PolicyEvaluate, HttpOutcome::PlatformError, @@ -2796,6 +2815,11 @@ where || evaluate_l7_request(engine, ctx, &request_info), ) .map_err(&capture_error)?; + let L7Decision { + allowed, + ref reason, + .. + } = decision; if close_if_stale(engine.generation_guard(), ctx) { return Ok(()); @@ -2837,7 +2861,7 @@ where SeverityId::Informational, ), }; - let event = HttpActivityBuilder::new(openshell_ocsf::ctx::ctx()) + let builder = HttpActivityBuilder::new(openshell_ocsf::ctx::ctx()) .activity(ActivityId::Other) .action(action_id) .disposition(disposition_id) @@ -2847,12 +2871,11 @@ where ctx.ocsf_url(&redacted_target), )) .dst_endpoint(Endpoint::from_domain(&ctx.host, ctx.port)) - .firewall_rule(&ctx.policy_name, "l7") .message(format!( "L7_REQUEST {decision_str} {} {}:{}{} reason={}", request_info.action, ctx.host, ctx.port, redacted_target, reason, - )) - .build(); + )); + let event = crate::l7::with_request_decision(builder, &decision, "l7").build(); correlation.emit(event); } @@ -3117,7 +3140,7 @@ where .deny_with_redacted_target( &req, &ctx.policy_name, - &reason, + reason, client, Some(&redacted_target), Some( @@ -3368,8 +3391,8 @@ where let hard_deny_reason = l7_request_hard_deny_reason(config.protocol, &request_info); let force_deny = hard_deny_reason.is_some(); - let (allowed, reason, jsonrpc_log_info) = if let Some(reason) = hard_deny_reason { - (false, reason, jsonrpc_info.clone()) + let (decision, jsonrpc_log_info) = if let Some(reason) = hard_deny_reason { + (L7Decision::deny(reason, Vec::new()), jsonrpc_info.clone()) } else { let evaluation = correlation .run_stage_sync( @@ -3386,8 +3409,13 @@ where }, ) .map_err(&capture_error)?; - (evaluation.allowed, evaluation.reason, evaluation.log_info) + (evaluation.decision, evaluation.log_info) }; + let L7Decision { + allowed, + ref reason, + .. + } = decision; if close_if_stale(engine.generation_guard(), ctx) { return Ok(()); @@ -3411,7 +3439,7 @@ where }; let endpoint = format!("{}:{}{}", ctx.host, ctx.port, redacted_target); let policy_version = engine.captured_generation(); - let event = HttpActivityBuilder::new(openshell_ocsf::ctx::ctx()) + let builder = HttpActivityBuilder::new(openshell_ocsf::ctx::ctx()) .activity(ActivityId::Other) .action(action_id) .disposition(disposition_id) @@ -3421,16 +3449,20 @@ 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)) .message(jsonrpc_log_message( decision_str, &request_info.action, &endpoint, &jsonrpc_log_info, policy_version, - &reason, - )) - .build(); + reason, + )); + let event = crate::l7::with_request_decision( + builder, + &decision, + jsonrpc_engine_type(config.protocol), + ) + .build(); correlation.emit(event); } @@ -3585,7 +3617,7 @@ where .deny_with_redacted_target( &req, &ctx.policy_name, - &reason, + reason, client, Some(&redacted_target), Some( @@ -3754,8 +3786,8 @@ where // otherwise in audit mode. let hard_deny_reason = l7_request_hard_deny_reason(config.protocol, &request_info); let force_deny = hard_deny_reason.is_some(); - let (allowed, reason) = if let Some(reason) = hard_deny_reason { - (false, reason) + let decision = if let Some(reason) = hard_deny_reason { + L7Decision::deny(reason, Vec::new()) } else { correlation .run_stage_sync( @@ -3766,6 +3798,11 @@ where ) .map_err(&capture_error)? }; + let L7Decision { + allowed, + ref reason, + .. + } = decision; if close_if_stale(engine.generation_guard(), ctx) { return Ok(()); @@ -3793,7 +3830,7 @@ where ), }; let gql_summary = crate::l7::graphql::log_summary(&graphql_info); - let event = HttpActivityBuilder::new(openshell_ocsf::ctx::ctx()) + let builder = HttpActivityBuilder::new(openshell_ocsf::ctx::ctx()) .activity(ActivityId::Other) .action(action_id) .disposition(disposition_id) @@ -3803,12 +3840,11 @@ where ctx.ocsf_url(&redacted_target), )) .dst_endpoint(Endpoint::from_domain(&ctx.host, ctx.port)) - .firewall_rule(&ctx.policy_name, "l7-graphql") .message(format!( "GRAPHQL_L7_REQUEST {decision_str} {} {}:{}{} {gql_summary} reason={}", request_info.action, ctx.host, ctx.port, redacted_target, reason, - )) - .build(); + )); + let event = crate::l7::with_request_decision(builder, &decision, "l7-graphql").build(); correlation.emit(event); } @@ -3969,7 +4005,7 @@ where .deny_with_redacted_target( &req, &ctx.policy_name, - &reason, + reason, client, Some(&redacted_target), Some( @@ -4032,8 +4068,7 @@ fn sanitize_log_token(value: &str) -> String { } struct JsonRpcEvaluation { - allowed: bool, - reason: String, + decision: L7Decision, log_info: crate::l7::jsonrpc::JsonRpcRequestInfo, } @@ -4091,81 +4126,116 @@ fn is_benign_connection_error(err: &miette::Report) -> bool { BENIGN.iter().any(|pat| msg.contains(pat)) } -/// Evaluate an L7 request against the OPA engine. -/// -/// Returns `(allowed, deny_reason)`. +/// Evaluate an L7 request against the tunnel's policy engine. pub fn evaluate_l7_request( engine: &TunnelPolicyEngine, ctx: &L7EvalContext, request: &L7RequestInfo, -) -> Result<(bool, String)> { +) -> Result { if let Some(jsonrpc) = &request.jsonrpc && jsonrpc.is_batch && !jsonrpc.calls.is_empty() { + let mut allowed = L7Decision::allow(Vec::new()); if jsonrpc.has_response { - let (allowed, reason) = engine.evaluate_request(&ctx.policy_context(), request)?; - if !allowed { - return Ok((false, reason)); + let decision = engine.evaluate_request(&ctx.policy_context(), request)?; + if !decision.allowed { + return Ok(decision); } + allowed.merge_policies(decision); } - for call in &jsonrpc.calls { - let item_request = jsonrpc_request_for_call(request, call); - let (allowed, reason) = - engine.evaluate_request(&ctx.policy_context(), &item_request)?; - if !allowed { - return Ok((false, reason)); - } - } - return Ok((true, String::new())); + let (decision, _) = evaluate_jsonrpc_calls( + request, + &jsonrpc.calls, + allowed, + ErrorAfterDenial::KeepDenial, + |item| engine.evaluate_request(&ctx.policy_context(), item), + )?; + return Ok(decision); } engine.evaluate_request(&ctx.policy_context(), request) } +/// What a batch evaluation does when a call fails to evaluate after another +/// call was denied. +#[derive(Clone, Copy)] +enum ErrorAfterDenial { + /// Fail the evaluation, as for any other evaluation error. + Fail, + /// Keep the denial. Callers that otherwise stop at the first denial use + /// this so attribution cannot change their outcome. + KeepDenial, +} + +/// Evaluates each call of a JSON-RPC batch, merging allowing policies into +/// `allowed`. A batch with denied calls is denied with the first denial's +/// reason, naming every policy that denied a call, and returns those calls. +fn evaluate_jsonrpc_calls( + request: &L7RequestInfo, + calls: &[crate::l7::jsonrpc::JsonRpcCallInfo], + mut allowed: L7Decision, + after_denial: ErrorAfterDenial, + mut evaluate: impl FnMut(&L7RequestInfo) -> Result, +) -> Result<(L7Decision, Vec)> { + let mut denied: Option = None; + let mut denied_calls = Vec::new(); + for call in calls { + let decision = match evaluate(&jsonrpc_request_for_call(request, call)) { + Ok(decision) => decision, + Err(_) if denied.is_some() && matches!(after_denial, ErrorAfterDenial::KeepDenial) => { + break; + } + Err(error) => return Err(error), + }; + if decision.allowed { + allowed.merge_policies(decision); + continue; + } + match &mut denied { + Some(denied) => denied.merge_policies(decision), + None => denied = Some(decision), + } + denied_calls.push(call.clone()); + } + Ok((denied.unwrap_or(allowed), denied_calls)) +} + fn evaluate_jsonrpc_l7_request_for_log( engine: &TunnelPolicyEngine, ctx: &L7EvalContext, request: &L7RequestInfo, jsonrpc: &crate::l7::jsonrpc::JsonRpcRequestInfo, ) -> Result { + let mut allowed = L7Decision::allow(Vec::new()); if jsonrpc.has_response { - let (allowed, reason) = engine.evaluate_request(&ctx.policy_context(), request)?; - if !allowed || !jsonrpc.is_batch || jsonrpc.calls.is_empty() { + let decision = engine.evaluate_request(&ctx.policy_context(), request)?; + if !decision.allowed || !jsonrpc.is_batch || jsonrpc.calls.is_empty() { return Ok(JsonRpcEvaluation { - allowed, - reason, + decision, log_info: jsonrpc.clone(), }); } + allowed.merge_policies(decision); } if jsonrpc.is_batch && !jsonrpc.calls.is_empty() { - let mut denied_calls = Vec::new(); - let mut first_denied_reason = None; - for call in &jsonrpc.calls { - let item_request = jsonrpc_request_for_call(request, call); - let (allowed, reason) = - engine.evaluate_request(&ctx.policy_context(), &item_request)?; - if !allowed { - if first_denied_reason.is_none() { - first_denied_reason = Some(reason); - } - denied_calls.push(call.clone()); - } - } - - if denied_calls.is_empty() { + let (decision, denied_calls) = evaluate_jsonrpc_calls( + request, + &jsonrpc.calls, + allowed, + ErrorAfterDenial::Fail, + |item| engine.evaluate_request(&ctx.policy_context(), item), + )?; + if decision.allowed { return Ok(JsonRpcEvaluation { - allowed: true, - reason: String::new(), + decision, log_info: jsonrpc.clone(), }); } return Ok(JsonRpcEvaluation { - allowed: false, - reason: first_denied_reason.unwrap_or_else(|| "request denied by policy".to_string()), + decision, log_info: crate::l7::jsonrpc::JsonRpcRequestInfo { calls: denied_calls, is_batch: true, @@ -4178,10 +4248,8 @@ fn evaluate_jsonrpc_l7_request_for_log( }); } - let (allowed, reason) = engine.evaluate_request(&ctx.policy_context(), request)?; Ok(JsonRpcEvaluation { - allowed, - reason, + decision: engine.evaluate_request(&ctx.policy_context(), request)?, log_info: jsonrpc.clone(), }) } @@ -4190,17 +4258,21 @@ fn jsonrpc_request_for_call( request: &L7RequestInfo, call: &crate::l7::jsonrpc::JsonRpcCallInfo, ) -> L7RequestInfo { - let mut item_request = request.clone(); - item_request.jsonrpc = Some(crate::l7::jsonrpc::JsonRpcRequestInfo { - calls: vec![call.clone()], - is_batch: false, - receive_stream: false, - has_response: false, - mcp_revision: request.jsonrpc.as_ref().and_then(|info| info.mcp_revision), - mcp_http_metadata: None, - error: None, - }); - item_request + L7RequestInfo { + action: request.action.clone(), + target: request.target.clone(), + query_params: request.query_params.clone(), + graphql: request.graphql.clone(), + jsonrpc: Some(crate::l7::jsonrpc::JsonRpcRequestInfo { + calls: vec![call.clone()], + is_batch: false, + receive_stream: false, + has_response: false, + mcp_revision: request.jsonrpc.as_ref().and_then(|info| info.mcp_revision), + mcp_http_metadata: None, + error: None, + }), + } } /// Re-evaluate body-aware policy against a middleware-transformed body. Policy @@ -4271,20 +4343,23 @@ fn reevaluate_transformed_body( }; if let Some(reason) = l7_request_hard_deny_reason(config.protocol, &transformed_info) { - let reason = format!("middleware transformation rejected: {reason}"); + let decision = L7Decision::deny( + format!("middleware transformation rejected: {reason}"), + Vec::new(), + ); emit_transformed_body_decision( ctx, request_info, engine_type, "deny", - &reason, + &decision, correlation, ); - return Ok(Some(reason)); + return Ok(Some(decision.reason)); } let evaluate = || evaluate_l7_request(engine, ctx, &transformed_info); - let (allowed, reason) = correlation.map_or_else(evaluate, |correlation| { + let mut decision = correlation.map_or_else(evaluate, |correlation| { correlation.run_stage_sync( RequestStage::PolicyEvaluate, HttpOutcome::PlatformError, @@ -4292,23 +4367,33 @@ fn reevaluate_transformed_body( evaluate, ) })?; - if allowed { + if decision.allowed { return Ok(None); } - let reason = format!("middleware transformation denied by policy: {reason}"); + decision.reason = format!( + "middleware transformation denied by policy: {}", + decision.reason + ); if config.enforcement == EnforcementMode::Audit { emit_transformed_body_decision( ctx, request_info, engine_type, "audit", - &reason, + &decision, correlation, ); return Ok(None); } - emit_transformed_body_decision(ctx, request_info, engine_type, "deny", &reason, correlation); - Ok(Some(reason)) + emit_transformed_body_decision( + ctx, + request_info, + engine_type, + "deny", + &decision, + correlation, + ); + Ok(Some(decision.reason)) } /// Build the per-stage transformed-body validator the middleware chain calls @@ -4334,7 +4419,7 @@ fn emit_transformed_body_decision( request_info: &L7RequestInfo, engine_type: &str, decision_str: &str, - reason: &str, + decision: &L7Decision, correlation: Option<&RequestCorrelation>, ) { let (action_id, disposition_id, severity) = match decision_str { @@ -4345,7 +4430,7 @@ fn emit_transformed_body_decision( SeverityId::Informational, ), }; - let event = HttpActivityBuilder::new(openshell_ocsf::ctx::ctx()) + let builder = HttpActivityBuilder::new(openshell_ocsf::ctx::ctx()) .activity(ActivityId::Other) .action(action_id) .disposition(disposition_id) @@ -4355,12 +4440,11 @@ 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) .message(format!( "L7_REQUEST_TRANSFORMED {decision_str} {} {}:{}{} reason={}", - request_info.action, ctx.host, ctx.port, request_info.target, reason - )) - .build(); + request_info.action, ctx.host, ctx.port, request_info.target, decision.reason + )); + let event = crate::l7::with_request_decision(builder, decision, engine_type).build(); crate::l7::correlation::emit_request_events(correlation, [event]); } @@ -4885,7 +4969,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; @@ -10654,7 +10738,9 @@ network_policies: jsonrpc: None, }; - let (allowed, reason) = evaluate_l7_request(&tunnel_engine, &ctx, &request).unwrap(); + let L7Decision { + allowed, reason, .. + } = evaluate_l7_request(&tunnel_engine, &ctx, &request).unwrap(); assert!(!allowed); assert!(reason.contains("WEBSOCKET_TEXT /ws not permitted")); @@ -10709,6 +10795,184 @@ network_policies: ); } + #[test] + fn jsonrpc_batch_names_every_policy_that_allowed_a_call() { + let data = r#" +network_policies: + rpc_list: + name: rpc_list + endpoints: + - host: api.example.test + port: 443 + protocol: json-rpc + enforcement: enforce + rules: + - allow: { method: "reports.list" } + binaries: + - { path: /usr/bin/node } + rpc_search: + name: rpc_search + endpoints: + - host: api.example.test + port: 443 + protocol: json-rpc + enforcement: enforce + rules: + - allow: { method: "reports.search" } + binaries: + - { path: /usr/bin/node } +"#; + let engine = OpaEngine::from_strings(TEST_POLICY, data).unwrap(); + let tunnel_engine = engine + .clone_engine_for_tunnel(engine.current_generation()) + .unwrap(); + let ctx = L7EvalContext { + host: "api.example.test".into(), + port: 443, + request_default_port: Some(443), + policy_name: "rpc_list".into(), + binary_path: "/usr/bin/node".into(), + ..Default::default() + }; + let request = L7RequestInfo { + action: "POST".into(), + target: "/rpc".into(), + query_params: std::collections::HashMap::new(), + graphql: None, + jsonrpc: Some(crate::l7::jsonrpc::parse_jsonrpc_body( + br#"[ + {"jsonrpc":"2.0","id":1,"method":"reports.list"}, + {"jsonrpc":"2.0","id":2,"method":"reports.search"} + ]"#, + crate::l7::jsonrpc::JsonRpcInspectionMode::JsonRpc, + )), + }; + + let decision = evaluate_l7_request(&tunnel_engine, &ctx, &request).unwrap(); + assert!(decision.allowed, "{}", decision.reason); + assert_eq!(decision.matched_policies, ["rpc_list", "rpc_search"]); + + let jsonrpc = request.jsonrpc.as_ref().expect("jsonrpc request"); + let evaluation = + evaluate_jsonrpc_l7_request_for_log(&tunnel_engine, &ctx, &request, jsonrpc).unwrap(); + assert_eq!(evaluation.decision, decision); + } + + #[test] + fn jsonrpc_batch_names_every_policy_that_denied_a_call() { + let data = r#" +network_policies: + rpc_list: + name: rpc_list + endpoints: + - host: api.example.test + port: 443 + protocol: json-rpc + enforcement: enforce + rules: + - allow: { method: "reports.list" } + deny_rules: + - { method: "reports.delete" } + binaries: + - { path: /usr/bin/node } + rpc_search: + name: rpc_search + endpoints: + - host: api.example.test + port: 443 + protocol: json-rpc + enforcement: enforce + rules: + - allow: { method: "reports.search" } + deny_rules: + - { method: "reports.purge" } + binaries: + - { path: /usr/bin/node } +"#; + let engine = OpaEngine::from_strings(TEST_POLICY, data).unwrap(); + let tunnel_engine = engine + .clone_engine_for_tunnel(engine.current_generation()) + .unwrap(); + let ctx = L7EvalContext { + host: "api.example.test".into(), + port: 443, + request_default_port: Some(443), + policy_name: "rpc_list".into(), + binary_path: "/usr/bin/node".into(), + ..Default::default() + }; + let batch = |body: &[u8]| L7RequestInfo { + action: "POST".into(), + target: "/rpc".into(), + query_params: std::collections::HashMap::new(), + graphql: None, + jsonrpc: Some(crate::l7::jsonrpc::parse_jsonrpc_body( + body, + crate::l7::jsonrpc::JsonRpcInspectionMode::JsonRpc, + )), + }; + let delete = br#"{"jsonrpc":"2.0","id":1,"method":"reports.delete"}"#.as_slice(); + let purge = br#"{"jsonrpc":"2.0","id":2,"method":"reports.purge"}"#.as_slice(); + + for (first, second) in [(delete, purge), (purge, delete)] { + let request = batch(&[b"[", first, b",", second, b"]"].concat()); + let first_reason = evaluate_l7_request(&tunnel_engine, &ctx, &batch(first)) + .unwrap() + .reason; + + let decision = evaluate_l7_request(&tunnel_engine, &ctx, &request).unwrap(); + assert!(!decision.allowed); + assert_eq!(decision.reason, first_reason); + assert_eq!(decision.matched_policies, ["rpc_list", "rpc_search"]); + + let jsonrpc = request.jsonrpc.as_ref().expect("jsonrpc request"); + let evaluation = + evaluate_jsonrpc_l7_request_for_log(&tunnel_engine, &ctx, &request, jsonrpc) + .unwrap(); + assert_eq!(evaluation.decision, decision); + } + } + + #[test] + fn jsonrpc_batch_error_after_denial_fails_only_where_errors_propagate() { + let request = L7RequestInfo { + action: "POST".into(), + target: "/rpc".into(), + query_params: std::collections::HashMap::new(), + graphql: None, + jsonrpc: Some(crate::l7::jsonrpc::parse_jsonrpc_body( + br#"[ + {"jsonrpc":"2.0","id":1,"method":"denied"}, + {"jsonrpc":"2.0","id":2,"method":"broken"} + ]"#, + crate::l7::jsonrpc::JsonRpcInspectionMode::JsonRpc, + )), + }; + let calls = &request.jsonrpc.as_ref().expect("jsonrpc request").calls; + let denial = L7Decision::deny("first denial", vec!["rpc_list".into()]); + let evaluate = |item: &L7RequestInfo| match item.jsonrpc.as_ref().expect("call").calls[0] + .method + .as_str() + { + "denied" => Ok(denial.clone()), + _ => Err(miette::miette!("evaluation failed")), + }; + let evaluate_calls = |after_denial| { + evaluate_jsonrpc_calls( + &request, + calls, + L7Decision::allow(Vec::new()), + after_denial, + evaluate, + ) + }; + + assert!(evaluate_calls(ErrorAfterDenial::Fail).is_err()); + let (decision, denied_calls) = evaluate_calls(ErrorAfterDenial::KeepDenial).unwrap(); + assert_eq!(decision, denial); + assert_eq!(denied_calls, calls[..1]); + } + #[test] fn jsonrpc_batch_evaluates_each_call() { let data = r#" @@ -10759,7 +11023,9 @@ network_policies: )), }; - let (allowed, reason) = evaluate_l7_request(&tunnel_engine, &ctx, &request).unwrap(); + let L7Decision { + allowed, reason, .. + } = evaluate_l7_request(&tunnel_engine, &ctx, &request).unwrap(); assert!(allowed, "{reason}"); request.jsonrpc = Some(crate::l7::jsonrpc::parse_jsonrpc_body( @@ -10769,14 +11035,16 @@ network_policies: ]"#, crate::l7::jsonrpc::JsonRpcInspectionMode::JsonRpc, )); - let (allowed, reason) = evaluate_l7_request(&tunnel_engine, &ctx, &request).unwrap(); + let L7Decision { + allowed, reason, .. + } = evaluate_l7_request(&tunnel_engine, &ctx, &request).unwrap(); assert!(!allowed); assert!(reason.contains("response frames")); let jsonrpc = request.jsonrpc.as_ref().expect("jsonrpc request"); let evaluation = evaluate_jsonrpc_l7_request_for_log(&tunnel_engine, &ctx, &request, jsonrpc).unwrap(); - assert!(!evaluation.allowed); + assert!(!evaluation.decision.allowed); assert!(evaluation.log_info.has_response); assert_eq!( rule_method_names_for_log(&evaluation.log_info), @@ -10787,14 +11055,16 @@ network_policies: br#"{"jsonrpc":"2.0","id":2,"result":{"ok":true}}"#, crate::l7::jsonrpc::JsonRpcInspectionMode::JsonRpc, )); - let (allowed, reason) = evaluate_l7_request(&tunnel_engine, &ctx, &request).unwrap(); + let L7Decision { + allowed, reason, .. + } = evaluate_l7_request(&tunnel_engine, &ctx, &request).unwrap(); assert!(!allowed); assert!(reason.contains("response frames")); let jsonrpc = request.jsonrpc.as_ref().expect("jsonrpc response"); let evaluation = evaluate_jsonrpc_l7_request_for_log(&tunnel_engine, &ctx, &request, jsonrpc).unwrap(); - assert!(!evaluation.allowed); + assert!(!evaluation.decision.allowed); assert!(evaluation.log_info.has_response); assert_eq!(rule_method_names_for_log(&evaluation.log_info), "-"); @@ -10806,13 +11076,14 @@ network_policies: ]"#, crate::l7::jsonrpc::JsonRpcInspectionMode::JsonRpc, )); - let (allowed, _) = evaluate_l7_request(&tunnel_engine, &ctx, &request).unwrap(); + let L7Decision { allowed, .. } = + evaluate_l7_request(&tunnel_engine, &ctx, &request).unwrap(); assert!(!allowed); let jsonrpc = request.jsonrpc.as_ref().expect("jsonrpc request"); let evaluation = evaluate_jsonrpc_l7_request_for_log(&tunnel_engine, &ctx, &request, jsonrpc).unwrap(); - assert!(!evaluation.allowed); + assert!(!evaluation.decision.allowed); assert!(evaluation.log_info.is_batch); assert_eq!( rule_method_names_for_log(&evaluation.log_info), @@ -10825,7 +11096,7 @@ network_policies: "api.example.test:443/rpc", &evaluation.log_info, 42, - &evaluation.reason, + &evaluation.decision.reason, ); assert!(message.contains("rule_methods=reports.delete")); assert!(message.contains("policy_version=42")); @@ -10878,13 +11149,17 @@ network_policies: )), }; - let (allowed, reason) = evaluate_l7_request(&tunnel_engine, &ctx, &request).unwrap(); + let L7Decision { + allowed, reason, .. + } = evaluate_l7_request(&tunnel_engine, &ctx, &request).unwrap(); assert!(allowed, "{reason}"); request.jsonrpc = Some(crate::l7::jsonrpc::parse_jsonrpc_body( br#"{"jsonrpc":"2.0","id":1,"method":"reports.search","params":["ignored",{"nested":true}]}"#, crate::l7::jsonrpc::JsonRpcInspectionMode::JsonRpc, )); - let (allowed, reason) = evaluate_l7_request(&tunnel_engine, &ctx, &request).unwrap(); + let L7Decision { + allowed, reason, .. + } = evaluate_l7_request(&tunnel_engine, &ctx, &request).unwrap(); assert!(allowed, "{reason}"); } @@ -10945,7 +11220,9 @@ network_policies: )), }; - let (allowed, reason) = evaluate_l7_request(&tunnel_engine, &ctx, &request).unwrap(); + let L7Decision { + allowed, reason, .. + } = evaluate_l7_request(&tunnel_engine, &ctx, &request).unwrap(); assert!(allowed, "{reason}"); let allowed_info = request.jsonrpc.as_ref().expect("parsed MCP request"); let allowed_message = jsonrpc_log_message( @@ -10976,7 +11253,9 @@ network_policies: Some("delete_resource") ); - let (allowed, reason) = evaluate_l7_request(&tunnel_engine, &ctx, &request).unwrap(); + let L7Decision { + allowed, reason, .. + } = evaluate_l7_request(&tunnel_engine, &ctx, &request).unwrap(); assert!(!allowed, "delete_resource must match the MCP deny rule"); assert!( reason.contains("deny rule"), @@ -11367,13 +11646,17 @@ network_policies: "l7", "no L7 endpoint path matched request", None, + Some(&L7Decision::deny( + "no L7 endpoint path matched request", + Vec::new(), + )), ); assert_eq!(event.class_uid(), 4002); assert_eq!(event.base().severity, SeverityId::Medium); 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]" + "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]" ); } @@ -11393,7 +11676,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); @@ -13282,6 +13565,138 @@ network_policies: Ok((masked, String::from_utf8(payload).expect("text payload"))) } + #[tokio::test] + async fn l7_relay_names_each_requests_deciding_policy_on_a_reused_connection() { + use tracing::instrument::WithSubscriber as _; + use tracing_subscriber::layer::SubscriberExt as _; + + let data = r" +network_policies: + a_read: + name: a_read + endpoints: + - host: api.example.test + port: 8080 + protocol: rest + enforcement: enforce + rules: + - allow: { method: GET, path: /item } + binaries: + - { path: /usr/bin/curl } + b_write: + name: b_write + endpoints: + - host: api.example.test + port: 8080 + protocol: rest + enforcement: enforce + rules: + - allow: { method: PUT, path: /item } + binaries: + - { path: /usr/bin/curl } +"; + let engine = OpaEngine::from_strings(TEST_POLICY, data).unwrap(); + let input = NetworkInput { + host: "api.example.test".into(), + port: 8080, + binary_path: PathBuf::from("/usr/bin/curl"), + binary_sha256: "unused".into(), + ancestors: vec![], + cmdline_paths: vec![], + }; + let (endpoint_config, generation) = engine + .query_endpoint_config_with_generation(&input) + .unwrap(); + let config = crate::l7::parse_l7_config(&endpoint_config.unwrap()).unwrap(); + let tunnel_engine = engine.clone_engine_for_tunnel(generation).unwrap(); + let ctx = L7EvalContext { + host: "api.example.test".into(), + port: 8080, + request_default_port: Some(8080), + policy_name: "a_read".into(), + binary_path: "/usr/bin/curl".into(), + ..Default::default() + }; + let capture = openshell_ocsf::test_support::OcsfCapture::default(); + let subscriber = tracing_subscriber::registry().with(capture.clone()); + let (mut app, mut relay_client) = tokio::io::duplex(8192); + let (mut relay_upstream, mut upstream) = tokio::io::duplex(8192); + let relay = tokio::spawn( + async move { + relay_with_inspection( + &config, + tunnel_engine, + &mut relay_client, + &mut relay_upstream, + &ctx, + ) + .await + } + .with_subscriber(subscriber), + ); + + for method in ["GET", "PUT", "POST"] { + app.write_all( + format!( + "{method} /item HTTP/1.1\r\nHost: api.example.test\r\nContent-Length: 0\r\nConnection: keep-alive\r\n\r\n" + ) + .as_bytes(), + ) + .await + .unwrap(); + if method != "POST" { + let mut forwarded = [0u8; 512]; + let n = tokio::time::timeout( + std::time::Duration::from_secs(1), + upstream.read(&mut forwarded), + ) + .await + .expect("allowed request should reach upstream") + .unwrap(); + assert!(String::from_utf8_lossy(&forwarded[..n]).starts_with(method)); + upstream + .write_all( + b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: keep-alive\r\n\r\nOK", + ) + .await + .unwrap(); + } + let mut response = [0u8; 1024]; + let n = + tokio::time::timeout(std::time::Duration::from_secs(1), app.read(&mut response)) + .await + .expect("response should reach client") + .unwrap(); + assert!(n > 0, "{method}: connection closed"); + } + drop(app); + let _ = tokio::time::timeout(std::time::Duration::from_secs(1), relay).await; + + let decisions: Vec<_> = capture + .json_events() + .into_iter() + .filter(|record| { + record["message"] + .as_str() + .is_some_and(|message| message.starts_with("L7_REQUEST ")) + }) + .map(|record| { + ( + record["http_request"]["http_method"].clone(), + record["firewall_rule"]["name"].clone(), + ) + }) + .collect(); + assert_eq!( + decisions, + [ + (serde_json::json!("GET"), serde_json::json!("a_read")), + (serde_json::json!("PUT"), serde_json::json!("b_write")), + (serde_json::json!("POST"), serde_json::json!("-")), + ] + ); + } + #[tokio::test] async fn l7_relay_closes_keep_alive_tunnel_after_policy_generation_change() { let initial_data = r#" diff --git a/crates/openshell-supervisor-network/src/l7/relay/token_grant_ownership_tests.rs b/crates/openshell-supervisor-network/src/l7/relay/token_grant_ownership_tests.rs index 9334234df7..c22379c353 100644 --- a/crates/openshell-supervisor-network/src/l7/relay/token_grant_ownership_tests.rs +++ b/crates/openshell-supervisor-network/src/l7/relay/token_grant_ownership_tests.rs @@ -1489,7 +1489,7 @@ fn jsonrpc_batch_requires_one_owner_to_admit_every_member() { assert!( evaluate_l7_request(&engine, &ctx, &info) .expect("batch admission") - .0 + .allowed ); let owners = admitted_token_grant_owners(&engine, &ctx, &info).expect("batch owner admission"); diff --git a/crates/openshell-supervisor-network/src/l7/websocket.rs b/crates/openshell-supervisor-network/src/l7/websocket.rs index dae95cf6d2..4adbc2d10e 100644 --- a/crates/openshell-supervisor-network/src/l7/websocket.rs +++ b/crates/openshell-supervisor-network/src/l7/websocket.rs @@ -7,7 +7,7 @@ //! raw passthrough so inspection and rewriting cannot expose response payloads. use crate::l7::relay::{L7EvalContext, evaluate_l7_request}; -use crate::l7::{EnforcementMode, L7RequestInfo}; +use crate::l7::{EnforcementMode, L7Decision, L7RequestInfo}; use crate::policy_engine::TunnelPolicyEngine; use crate::policy_types::PolicyGenerationGuard; use crate::telemetry::egress_emit; @@ -1381,8 +1381,9 @@ fn inspect_websocket_text_message( graphql: None, jsonrpc: None, }; - let (allowed, reason) = evaluate_l7_request(inspector.engine, inspector.ctx, &request_info) + let l7_decision = evaluate_l7_request(inspector.engine, inspector.ctx, &request_info) .map_err(|error| terminate(WebSocketTerminationCause::PolicyReload, error))?; + let allowed = l7_decision.allowed; let decision = match (allowed, inspector.enforcement) { (true, _) => "allow", (false, EnforcementMode::Audit) => "audit", @@ -1392,9 +1393,10 @@ fn inspect_websocket_text_message( host, port, policy_name, + Some(&l7_decision), &request_info, decision, - &reason, + &l7_decision.reason, None, ); if !allowed && inspector.enforcement == EnforcementMode::Enforce { @@ -1426,6 +1428,7 @@ fn inspect_graphql_websocket_message( host, port, policy_name, + None, &request_info, "allow", &format!("GraphQL WebSocket control message {message_type}"), @@ -1449,23 +1452,25 @@ fn inspect_graphql_websocket_message( .as_deref() .map(|error| format!("GraphQL WebSocket message rejected: {error}")); let force_deny = parse_error_reason.is_some(); - let (allowed, reason) = if let Some(reason) = parse_error_reason { - (false, reason) + let l7_decision = if let Some(reason) = parse_error_reason { + L7Decision::deny(reason, Vec::new()) } else { evaluate_l7_request(inspector.engine, inspector.ctx, &request_info) .map_err(|error| terminate(WebSocketTerminationCause::PolicyReload, error))? }; + let allowed = l7_decision.allowed; let decision = match (allowed, inspector.enforcement) { (_, _) if force_deny => "deny", (true, _) => "allow", (false, EnforcementMode::Audit) => "audit", (false, EnforcementMode::Enforce) => "deny", }; - let reason = format!("graphql_ws_type={message_type} {reason}"); + let reason = format!("graphql_ws_type={message_type} {}", l7_decision.reason); emit_websocket_l7_event( host, port, policy_name, + Some(&l7_decision), &request_info, decision, &reason, @@ -2043,19 +2048,21 @@ fn rewrite_event_message(host: &str, port: u16, replacements: usize) -> String { ) } +#[allow(clippy::too_many_arguments)] fn emit_websocket_l7_event( host: &str, port: u16, policy_name: &str, + l7_decision: Option<&L7Decision>, request_info: &L7RequestInfo, decision: &str, reason: &str, graphql: Option<&crate::l7::graphql::GraphqlRequestInfo>, ) { - let policy_name = if policy_name.is_empty() { - "-" - } else { - policy_name + 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), @@ -2085,8 +2092,13 @@ fn emit_websocket_l7_event( .message(format!( "WEBSOCKET_L7_REQUEST {decision} {} {host}:{port}{}{} reason={reason}", request_info.action, request_info.target, summary - )) - .build(); + )); + let event = match l7_decision { + Some(l7_decision) => event + .unmapped("matched_policies", l7_decision.matched_policies.clone()) + .build(), + None => event.build(), + }; egress_emit!(event); } @@ -2215,6 +2227,123 @@ network_policies: - { path: /usr/bin/node } "#; + #[tokio::test] + async fn websocket_records_name_the_policies_that_decided_each_message() { + const POLICY: &str = r#" +network_policies: + ws_a: + name: ws_a + endpoints: + - host: realtime.graphql.test + port: 443 + path: "/graphql" + protocol: websocket + enforcement: audit + rules: + - allow: { operation_type: query, fields: [viewer] } + binaries: + - { path: /usr/bin/node } + ws_b: + name: ws_b + endpoints: + - host: realtime.graphql.test + port: 443 + path: "/graphql" + protocol: websocket + enforcement: audit + rules: + - allow: { operation_type: query, fields: [viewer] } + - allow: { operation_type: subscription, fields: [messageAdded] } + deny_rules: + - operation_type: mutation + binaries: + - { path: /usr/bin/node } +"#; + let _lock = openshell_otel_test_support::tracing_test_lock().await; + let engine = OpaEngine::from_strings(TEST_POLICY, POLICY).expect("policy loads"); + let tunnel_engine = engine + .clone_engine_for_tunnel(engine.current_generation()) + .expect("tunnel engine"); + let ctx = L7EvalContext { + host: "realtime.graphql.test".into(), + port: 443, + policy_name: "ws_a".into(), + binary_path: "/usr/bin/node".into(), + ..Default::default() + }; + let inspector = InspectionOptions { + engine: &tunnel_engine, + ctx: &ctx, + enforcement: EnforcementMode::Audit, + target: "/graphql".to_string(), + query_params: HashMap::new(), + graphql_policy: true, + }; + let subscribe = |query: &str| { + serde_json::json!({"id": "1", "type": "subscribe", "payload": {"query": query}}) + .to_string() + }; + let messages = [ + subscribe("subscription { messageAdded }"), + subscribe("query { viewer }"), + subscribe("mutation { deleteRepository }"), + r#"{"type":"connection_init"}"#.to_string(), + ]; + + let capture = crate::test_support::request_tracing::RequestTracing::new(None); + tracing::subscriber::with_default(capture.subscriber(), || { + for message in &messages { + inspect_websocket_text_message( + "realtime.graphql.test", + 443, + "ws_a", + &inspector, + message, + ) + .expect("audit mode forwards every message"); + } + }); + let records: Vec<_> = capture + .events + .json_events() + .into_iter() + .filter(|record| { + record["message"] + .as_str() + .is_some_and(|message| message.starts_with("WEBSOCKET_L7_REQUEST ")) + }) + .map(|record| { + ( + record["message"] + .as_str() + .unwrap() + .split(' ') + .nth(1) + .unwrap() + .to_string(), + record["firewall_rule"]["name"].clone(), + record["unmapped"]["matched_policies"].clone(), + ) + }) + .collect(); + capture.shutdown(); + + let json = serde_json::Value::from; + assert_eq!( + records, + [ + ("audit".into(), json("-"), serde_json::json!([])), + ( + "allow".into(), + json("-"), + serde_json::json!(["ws_a", "ws_b"]) + ), + ("audit".into(), json("ws_b"), serde_json::json!(["ws_b"])), + ("allow".into(), json("ws_a"), serde_json::Value::Null), + ] + ); + } + #[test] fn termination_causes_map_to_protocol_close_codes_and_session_reasons() { use openshell_core::proto::MiddlewareSessionEndReason as EndReason; diff --git a/crates/openshell-supervisor-network/src/opa.rs b/crates/openshell-supervisor-network/src/opa.rs index 87eeffca9a..7b3610c4b0 100644 --- a/crates/openshell-supervisor-network/src/opa.rs +++ b/crates/openshell-supervisor-network/src/opa.rs @@ -252,7 +252,7 @@ impl RegoTunnelEvaluator { middleware_configs_from_rego(&configs, &input.host)?.select(&input.host) } - /// Evaluates one L7 request and returns `(allowed, deny_reason)`. + /// Evaluates one L7 request and the policies that decided it. /// /// # Errors /// @@ -261,7 +261,7 @@ impl RegoTunnelEvaluator { &self, ctx: &openshell_policy_runtime_interface::L7PolicyContext, request: &crate::l7::L7RequestInfo, - ) -> Result<(bool, String)> { + ) -> Result { let input = regorus_input( openshell_policy_runtime_interface::l7::l7_request_policy_input(ctx, request), )?; @@ -272,22 +272,21 @@ impl RegoTunnelEvaluator { let allowed = engine .eval_rule("data.openshell.sandbox.allow_request".into()) .map_err(|e| miette::miette!("{e}"))?; - let allowed = allowed == regorus::Value::from(true); + if allowed == regorus::Value::from(true) { + let policies = eval_policy_names(&mut engine, "request_allowing_policies"); + return Ok(crate::l7::L7Decision::allow(policies)); + } - let reason = if allowed { - String::new() - } else { - let val = engine - .eval_rule("data.openshell.sandbox.request_deny_reason".into()) - .map_err(|e| miette::miette!("{e}"))?; - match val { - regorus::Value::String(s) => s.to_string(), - regorus::Value::Undefined => "request denied by policy".to_string(), - other => other.to_string(), - } + let reason = match engine + .eval_rule("data.openshell.sandbox.request_deny_reason".into()) + .map_err(|e| miette::miette!("{e}"))? + { + regorus::Value::String(s) => s.to_string(), + regorus::Value::Undefined => "request denied by policy".to_string(), + other => other.to_string(), }; - - Ok((allowed, reason)) + let policies = eval_policy_names(&mut engine, "request_denying_policies"); + Ok(crate::l7::L7Decision::deny(reason, policies)) } /// Returns the token-grant owners whose own endpoint admits one request. @@ -323,6 +322,40 @@ impl RegoTunnelEvaluator { } } +/// Reads the policies that decided a request. Attribution only labels the +/// decision, so a rule the loaded rules file does not define, or one that +/// fails or returns another shape, names no policy instead of failing it. +fn eval_policy_names(engine: &mut regorus::Engine, rule: &str) -> Vec { + let names = engine + .eval_query(format!("data.openshell.sandbox.{rule}"), false) + .map_err(|error| error.to_string()) + .and_then(|results| { + let Some(value) = results + .result + .into_iter() + .next() + .and_then(|result| result.expressions.into_iter().next()) + .map(|expression| expression.value) + else { + return Ok(Vec::new()); + }; + let regorus::Value::Array(names) = value else { + return Err("not an array".to_string()); + }; + names + .iter() + .map(|name| match name { + regorus::Value::String(name) => Ok(name.to_string()), + _ => Err("non-string entry".to_string()), + }) + .collect() + }); + names.unwrap_or_else(|error| { + tracing::debug!(rule, %error, "Request attribution unavailable"); + Vec::new() + }) +} + impl OpaEngine { pub(crate) fn websocket_assembly_budget( &self, @@ -5415,6 +5448,41 @@ process: assert!(!eval_l7(&engine, &input)); } + #[test] + fn l7_graphql_denials_name_only_policies_whose_deny_rules_matched() { + let engine = l7_engine(); + let denial = |operation: serde_json::Value| { + let mut eng = engine.engine.lock().unwrap(); + set_regorus_input( + &mut eng, + l7_graphql_input("api.graphql.com", serde_json::json!([operation])), + ) + .unwrap(); + let denied = eng + .eval_rule("data.openshell.sandbox.deny_request".into()) + .unwrap(); + ( + denied == regorus::Value::from(true), + eval_policy_names(&mut eng, "request_denying_policies"), + ) + }; + + let unlisted = denial(serde_json::json!({ + "operation_type": "query", + "fields": ["viewer", "adminAuditLog"], + "persisted_query": false + })); + assert_eq!(unlisted, (true, Vec::new())); + + let deny_rule = denial(serde_json::json!({ + "operation_type": "mutation", + "operation_name": "IssueDelete", + "fields": ["deleteRepository"], + "persisted_query": false + })); + assert_eq!(deny_rule, (true, vec!["graphql_api".to_string()])); + } + #[test] fn l7_graphql_deny_rule_takes_precedence() { let engine = l7_engine(); @@ -8252,6 +8320,54 @@ network_policies: ); } + #[test] + fn attribution_failures_keep_the_decision() { + let renamed = TEST_POLICY + .replace("request_allowing_policies", "legacy_allowing_policies") + .replace("request_denying_policies", "legacy_denying_policies"); + let malformed = format!( + "{renamed}\nrequest_allowing_policies := \"a\"\nrequest_denying_policies := [1]\n" + ); + let tunnel = |rules: &str| { + let engine = OpaEngine::from_strings(rules, L7_TEST_DATA).unwrap(); + engine + .clone_engine_for_tunnel(engine.current_generation()) + .unwrap() + }; + let context = openshell_policy_runtime_interface::L7PolicyContext { + host: "api.example.com".into(), + port: 8080, + binary_path: "/usr/bin/curl".into(), + ..Default::default() + }; + let request = |action: &str, target: &str| crate::l7::L7RequestInfo { + action: action.into(), + target: target.into(), + query_params: std::collections::HashMap::default(), + graphql: None, + jsonrpc: None, + }; + let expected_denial = tunnel(TEST_POLICY) + .evaluate_request(&context, &request("DELETE", "/repos/myorg/foo")) + .unwrap(); + + for rules in [renamed.as_str(), malformed.as_str()] { + let engine = tunnel(rules); + let allowed = engine + .evaluate_request(&context, &request("GET", "/repos/myorg/foo")) + .unwrap(); + assert_eq!(allowed, crate::l7::L7Decision::allow(Vec::new())); + + let denied = engine + .evaluate_request(&context, &request("DELETE", "/repos/myorg/foo")) + .unwrap(); + assert_eq!( + denied, + crate::l7::L7Decision::deny(expected_denial.reason.clone(), Vec::new()) + ); + } + } + #[test] fn l7_clone_engine_for_tunnel() { let engine = l7_engine(); @@ -8272,7 +8388,7 @@ network_policies: graphql: None, jsonrpc: None, }; - assert!(cloned.evaluate_request(&context, &request).unwrap().0); + assert!(cloned.evaluate_request(&context, &request).unwrap().allowed); } #[test] @@ -8321,7 +8437,7 @@ network_policies: graphql: None, jsonrpc: None, }; - assert!(cloned.evaluate_request(&context, &request).unwrap().0); + assert!(cloned.evaluate_request(&context, &request).unwrap().allowed); } #[test] diff --git a/crates/openshell-supervisor-network/src/policy_engine.rs b/crates/openshell-supervisor-network/src/policy_engine.rs index 1ec345d396..94c6ac02bd 100644 --- a/crates/openshell-supervisor-network/src/policy_engine.rs +++ b/crates/openshell-supervisor-network/src/policy_engine.rs @@ -10,8 +10,8 @@ use openshell_policy_runtime_interface::{ }; use openshell_supervisor_middleware::{ChainEntry, ChainRunner, MiddlewareRegistry}; -use crate::l7::L7RequestInfo; use crate::l7::websocket::WebSocketAssemblyBudget; +use crate::l7::{L7Decision, L7RequestInfo}; use crate::network_middleware::ActiveMiddleware; use crate::opa::{OpaEngine, RegoTunnelEvaluator}; use crate::policy_types::{ @@ -153,7 +153,7 @@ impl RequestPolicy for RegoTunnelEvaluator { &self, ctx: &L7PolicyContext, request: &L7RequestInfo, - ) -> Result<(bool, String)> { + ) -> Result { self.evaluate_request(ctx, request) } fn admitted_token_grant_owners( diff --git a/crates/openshell-supervisor-network/src/proxy.rs b/crates/openshell-supervisor-network/src/proxy.rs index 0aba0d900a..93c8e48bc7 100644 --- a/crates/openshell-supervisor-network/src/proxy.rs +++ b/crates/openshell-supervisor-network/src/proxy.rs @@ -6547,7 +6547,7 @@ async fn handle_forward_proxy_inner( crate::l7::relay::l7_request_hard_deny_reason(l7_config.config.protocol, &request_info); let force_deny = hard_deny_reason.is_some(); let mut evaluation_error = None; - let (allowed, reason) = hard_deny_reason.map_or_else( + let l7_decision = hard_deny_reason.map_or_else( || { let evaluation = correlation.run_stage_sync( RequestStage::PolicyEvaluate, @@ -6568,11 +6568,16 @@ async fn handle_forward_proxy_inner( l7_config.config.enforcement, &e.to_string(), )); - (false, format!("L7 evaluation error: {e}")) + crate::l7::L7Decision::deny(format!("L7 evaluation error: {e}"), Vec::new()) }) }, - |reason| (false, reason), + |reason| crate::l7::L7Decision::deny(reason, Vec::new()), ); + let crate::l7::L7Decision { + allowed, + ref reason, + .. + } = l7_decision; let decision_str = match (allowed, l7_config.config.enforcement) { (_, _) if force_deny => "deny", @@ -6621,11 +6626,11 @@ async fn handle_forward_proxy_inner( &endpoint, jsonrpc_info, tunnel_engine.captured_generation(), - &reason, + reason, ) }, ); - let event = HttpActivityBuilder::new(openshell_ocsf::ctx::ctx()) + let builder = HttpActivityBuilder::new(openshell_ocsf::ctx::ctx()) .activity(ActivityId::Other) .action(action_id) .disposition(disposition_id) @@ -6637,9 +6642,9 @@ 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) - .message(log_message) - .build(); + .message(log_message); + let event = + crate::l7::with_request_decision(builder, &l7_decision, engine_type).build(); emit_forward_l7_decision(event, evaluation_error, &connect_span, request_correlation); } @@ -6656,7 +6661,7 @@ async fn handle_forward_proxy_inner( port, &binary_str, &decision, - &reason, + reason, "forward-l7-deny", ); respond( @@ -7891,6 +7896,7 @@ fn is_benign_relay_error(err: &miette::Report) -> bool { mod tests { mod destination_policy; mod ipv4_mapped; + mod request_attribution; mod request_trace; #[test] diff --git a/crates/openshell-supervisor-network/src/proxy/tests/request_attribution.rs b/crates/openshell-supervisor-network/src/proxy/tests/request_attribution.rs new file mode 100644 index 0000000000..0b8d2602c0 --- /dev/null +++ b/crates/openshell-supervisor-network/src/proxy/tests/request_attribution.rs @@ -0,0 +1,156 @@ +// SPDX-License-Identifier: Apache-2.0 + +use super::*; +use crate::test_support::request_tracing::RequestTracing; +use tracing::instrument::WithSubscriber as _; + +const READ_WRITE_POLICY: &str = r#" +network_policies: + a_read: + name: a_read + endpoints: + - host: "UPSTREAM_IP" + port: UPSTREAM_PORT + allowed_ips: ["UPSTREAM_IP/32"] + protocol: rest + enforcement: enforce + rules: + - allow: { method: GET, path: /item } + - allow: { method: GET, path: /shared } + binaries: + - path: /usr/bin/python3 + b_write: + name: b_write + endpoints: + - host: "UPSTREAM_IP" + port: UPSTREAM_PORT + allowed_ips: ["UPSTREAM_IP/32"] + protocol: rest + enforcement: enforce + rules: + - allow: { method: PUT, path: /item } + - allow: { method: GET, path: /shared } + deny_rules: + - { method: DELETE, path: /item } + binaries: + - path: /usr/bin/python3 +"#; + +/// Sends one request through the forward proxy and returns its HTTP +/// Activity decision record, which precedes any upstream connection. +async fn forward_decision(method: &str, path: &str) -> serde_json::Value { + let _lock = openshell_otel_test_support::tracing_test_lock().await; + let ip = + non_loopback_test_ipv4().expect("forward attribution requires a non-loopback IPv4 address"); + let listener = TcpListener::bind((ip, 0)).await.unwrap(); + let port = listener.local_addr().unwrap().port(); + let policy = READ_WRITE_POLICY + .replace("UPSTREAM_IP", &ip.to_string()) + .replace("UPSTREAM_PORT", &port.to_string()); + let engine = Arc::new( + native_identity_engine(include_str!("../../../data/sandbox-policy.rego"), &policy).unwrap(), + ); + let identity = Ok(ContractBinaryIdentity { + executable: ContractExecutableIdentity { + path: executable_path("/usr/bin/python3"), + digest: Some("00".repeat(32).parse().unwrap()), + }, + ancestors: Vec::new(), + cmdline_paths: Vec::new(), + process: None, + }); + let capture = RequestTracing::new(None); + let (_app, proxy) = tokio::io::duplex(8192); + let mut proxy: ProxyClient = tokio::io::BufReader::new(Box::new(proxy)); + let target = format!("http://{ip}:{port}{path}"); + let request = + format!("{method} {target} HTTP/1.1\r\nHost: {ip}:{port}\r\nConnection: close\r\n\r\n"); + let decision = Box::pin(handle_forward_proxy( + method, + &target, + request.as_bytes(), + request.len(), + &mut proxy, + Some(&identity), + Some(( + "192.0.2.20:42123".parse().unwrap(), + "192.0.2.10:3128".parse().unwrap(), + )), + engine.into(), + Arc::new(BinaryIdentityCache::new()), + Arc::new(AtomicU32::new(0)), + None, + AgentProposals::default(), + Arc::new(None), + Arc::new(None), + None, + None, + None, + None, + None, + )); + let _ = tokio::time::timeout(std::time::Duration::from_millis(500), decision) + .with_subscriber(capture.subscriber()) + .await; + capture + .events + .json_events() + .into_iter() + .find(|record| { + record["message"] + .as_str() + .is_some_and(|message| message.starts_with("FORWARD_L7 ")) + }) + .expect("forward L7 decision record") +} + +#[tokio::test] +async fn forward_decision_names_the_entry_that_allowed_the_request() { + for (method, expected) in [("PUT", "b_write"), ("GET", "a_read")] { + let record = forward_decision(method, "/item").await; + + assert_eq!(record["action"], "Allowed", "{method}"); + assert_eq!(record["firewall_rule"]["name"], expected, "{method}"); + assert_eq!( + record["unmapped"]["matched_policies"], + serde_json::json!([expected]), + "{method}" + ); + } +} + +#[tokio::test] +async fn forward_decision_names_the_entry_whose_deny_rule_matched() { + let record = forward_decision("DELETE", "/item").await; + + assert_eq!(record["action"], "Denied"); + assert_eq!(record["firewall_rule"]["name"], "b_write"); + assert_eq!( + record["unmapped"]["matched_policies"], + serde_json::json!(["b_write"]) + ); +} + +#[tokio::test] +async fn forward_decision_names_no_entry_when_no_rule_allows_the_request() { + let record = forward_decision("POST", "/item").await; + + assert_eq!(record["action"], "Denied"); + assert_eq!(record["firewall_rule"]["name"], "-"); + assert_eq!( + record["unmapped"]["matched_policies"], + serde_json::json!([]) + ); +} + +#[tokio::test] +async fn forward_decision_lists_every_entry_when_several_allow_the_request() { + let record = forward_decision("GET", "/shared").await; + + assert_eq!(record["action"], "Allowed"); + assert_eq!(record["firewall_rule"]["name"], "-"); + assert_eq!( + record["unmapped"]["matched_policies"], + serde_json::json!(["a_read", "b_write"]) + ); +} diff --git a/crates/openshell-supervisor-network/src/proxy/tests/token_grants.rs b/crates/openshell-supervisor-network/src/proxy/tests/token_grants.rs index 30bd898494..f4664f9b29 100644 --- a/crates/openshell-supervisor-network/src/proxy/tests/token_grants.rs +++ b/crates/openshell-supervisor-network/src/proxy/tests/token_grants.rs @@ -63,7 +63,7 @@ async fn forward_inspection_selects_only_the_owner_admitting_the_request() { assert!( crate::l7::relay::evaluate_l7_request(&engine, &ctx, &info) .unwrap() - .0 + .allowed ); let raw = format!( "{method} http://api.example.test:8080/v1/projects HTTP/1.1\r\nHost: api.example.test:8080\r\nAuthorization: Bearer stale-token\r\nContent-Length: 0\r\n\r\n" diff --git a/crates/openshell-supervisor/src/lib.rs b/crates/openshell-supervisor/src/lib.rs index b9e6327d15..da9258656e 100644 --- a/crates/openshell-supervisor/src/lib.rs +++ b/crates/openshell-supervisor/src/lib.rs @@ -7145,7 +7145,7 @@ network_policies: tunnel .evaluate_request(&ctx, &request) .expect("public scope") - .0 + .allowed ); request .query_params @@ -7154,7 +7154,7 @@ network_policies: !tunnel .evaluate_request(&ctx, &request) .expect("private scope") - .0 + .allowed ); input.binary_path = "/usr/bin/unlisted".into(); assert!(matches!( diff --git a/docs/how-it-works/policies/cedar.mdx b/docs/how-it-works/policies/cedar.mdx index 5570f1a140..c1100bc818 100644 --- a/docs/how-it-works/policies/cedar.mdx +++ b/docs/how-it-works/policies/cedar.mdx @@ -417,7 +417,7 @@ forbid ( when { context.path like("/repos/*/*/hooks/**", "/") }; ``` -Logs name policies by their `@id` annotation when they have one. +Logs name policies by their `@id` annotation. A policy without one is named by Cedar's generated ID, such as `policy0`, which changes when policies before it are added or removed. Give each `permit` and `forbid` a unique `@id` so that logs keep naming it the same way. ## Providers and Credentials diff --git a/docs/observability/logging.mdx b/docs/observability/logging.mdx index 3dfdc72635..42baf98f56 100644 --- a/docs/observability/logging.mdx +++ b/docs/observability/logging.mdx @@ -136,9 +136,11 @@ OCSF NET:OPEN [INFO] ALLOWED /usr/bin/curl(58) -> api.github.com:443 [policy:git An L7 read-only policy denying a POST: ```text -OCSF HTTP:POST [MED] DENIED POST https://api.github.com/user/repos [policy:github_api engine:opa] +OCSF HTTP:POST [MED] DENIED POST https://api.github.com/user/repos [policy:- engine:opa] ``` +A request policy decision names the policy that decided that request, which can differ from the policy that allowed its connection: the policy that allowed the request, or the policy whose deny rule blocked it. It shows `policy:-` when no allow or deny rule decided the request, as in the read-only example above, or when several policies decided it. The JSON record lists the deciding policies in `unmapped.matched_policies`. Connection records, and records from other request controls such as middleware and credential binding, name the policy that allowed the connection. In a Cedar sandbox, request decisions name the deciding Cedar policies. + A connection denied because no policy matched: ```text diff --git a/docs/observability/ocsf-json-export.mdx b/docs/observability/ocsf-json-export.mdx index 46f541ebd3..7f5b21e8e3 100644 --- a/docs/observability/ocsf-json-export.mdx +++ b/docs/observability/ocsf-json-export.mdx @@ -383,6 +383,14 @@ collection. To count policy outcomes, group by `metadata.correlation_uid` and select the actual policy or firewall control record. Do not count every HTTP Activity or `decision` record as another request. +A request policy decision lists every policy that decided the request, sorted, +in `unmapped.matched_policies`, and names that policy in `firewall_rule.name` +when there is exactly one. When no allow or deny rule decided the request, such +as a request no rule allows, the list is empty and `firewall_rule.name` is `-`. +When several policies decided it, `firewall_rule.name` is also `-`. Records from +other request controls, such as middleware and credential binding, name the +policy that allowed the connection and omit `unmapped.matched_policies`. + Errors that end an inspected request retain that request's ID. A policy reload records the active request before closing it; an idle connection has no request ID. The `101` upgrade handoff record shares the HTTP handshake ID. Later diff --git a/tests/policy-conformance/src/cedar_integration.rs b/tests/policy-conformance/src/cedar_integration.rs index 7fdf801591..98fdcdb664 100644 --- a/tests/policy-conformance/src/cedar_integration.rs +++ b/tests/policy-conformance/src/cedar_integration.rs @@ -166,5 +166,5 @@ fn decoded_query_params_reach_the_cedar_backend() { graphql: None, jsonrpc: None, }; - assert!(tunnel.evaluate_request(&ctx, &request).unwrap().0); + assert!(tunnel.evaluate_request(&ctx, &request).unwrap().allowed); } diff --git a/tests/policy-conformance/src/conformance/mod.rs b/tests/policy-conformance/src/conformance/mod.rs index dfd8de6e92..dd514bd7ca 100644 --- a/tests/policy-conformance/src/conformance/mod.rs +++ b/tests/policy-conformance/src/conformance/mod.rs @@ -596,8 +596,8 @@ impl Engines { .l7_handle(self.cedar.current_generation()) .evaluate_request(&ctx.policy_context(), request); ( - request_outcome(&yaml.map(|(allowed, _)| allowed)), - request_outcome(&cedar.map(|(allowed, _)| allowed)), + request_outcome(&yaml.map(|decision| decision.allowed)), + request_outcome(&cedar.map(|decision| decision.allowed)), ) } Probe::Connect(input) => ( @@ -813,10 +813,10 @@ fn tls_mode_outcome(result: &miette::Result) -> String { } } -fn deny_reason_outcome(result: &miette::Result<(bool, String)>) -> String { +fn deny_reason_outcome(result: &miette::Result) -> String { match result { - Ok((true, _)) => "allow".to_string(), - Ok((false, reason)) => format!("deny: {reason}"), + Ok(decision) if decision.allowed => "allow".to_string(), + Ok(decision) => format!("deny: {}", decision.reason), Err(error) => format!("deny (error: {})", error_line(error)), } }