Skip to content

Commit 481ce56

Browse files
authored
fix(ocsf): correct HTTP activity context (#3316)
Previously, metadata events omitted both HTTP request and response objects, early proxy rejections used HTTP Activity without request context, and unsupported-scheme events did not expose enough safe HTTP context to satisfy the OCSF 1.8 schema. Now, metadata events include a method-only request and their actual HTTP response codes without recording the metadata URL. Unsupported-scheme events also include a method-only request plus the generated 400 response. Authority mismatches and credential-resolution denials use HTTP Activity with their generated 403 or 500 responses, and HTTP activity IDs are derived from the request method. Additionally, HttpActivityBuilder now enforces the OCSF request-or-response constraint at compile time. Signed-off-by: Kris Hicks <khicks@nvidia.com>
1 parent 39cf482 commit 481ce56

16 files changed

Lines changed: 521 additions & 84 deletions

File tree

‎Cargo.lock‎

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎architecture/sandbox.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -491,6 +491,10 @@ Security-relevant sandbox behavior uses OCSF structured events; internal
491491
diagnostics use ordinary tracing.
492492
The OCSF device describes the sandbox environment, with type ID Other and type
493493
label `Sandbox`; its operating system is a separate attribute.
494+
HTTP Activity records contain a request or response; early rejections with only
495+
connection context use Network Activity. Producer regression tests validate
496+
required fields and `at_least_one` constraints against the vendored OCSF 1.8
497+
schemas.
494498

495499
## Policy Proposals
496500

‎crates/openshell-ocsf/Cargo.toml‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,10 @@ rust-version.workspace = true
1010
license.workspace = true
1111
repository.workspace = true
1212

13+
[features]
14+
# Share vendored-schema assertions with producer regression tests.
15+
test-support = []
16+
1317
[dependencies]
1418
chrono = { version = "0.4", features = ["serde"] }
1519
serde = { workspace = true }

‎crates/openshell-ocsf/src/builders/http.rs‎

Lines changed: 143 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ use crate::events::{HttpActivityEvent, OcsfEvent};
1010
use crate::objects::{Actor, Endpoint, FirewallRule, HttpRequest, HttpResponse};
1111

1212
/// Builder for HTTP Activity [4002] events.
13-
pub struct HttpActivityBuilder<'a> {
13+
pub struct HttpActivityBuilder<'a, Context = MissingHttpContext> {
1414
ctx: &'a EventContext,
1515
activity: ActivityId,
1616
action: Option<ActionId>,
@@ -26,9 +26,35 @@ pub struct HttpActivityBuilder<'a> {
2626
message: Option<String>,
2727
status_detail: Option<String>,
2828
unmapped: serde_json::Map<String, serde_json::Value>,
29+
context: std::marker::PhantomData<Context>,
2930
}
3031

31-
impl<'a> HttpActivityBuilder<'a> {
32+
/// Marker for an HTTP Activity builder that has neither request nor response.
33+
pub struct MissingHttpContext;
34+
35+
/// Marker for an HTTP Activity builder that has a request or response.
36+
pub struct HasHttpContext;
37+
38+
impl<'a> HttpActivityBuilder<'a, MissingHttpContext> {
39+
/// Start building an HTTP Activity event.
40+
///
41+
/// An HTTP Activity must include an HTTP request or response before it can
42+
/// be built.
43+
///
44+
/// ```compile_fail
45+
/// use openshell_ocsf::{EventContext, HttpActivityBuilder};
46+
///
47+
/// let ctx = EventContext {
48+
/// sandbox_id: String::new(),
49+
/// sandbox_name: String::new(),
50+
/// container_image: String::new(),
51+
/// hostname: String::new(),
52+
/// product_version: String::new(),
53+
/// proxy_ip: "127.0.0.1".parse().unwrap(),
54+
/// proxy_port: 3128,
55+
/// };
56+
/// HttpActivityBuilder::new(&ctx).build();
57+
/// ```
3258
#[must_use]
3359
pub fn new(ctx: &'a EventContext) -> Self {
3460
Self {
@@ -47,19 +73,78 @@ impl<'a> HttpActivityBuilder<'a> {
4773
message: None,
4874
status_detail: None,
4975
unmapped: serde_json::Map::new(),
76+
context: std::marker::PhantomData,
5077
}
5178
}
5279

80+
#[must_use]
81+
pub fn http_request(self, req: HttpRequest) -> HttpActivityBuilder<'a, HasHttpContext> {
82+
self.with_http_request(req)
83+
}
84+
85+
#[must_use]
86+
pub fn http_response(self, resp: HttpResponse) -> HttpActivityBuilder<'a, HasHttpContext> {
87+
self.with_http_response(resp)
88+
}
89+
}
90+
91+
impl HttpActivityBuilder<'_, HasHttpContext> {
5392
#[must_use]
5493
pub fn http_request(mut self, req: HttpRequest) -> Self {
5594
self.http_request = Some(req);
5695
self
5796
}
97+
5898
#[must_use]
5999
pub fn http_response(mut self, resp: HttpResponse) -> Self {
60100
self.http_response = Some(resp);
61101
self
62102
}
103+
}
104+
105+
impl<'a, Context> HttpActivityBuilder<'a, Context> {
106+
fn with_http_request(self, req: HttpRequest) -> HttpActivityBuilder<'a, HasHttpContext> {
107+
HttpActivityBuilder {
108+
ctx: self.ctx,
109+
activity: self.activity,
110+
action: self.action,
111+
disposition: self.disposition,
112+
severity: self.severity,
113+
status: self.status,
114+
http_request: Some(req),
115+
http_response: self.http_response,
116+
src_endpoint: self.src_endpoint,
117+
dst_endpoint: self.dst_endpoint,
118+
actor: self.actor,
119+
firewall_rule: self.firewall_rule,
120+
message: self.message,
121+
status_detail: self.status_detail,
122+
unmapped: self.unmapped,
123+
context: std::marker::PhantomData,
124+
}
125+
}
126+
127+
fn with_http_response(self, resp: HttpResponse) -> HttpActivityBuilder<'a, HasHttpContext> {
128+
HttpActivityBuilder {
129+
ctx: self.ctx,
130+
activity: self.activity,
131+
action: self.action,
132+
disposition: self.disposition,
133+
severity: self.severity,
134+
status: self.status,
135+
http_request: self.http_request,
136+
http_response: Some(resp),
137+
src_endpoint: self.src_endpoint,
138+
dst_endpoint: self.dst_endpoint,
139+
actor: self.actor,
140+
firewall_rule: self.firewall_rule,
141+
message: self.message,
142+
status_detail: self.status_detail,
143+
unmapped: self.unmapped,
144+
context: std::marker::PhantomData,
145+
}
146+
}
147+
63148
#[must_use]
64149
pub fn src_endpoint(mut self, ep: Endpoint) -> Self {
65150
self.src_endpoint = Some(ep);
@@ -78,6 +163,62 @@ impl<'a> HttpActivityBuilder<'a> {
78163
self
79164
}
80165

166+
#[must_use]
167+
pub fn activity(mut self, id: ActivityId) -> Self {
168+
self.activity = id;
169+
self
170+
}
171+
172+
#[must_use]
173+
pub fn action(mut self, id: ActionId) -> Self {
174+
self.action = Some(id);
175+
self
176+
}
177+
178+
#[must_use]
179+
pub fn disposition(mut self, id: DispositionId) -> Self {
180+
self.disposition = Some(id);
181+
self
182+
}
183+
184+
#[must_use]
185+
pub fn actor_process(mut self, process: crate::objects::Process) -> Self {
186+
self.actor = Some(Actor { process });
187+
self
188+
}
189+
190+
#[must_use]
191+
pub fn dst_endpoint(mut self, endpoint: Endpoint) -> Self {
192+
self.dst_endpoint = Some(endpoint);
193+
self
194+
}
195+
196+
#[must_use]
197+
pub fn firewall_rule(mut self, name: &str, rule_type: &str) -> Self {
198+
self.firewall_rule = Some(FirewallRule::new(name, rule_type));
199+
self
200+
}
201+
202+
#[must_use]
203+
pub fn severity(mut self, id: SeverityId) -> Self {
204+
self.severity = id;
205+
self
206+
}
207+
208+
#[must_use]
209+
pub fn status(mut self, id: StatusId) -> Self {
210+
self.status = Some(id);
211+
self
212+
}
213+
214+
#[must_use]
215+
pub fn message(mut self, msg: impl Into<String>) -> Self {
216+
self.message = Some(msg.into());
217+
self
218+
}
219+
}
220+
221+
impl HttpActivityBuilder<'_, HasHttpContext> {
81222
#[must_use]
82223
pub fn build(self) -> OcsfEvent {
83224
let activity_name = self.activity.http_label().to_string();
@@ -118,13 +259,6 @@ impl<'a> HttpActivityBuilder<'a> {
118259
}
119260
}
120261

121-
impl_activity_setter!(HttpActivityBuilder);
122-
impl_action_disposition_setters!(HttpActivityBuilder);
123-
impl_actor_process_setter!(HttpActivityBuilder);
124-
impl_dst_endpoint_setter!(HttpActivityBuilder);
125-
impl_firewall_rule_setter!(HttpActivityBuilder);
126-
impl_builder_setters!(HttpActivityBuilder);
127-
128262
#[cfg(test)]
129263
mod tests {
130264
use super::*;

‎crates/openshell-ocsf/src/enums/activity.rs‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,23 @@ pub enum ActivityId {
4747
}
4848

4949
impl ActivityId {
50+
/// Map an HTTP method to its HTTP Activity identifier.
51+
#[must_use]
52+
pub fn for_http_method(method: &str) -> Self {
53+
match method.to_ascii_uppercase().as_str() {
54+
"CONNECT" => Self::Open,
55+
"DELETE" => Self::Close,
56+
"GET" => Self::Reset,
57+
"HEAD" => Self::Fail,
58+
"OPTIONS" => Self::Refuse,
59+
"POST" => Self::Traffic,
60+
"PUT" => Self::Listen,
61+
"TRACE" => Self::Trace,
62+
"PATCH" => Self::Patch,
63+
_ => Self::Other,
64+
}
65+
}
66+
5067
/// Returns a human-readable label for this activity in a network context.
5168
#[must_use]
5269
pub fn network_label(self) -> &'static str {
@@ -163,6 +180,13 @@ mod tests {
163180
assert_eq!(ActivityId::Patch.http_label(), "Patch");
164181
}
165182

183+
#[test]
184+
fn maps_http_methods_to_http_activity_ids() {
185+
assert_eq!(ActivityId::for_http_method("GET"), ActivityId::Reset);
186+
assert_eq!(ActivityId::for_http_method("post"), ActivityId::Traffic);
187+
assert_eq!(ActivityId::for_http_method("PROPFIND"), ActivityId::Other);
188+
}
189+
166190
#[test]
167191
fn test_activity_process_labels() {
168192
assert_eq!(ActivityId::Open.process_label(), "Launch");

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ pub mod format;
3232
pub mod objects;
3333
pub mod tracing_layers;
3434

35-
#[cfg(test)]
35+
#[cfg(any(test, feature = "test-support"))]
3636
pub mod validation;
3737

3838
// --- Core event types ---

‎crates/openshell-ocsf/src/validation/mod.rs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,8 @@
33

44
//! Schema validation utilities for testing OCSF events against vendored schemas.
55
//!
6-
//! These utilities are gated behind `#[cfg(test)]` — they are only available
7-
//! in test builds.
6+
//! Available in this crate's tests or through the `test-support` feature for
7+
//! producer regression tests.
88
99
pub mod schema;
1010

‎crates/openshell-ocsf/src/validation/schema.rs‎

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,12 +56,26 @@ pub fn validate_required_fields(event: &Value, schema: &Value) {
5656
_ => return,
5757
};
5858

59+
if let Some(fields) = schema
60+
.get("constraints")
61+
.and_then(|constraints| constraints.get("at_least_one"))
62+
.and_then(Value::as_array)
63+
{
64+
assert!(
65+
fields
66+
.iter()
67+
.filter_map(Value::as_str)
68+
.any(|field| { event.get(field).is_some_and(|value| !value.is_null()) }),
69+
"Missing at_least_one field from {fields:?}"
70+
);
71+
}
72+
5973
for (name, def) in &attrs {
6074
let is_required = def.get("requirement").and_then(|r| r.as_str()) == Some("required");
6175
let is_profile_field = def.get("profile").is_some() || def.get("profiles").is_some();
6276
if is_required && !is_profile_field {
6377
assert!(
64-
event.get(name).is_some(),
78+
event.get(name).is_some_and(|value| !value.is_null()),
6579
"Missing required field '{name}' in OCSF event. Event keys: {:?}",
6680
event.as_object().map(|o| o.keys().collect::<Vec<_>>())
6781
);
@@ -92,6 +106,32 @@ pub fn validate_enum_value(event: &Value, field: &str, schema: &Value) {
92106
mod tests {
93107
use super::*;
94108

109+
#[test]
110+
fn network_and_http_require_at_least_one_non_null_field() {
111+
for (class, fields) in [
112+
("network_activity", ["src_endpoint", "dst_endpoint"]),
113+
("http_activity", ["http_request", "http_response"]),
114+
] {
115+
let schema = load_class_schema(class);
116+
let mut event = serde_json::json!({
117+
"class_uid": schema["uid"], "severity_id": 1, "metadata": {},
118+
"time": 12345, "type_uid": 0, "activity_id": 0, "category_uid": 4
119+
});
120+
assert!(
121+
std::panic::catch_unwind(|| validate_required_fields(&event, &schema)).is_err()
122+
);
123+
for field in fields {
124+
event[field] = Value::Null;
125+
assert!(
126+
std::panic::catch_unwind(|| validate_required_fields(&event, &schema)).is_err()
127+
);
128+
event[field] = serde_json::json!({});
129+
validate_required_fields(&event, &schema);
130+
event.as_object_mut().unwrap().remove(field);
131+
}
132+
}
133+
}
134+
95135
#[test]
96136
fn test_load_class_schemas() {
97137
// These tests only pass when the vendored schemas are present

‎crates/openshell-sandbox/Cargo.toml‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ openshell-supervisor-process = { path = "../openshell-supervisor-process" }
2626

2727
# Async runtime
2828
tokio = { workspace = true }
29+
http = { workspace = true }
2930

3031
# gRPC (tonic::Status downcast in error mapping)
3132
tonic = { workspace = true, features = ["channel", "tls-native-roots"] }
@@ -76,6 +77,7 @@ telemetry = ["openshell-core/telemetry"]
7677
bundled-ca-roots = ["openshell-supervisor-network/bundled-ca-roots"]
7778

7879
[dev-dependencies]
80+
openshell-ocsf = { path = "../openshell-ocsf", features = ["test-support"] }
7981
tempfile = "3"
8082
temp-env = "0.3"
8183
tokio-tungstenite = { workspace = true }

0 commit comments

Comments
 (0)