Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions crates/openshell-ocsf/src/builders/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,22 @@ impl<'a, Context> HttpActivityBuilder<'a, Context> {
self.firewall_rule = Some(FirewallRule::new(name, rule_type));
self
}

/// Set the firewall rule and the policy generation that evaluated it.
///
/// Use this for allow and deny decisions so the event names the exact
/// policy generation, not only the rule name.
#[must_use]
pub fn firewall_rule_at_generation(
mut self,
name: &str,
rule_type: &str,
generation: u64,
) -> Self {
self.firewall_rule =
Some(FirewallRule::new(name, rule_type).with_policy_generation(generation));
self
}
}

impl_activity_setter!(HttpActivityBuilder<Context>);
Expand Down Expand Up @@ -272,4 +288,27 @@ mod tests {
assert_eq!(json["unmapped"]["cached"], true);
assert_eq!(json["action_id"], 2); // Denied
}

#[test]
fn test_http_decision_records_policy_generation() {
let ctx = test_sandbox_context();
let event = HttpActivityBuilder::new(&ctx)
.activity(ActivityId::Other)
.action(ActionId::Allowed)
.disposition(DispositionId::Allowed)
.severity(SeverityId::Informational)
.dst_endpoint(Endpoint::from_domain("api.github.com", 443))
.http_request(HttpRequest::new(
"GET",
Url::new("https", "api.github.com", "/zen", 443),
))
.firewall_rule_at_generation("github_api", "l7", 12)
.build();

let json = event.to_json().unwrap();
assert_eq!(json["firewall_rule"]["name"], "github_api");
assert_eq!(json["firewall_rule"]["version"], "12");
openshell_ocsf_validate::validate_event(&json)
.unwrap_or_else(|e| panic!("firewall_rule.version must stay schema-valid: {e}"));
}
}
41 changes: 41 additions & 0 deletions crates/openshell-ocsf/src/builders/network.rs
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,22 @@ impl<'a, EndpointState> NetworkActivityBuilder<'a, EndpointState> {
self.firewall_rule = Some(FirewallRule::new(name, rule_type));
self
}

/// Set the firewall rule and the policy generation that evaluated it.
///
/// Use this for allow and deny decisions so the event names the exact
/// policy generation, not only the rule name.
#[must_use]
pub fn firewall_rule_at_generation(
mut self,
name: &str,
rule_type: &str,
generation: u64,
) -> Self {
self.firewall_rule =
Some(FirewallRule::new(name, rule_type).with_policy_generation(generation));
self
}
}

impl_activity_setter!(NetworkActivityBuilder<EndpointState>);
Expand Down Expand Up @@ -292,5 +308,30 @@ mod tests {
assert_eq!(json["device"]["container"]["name"], "my-sandbox");
assert_eq!(json["device"]["hostname"], "sandbox-abc123");
assert_eq!(json["is_src_dst_assignment_known"], true);
assert!(
json["firewall_rule"].get("version").is_none(),
"decisions built without a generation leave firewall_rule.version unset"
);
}

#[test]
fn test_network_decision_records_policy_generation() {
let ctx = test_sandbox_context();
let event = NetworkActivityBuilder::new(&ctx)
.activity(ActivityId::Open)
.action(ActionId::Denied)
.disposition(DispositionId::Blocked)
.severity(SeverityId::Medium)
.dst_endpoint(Endpoint::from_domain("httpbin.org", 443))
.firewall_rule_at_generation("-", "opa", 4)
.message("CONNECT denied httpbin.org:443")
.build();

let json = event.to_json().unwrap();
assert_eq!(json["firewall_rule"]["name"], "-");
assert_eq!(json["firewall_rule"]["type"], "opa");
assert_eq!(json["firewall_rule"]["version"], "4");
openshell_ocsf_validate::validate_event(&json)
.unwrap_or_else(|e| panic!("firewall_rule.version must stay schema-valid: {e}"));
}
}
33 changes: 33 additions & 0 deletions crates/openshell-ocsf/src/objects/firewall_rule.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,16 @@ pub struct FirewallRule {
/// (not OCSF-enumerated) with runtime-dynamic values from the policy engine.
#[serde(rename = "type")]
pub rule_type: String,

/// Version of the policy the rule belongs to, as evaluated for this event.
///
/// `OpenShell` sets this to the supervisor's policy engine generation: a
/// counter the engine advances whenever it replaces its active
/// configuration. Policy activation events record the same counter in
/// `unmapped.active_generation`, so a consumer can resolve the policy
/// behind each decision without relying on timestamps.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub version: Option<String>,
}

impl FirewallRule {
Expand All @@ -26,8 +36,16 @@ impl FirewallRule {
Self {
name: name.to_string(),
rule_type: rule_type.to_string(),
version: None,
}
}

/// Record the policy generation under which the rule was evaluated.
#[must_use]
pub fn with_policy_generation(mut self, generation: u64) -> Self {
self.version = Some(generation.to_string());
self
}
}

#[cfg(test)]
Expand All @@ -40,5 +58,20 @@ mod tests {
let json = serde_json::to_value(&rule).unwrap();
assert_eq!(json["name"], "default-egress");
assert_eq!(json["type"], "mechanistic");
assert!(
json.get("version").is_none(),
"version is omitted when no generation is recorded"
);
}

#[test]
fn test_firewall_rule_policy_generation_serializes_as_version() {
let rule = FirewallRule::new("github_api", "opa").with_policy_generation(7);
let json = serde_json::to_value(&rule).unwrap();
assert_eq!(json["name"], "github_api");
assert_eq!(json["version"], "7");

let round_trip: FirewallRule = serde_json::from_value(json).unwrap();
assert_eq!(round_trip, rule);
}
}
6 changes: 4 additions & 2 deletions crates/openshell-policy-cedar-runtime/src/backend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -96,8 +96,10 @@ impl PolicyBackend for CedarOnlyEngine {
fn middleware_runner(&self) -> Result<ChainRunner> {
self.middleware().runner()
}
fn replace_middleware_registry(&self, registry: MiddlewareRegistry) -> Result<()> {
self.middleware().replace_registry(registry)
fn replace_middleware_registry(&self, registry: MiddlewareRegistry) -> Result<u64> {
// A registry swap advances the middleware generation, not Cedar's.
self.middleware().replace_registry(registry)?;
Ok(PolicyBackend::current_generation(self))
}
fn passthrough_snapshot(&self) -> Result<Option<ActiveMiddleware>> {
self.middleware().snapshot().map(Some)
Expand Down
5 changes: 4 additions & 1 deletion crates/openshell-policy-runtime-interface/src/runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,10 @@ pub trait PolicyBackend: Send + Sync {
input: &NetworkInput,
) -> Result<(Vec<ChainEntry>, u64)>;
fn middleware_runner(&self) -> Result<ChainRunner>;
fn replace_middleware_registry(&self, registry: MiddlewareRegistry) -> Result<()>;
/// Install a new middleware registry and return the policy generation in
/// force afterwards. Engines that advance the policy generation on a
/// registry change return the generation the change activated.
fn replace_middleware_registry(&self, registry: MiddlewareRegistry) -> Result<u64>;
fn passthrough_snapshot(&self) -> Result<Option<ActiveMiddleware>>;
fn tunnel_engine(&self, expected: u64) -> Result<TunnelPolicyEngine>;
fn effective_filesystem(
Expand Down
Loading
Loading