Skip to content

Commit ca0a5ab

Browse files
committed
feat(observability): record generation on mapping denials and middleware reloads
Two events still lacked the generation after the main change. A transparent TCP connection that passes policy evaluation but then fails the DNS mapping check, including when the policy changes between the decision and the mapping lookup, now records the decision's generation in firewall_rule.version. Opens that fail the mapping check before evaluation leave it unset. Installing a new middleware registry advances the policy engine generation. replace_middleware_registry now returns that generation, and the "Supervisor middleware registry reloaded" event records it as unmapped.active_generation, like the other activation events. Refs #3840 Signed-off-by: Rakesh Gohel <mocha384@gmail.com>
1 parent 0f557ba commit ca0a5ab

4 files changed

Lines changed: 138 additions & 36 deletions

File tree

‎crates/openshell-supervisor-network/src/opa.rs‎

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -918,7 +918,9 @@ impl OpaEngine {
918918

919919
/// Replace the complete middleware service registry and invalidate
920920
/// existing tunnels so subsequent requests use the new service set.
921-
pub fn replace_middleware_registry(&self, registry: MiddlewareRegistry) -> Result<()> {
921+
/// Install a new middleware registry and return the policy generation it
922+
/// activated.
923+
pub fn replace_middleware_registry(&self, registry: MiddlewareRegistry) -> Result<u64> {
922924
// Generation changes serialize through the engine lock so guarded
923925
// publication cannot overlap any runtime generation transition.
924926
let _engine = self
@@ -930,8 +932,7 @@ impl OpaEngine {
930932
.write()
931933
.map_err(|_| miette::miette!("middleware runner lock poisoned"))?;
932934
*runner = runner.with_replacement_registry(registry);
933-
self.advance_generation();
934-
Ok(())
935+
Ok(self.advance_generation())
935936
}
936937

937938
pub(crate) fn middleware_runner(&self) -> Result<ChainRunner> {
@@ -8729,6 +8730,17 @@ network_policies:
87298730
assert_eq!(val, regorus::Value::from(true));
87308731
}
87318732

8733+
#[test]
8734+
fn replacing_the_middleware_registry_returns_the_activated_generation() {
8735+
let engine = test_engine();
8736+
let before = engine.current_generation();
8737+
let activated = engine
8738+
.replace_middleware_registry(MiddlewareRegistry::default())
8739+
.unwrap();
8740+
assert_eq!(activated, before + 1);
8741+
assert_eq!(engine.current_generation(), activated);
8742+
}
8743+
87328744
#[test]
87338745
fn policy_generation_starts_at_zero_and_increments_on_successful_reload() {
87348746
let engine = l7_engine();

‎crates/openshell-supervisor-network/src/proxy.rs‎

Lines changed: 84 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1262,7 +1262,7 @@ async fn handle_transparent_tcp_connection(
12621262
MappingLookupError::Expired
12631263
}
12641264
};
1265-
emit_transparent_mapping_denial(workload_addr, original, None, cause);
1265+
emit_transparent_mapping_denial(workload_addr, original, None, cause, None);
12661266
emit_activity(&activity_tx, true, "transparent_tcp_mapping");
12671267
return Ok(());
12681268
}
@@ -1306,6 +1306,7 @@ async fn handle_transparent_tcp_connection(
13061306
original,
13071307
Some(&host),
13081308
MappingLookupError::EndpointMismatch,
1309+
Some(decision.policy_generation),
13091310
);
13101311
emit_activity(&activity_tx, true, "transparent_tcp_mapping");
13111312
return Ok(());
@@ -1324,6 +1325,7 @@ async fn handle_transparent_tcp_connection(
13241325
original,
13251326
Some(&host),
13261327
MappingLookupError::StalePolicy,
1328+
Some(decision.policy_generation),
13271329
);
13281330
emit_activity(&activity_tx, true, "transparent_tcp_mapping");
13291331
return Ok(());
@@ -1336,7 +1338,13 @@ async fn handle_transparent_tcp_connection(
13361338
) {
13371339
Ok(mapping) => mapping,
13381340
Err(error) => {
1339-
emit_transparent_mapping_denial(workload_addr, original, Some(&host), error);
1341+
emit_transparent_mapping_denial(
1342+
workload_addr,
1343+
original,
1344+
Some(&host),
1345+
error,
1346+
Some(decision.policy_generation),
1347+
);
13401348
emit_activity(&activity_tx, true, "transparent_tcp_mapping");
13411349
return Ok(());
13421350
}
@@ -1590,7 +1598,28 @@ fn emit_transparent_mapping_denial(
15901598
original: SocketAddr,
15911599
mapped_host: Option<&str>,
15921600
error: MappingLookupError,
1601+
policy_generation: Option<u64>,
15931602
) {
1603+
egress_emit!(build_transparent_mapping_denial_event(
1604+
workload,
1605+
original,
1606+
mapped_host,
1607+
error,
1608+
policy_generation,
1609+
));
1610+
}
1611+
1612+
/// `policy_generation` is the generation of the egress decision made before
1613+
/// the mapping check, or `None` when the open failed before policy
1614+
/// evaluation.
1615+
#[cfg(target_os = "linux")]
1616+
fn build_transparent_mapping_denial_event(
1617+
workload: SocketAddr,
1618+
original: SocketAddr,
1619+
mapped_host: Option<&str>,
1620+
error: MappingLookupError,
1621+
policy_generation: Option<u64>,
1622+
) -> openshell_ocsf::OcsfEvent {
15941623
let detail = match error {
15951624
MappingLookupError::Missing => "transparent_tcp_mapping_missing",
15961625
MappingLookupError::Expired => "transparent_tcp_mapping_expired",
@@ -1600,19 +1629,21 @@ fn emit_transparent_mapping_denial(
16001629
| MappingLookupError::InvalidMapping
16011630
| MappingLookupError::LockPoisoned => "transparent_tcp_destination_denied",
16021631
};
1603-
egress_emit!(
1604-
NetworkActivityBuilder::new(openshell_ocsf::ctx::ctx())
1605-
.activity(ActivityId::Open)
1606-
.action(ActionId::Denied)
1607-
.disposition(DispositionId::Blocked)
1608-
.severity(SeverityId::Medium)
1609-
.status(StatusId::Failure)
1610-
.dst_endpoint(transparent_destination_endpoint(original, mapped_host))
1611-
.src_endpoint_addr(workload.ip(), workload.port())
1612-
.message(format!("Transparent TCP denied: {error}"))
1613-
.status_detail(detail)
1614-
.build()
1615-
);
1632+
let mut builder = NetworkActivityBuilder::new(openshell_ocsf::ctx::ctx())
1633+
.activity(ActivityId::Open)
1634+
.action(ActionId::Denied)
1635+
.disposition(DispositionId::Blocked)
1636+
.severity(SeverityId::Medium)
1637+
.status(StatusId::Failure)
1638+
.dst_endpoint(transparent_destination_endpoint(original, mapped_host))
1639+
.src_endpoint_addr(workload.ip(), workload.port());
1640+
if let Some(generation) = policy_generation {
1641+
builder = builder.firewall_rule_at_generation("-", "opa", generation);
1642+
}
1643+
builder
1644+
.message(format!("Transparent TCP denied: {error}"))
1645+
.status_detail(detail)
1646+
.build()
16161647
}
16171648

16181649
#[cfg(target_os = "linux")]
@@ -9091,6 +9122,44 @@ process: {{ run_as_user: sandbox, run_as_group: sandbox }}
90919122
);
90929123
}
90939124

9125+
#[cfg(target_os = "linux")]
9126+
#[test]
9127+
fn mapping_denial_after_evaluation_records_the_decision_generation() {
9128+
let workload: SocketAddr = "10.0.0.5:40000".parse().unwrap();
9129+
let original: SocketAddr = "198.18.0.2:443".parse().unwrap();
9130+
9131+
let stale = build_transparent_mapping_denial_event(
9132+
workload,
9133+
original,
9134+
Some("api.example.test"),
9135+
MappingLookupError::StalePolicy,
9136+
Some(5),
9137+
);
9138+
let stale = serde_json::to_value(stale).unwrap();
9139+
assert_eq!(
9140+
stale["status_detail"],
9141+
"transparent_tcp_mapping_stale_policy"
9142+
);
9143+
assert_eq!(
9144+
stale["firewall_rule"],
9145+
serde_json::json!({"name": "-", "type": "opa", "version": "5"})
9146+
);
9147+
9148+
let before_evaluation = build_transparent_mapping_denial_event(
9149+
workload,
9150+
original,
9151+
None,
9152+
MappingLookupError::Missing,
9153+
None,
9154+
);
9155+
let before_evaluation = serde_json::to_value(before_evaluation).unwrap();
9156+
assert_eq!(
9157+
before_evaluation["status_detail"],
9158+
"transparent_tcp_mapping_missing"
9159+
);
9160+
assert!(before_evaluation.get("firewall_rule").is_none());
9161+
}
9162+
90949163
#[test]
90959164
fn staged_denial_names_the_mapped_host_and_keeps_the_synthetic_address() {
90969165
let (open, _) = staged_curl_open("198.18.0.2:80".parse().unwrap(), 1);

‎crates/openshell-supervisor/src/lib.rs‎

Lines changed: 38 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -4441,7 +4441,7 @@ async fn install_builtin_middleware_registry(opa_engine: &OpaEngine) -> Result<(
44414441
Vec::new(),
44424442
)
44434443
.await?;
4444-
opa_engine.replace_middleware_registry(registry)
4444+
opa_engine.replace_middleware_registry(registry).map(|_| ())
44454445
}
44464446

44474447
/// Wait the configured poll interval, but never past the point at which an
@@ -4487,6 +4487,25 @@ struct MiddlewareRegistryReconciliation<'a> {
44874487
status: &'a mut MiddlewareRegistryStatus,
44884488
}
44894489

4490+
/// Build the CONFIG event recorded when a new middleware registry is
4491+
/// installed. Installing it advances the policy engine generation, so the
4492+
/// event records the generation it activated.
4493+
fn middleware_registry_reloaded_event(service_count: usize, active_generation: u64) -> OcsfEvent {
4494+
ConfigStateChangeBuilder::new(ocsf_ctx())
4495+
.severity(SeverityId::Informational)
4496+
.status(StatusId::Success)
4497+
.state(StateId::Enabled, "loaded")
4498+
.unmapped(
4499+
"supervisor_middleware_service_count",
4500+
serde_json::json!(service_count),
4501+
)
4502+
.unmapped("active_generation", serde_json::json!(active_generation))
4503+
.message(format!(
4504+
"Supervisor middleware registry reloaded [service_count:{service_count}]"
4505+
))
4506+
.build()
4507+
}
4508+
44904509
async fn reconcile_middleware_registry(
44914510
opa_engine: &OpaEngine,
44924511
middleware_connector: &MiddlewareConnector,
@@ -4503,7 +4522,7 @@ async fn reconcile_middleware_registry(
45034522
.await
45044523
.and_then(|registry| opa_engine.replace_middleware_registry(registry))
45054524
{
4506-
Ok(()) => {
4525+
Ok(active_generation) => {
45074526
retain_extension_credentials(
45084527
reconciliation.extension_credentials,
45094528
reconciliation.desired_services,
@@ -4514,21 +4533,10 @@ async fn reconcile_middleware_registry(
45144533
.current_services
45154534
.extend_from_slice(reconciliation.desired_services);
45164535
*reconciliation.status = MiddlewareRegistryStatus::Synchronized;
4517-
ocsf_emit!(
4518-
ConfigStateChangeBuilder::new(ocsf_ctx())
4519-
.severity(SeverityId::Informational)
4520-
.status(StatusId::Success)
4521-
.state(StateId::Enabled, "loaded")
4522-
.unmapped(
4523-
"supervisor_middleware_service_count",
4524-
serde_json::json!(reconciliation.current_services.len())
4525-
)
4526-
.message(format!(
4527-
"Supervisor middleware registry reloaded [service_count:{}]",
4528-
reconciliation.current_services.len()
4529-
))
4530-
.build()
4531-
);
4536+
ocsf_emit!(middleware_registry_reloaded_event(
4537+
reconciliation.current_services.len(),
4538+
active_generation,
4539+
));
45324540
}
45334541
Err(error) => {
45344542
// Emit only on the transition into the failed state to avoid
@@ -7818,6 +7826,19 @@ network_policies:
78187826
assert_eq!(json["unmapped"]["policy_hash"], "sha256:same");
78197827
assert!(json["unmapped"].get("active_generation").is_none());
78207828
}
7829+
7830+
#[test]
7831+
fn middleware_registry_reload_records_active_generation() {
7832+
let json = middleware_registry_reloaded_event(2, 7).to_json().unwrap();
7833+
assert_eq!(json["unmapped"]["supervisor_middleware_service_count"], 2);
7834+
assert_eq!(json["unmapped"]["active_generation"], 7);
7835+
assert!(
7836+
json["message"]
7837+
.as_str()
7838+
.unwrap()
7839+
.contains("Supervisor middleware registry reloaded [service_count:2]")
7840+
);
7841+
}
78217842
}
78227843

78237844
#[cfg(test)]

‎docs/observability/ocsf-json-export.mdx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -438,7 +438,7 @@ Policy validation failures emit a `CONFIG` event with `active_generation` and `c
438438

439439
The generation starts at zero when the supervisor starts. Use the `LIFECYCLE` start event as the boundary between supervisor lifetimes.
440440

441-
Layer 4 decisions (CONNECT, forward proxy, and transparent TCP) and layer 7 decisions for REST, JSON-RPC, MCP, GraphQL, and inspected WebSocket messages carry the generation. Denials made without matching a rule, such as when the calling process cannot be identified, carry the generation that was active when the denial was made. Events that are not policy decisions, such as MCP protocol version rejections and credential binding failures, leave `firewall_rule.version` unset. Policy DNS refusals also leave it unset. When the workload then connects anyway, the transparent TCP denial that follows carries the generation. Connections closed because the policy changed carry the generation they were authorized under.
441+
Layer 4 decisions (CONNECT, forward proxy, and transparent TCP) and layer 7 decisions for REST, JSON-RPC, MCP, GraphQL, and inspected WebSocket messages carry the generation. Denials made without matching a rule, such as when the calling process cannot be identified, carry the generation that was active when the denial was made. Events that are not policy decisions, such as MCP protocol version rejections and credential binding failures, leave `firewall_rule.version` unset. Policy DNS refusals also leave it unset. When the workload then connects anyway, the transparent TCP denial that follows carries the generation. A transparent TCP connection that passes policy but fails the DNS mapping check, for example because the policy changed in between, carries the generation of that policy decision. Connections closed because the policy changed carry the generation they were authorized under.
442442

443443
## OCSF Event Classes in JSON
444444

0 commit comments

Comments
 (0)