From 22073fcaaeeb6ccefeb3b45145c18de5d3a36b05 Mon Sep 17 00:00:00 2001 From: krishicks Date: Mon, 31 Aug 2026 23:02:30 +0000 Subject: [PATCH 1/3] test: backfill coverage for OCSF logging (#3065) Characterization tests for behavior that later work changes. No behavior change. - Pin the `openshell logs` output format, so a change to how that text is produced shows up as a diff rather than passing silently. - Cover the supervisor log push layer. - Assert OcsfEvent survives a JSON round trip. Serialization is written by hand and deserialization dispatches on class_uid into independent per-variant paths, so a field can serialize correctly and still be dropped or rejected on the way back in. Refs #1055 Signed-off-by: Kris Hicks --- crates/openshell-cli/src/run.rs | 116 ++++++++- crates/openshell-ocsf/tests/roundtrip.rs | 221 ++++++++++++++++++ .../src/log_push.rs | 217 ++++++++++++++++- 3 files changed, 545 insertions(+), 9 deletions(-) create mode 100644 crates/openshell-ocsf/tests/roundtrip.rs diff --git a/crates/openshell-cli/src/run.rs b/crates/openshell-cli/src/run.rs index b89f4f9371..bead4b4319 100644 --- a/crates/openshell-cli/src/run.rs +++ b/crates/openshell-cli/src/run.rs @@ -7117,6 +7117,10 @@ pub async fn sandbox_logs( } fn print_log_line(log: &openshell_core::proto::SandboxLogLine) { + println!("{}", format_log_line(log)); +} + +fn format_log_line(log: &openshell_core::proto::SandboxLogLine) -> String { let source = if log.source.is_empty() { "gateway" } else { @@ -7125,10 +7129,10 @@ fn print_log_line(log: &openshell_core::proto::SandboxLogLine) { let secs = log.timestamp_ms / 1000; let millis = log.timestamp_ms % 1000; if log.fields.is_empty() { - println!( + format!( "[{secs}.{millis:03}] [{source:<7}] [{:<5}] [{}] {}", log.level, log.target, log.message - ); + ) } else { let mut fields_str = String::new(); let mut entries: Vec<_> = log.fields.iter().collect(); @@ -7141,10 +7145,10 @@ fn print_log_line(log: &openshell_core::proto::SandboxLogLine) { fields_str.push('='); fields_str.push_str(v); } - println!( + format!( "[{secs}.{millis:03}] [{source:<7}] [{:<5}] [{}] {} {}", log.level, log.target, log.message, fields_str - ); + ) } } @@ -7509,7 +7513,7 @@ fn format_endpoint(endpoint: &openshell_core::proto::NetworkEndpoint) -> String mod tests { use super::{ PolicyGetView, ProvisioningStep, build_sandbox_resource_limits, - dockerfile_sources_supported_for_gateway, format_endpoint, + dockerfile_sources_supported_for_gateway, format_endpoint, format_log_line, format_provider_attachment_table, git_sync_files, has_main_process_result, inferred_provider_type, parse_cli_setting_value, parse_credential_expiry_cli_value, parse_credential_expiry_pairs, parse_credential_pairs, parse_driver_config_json, @@ -8974,4 +8978,106 @@ mod tests { assert!(json["revision"].is_null()); assert!(json["policy"].is_null()); } + + fn log_line( + level: &str, + target: &str, + message: &str, + source: &str, + fields: &[(&str, &str)], + ) -> openshell_core::proto::SandboxLogLine { + openshell_core::proto::SandboxLogLine { + sandbox_id: "sb-1".to_string(), + timestamp_ms: 1_234_567, + level: level.to_string(), + target: target.to_string(), + message: message.to_string(), + source: source.to_string(), + fields: fields + .iter() + .map(|(k, v)| ((*k).to_string(), (*v).to_string())) + .collect(), + } + } + + #[test] + fn format_log_line_without_fields() { + let log = log_line("INFO", "openshell_server", "hello world", "sandbox", &[]); + assert_eq!( + format_log_line(&log), + "[1234.567] [sandbox] [INFO ] [openshell_server] hello world" + ); + } + + #[test] + fn format_log_line_empty_source_defaults_to_gateway() { + let log = log_line("WARN", "t", "msg", "", &[]); + assert_eq!( + format_log_line(&log), + "[1234.567] [gateway] [WARN ] [t] msg" + ); + } + + #[test] + fn format_log_line_pads_source_and_level() { + let log = log_line("OCSF", "ocsf", "NET:OPEN", "gateway", &[]); + assert_eq!( + format_log_line(&log), + "[1234.567] [gateway] [OCSF ] [ocsf] NET:OPEN" + ); + + let short_source = log_line("ERROR", "t", "m", "vm", &[]); + assert_eq!( + format_log_line(&short_source), + "[1234.567] [vm ] [ERROR] [t] m" + ); + } + + #[test] + fn format_log_line_sorts_fields_alphabetically() { + let log = log_line( + "INFO", + "ocsf", + "CONNECT", + "sandbox", + &[("dst_port", "443"), ("action", "allow"), ("dst_host", "x")], + ); + assert_eq!( + format_log_line(&log), + "[1234.567] [sandbox] [INFO ] [ocsf] CONNECT action=allow dst_host=x dst_port=443" + ); + } + + #[test] + fn format_log_line_keeps_empty_field_values() { + let log = log_line("INFO", "t", "m", "sandbox", &[("a", ""), ("b", "1")]); + assert_eq!( + format_log_line(&log), + "[1234.567] [sandbox] [INFO ] [t] m a= b=1" + ); + } + + #[test] + fn format_log_line_renders_empty_target_as_empty_brackets() { + let log = log_line("INFO", "", "m", "sandbox", &[]); + assert_eq!(format_log_line(&log), "[1234.567] [sandbox] [INFO ] [] m"); + } + + #[test] + fn format_log_line_zero_pads_millis() { + let mut log = log_line("INFO", "t", "m", "sandbox", &[]); + log.timestamp_ms = 1_000_007; + assert_eq!(format_log_line(&log), "[1000.007] [sandbox] [INFO ] [t] m"); + + log.timestamp_ms = 0; + assert_eq!(format_log_line(&log), "[0.000] [sandbox] [INFO ] [t] m"); + } + + #[test] + fn format_log_line_preserves_message_verbatim() { + // OCSF shorthand must pass through unchanged. + let message = "NET:OPEN [MED] DENIED /usr/bin/curl(4711) -> api.example.com:443"; + let log = log_line("OCSF", "ocsf", message, "sandbox", &[]); + assert!(format_log_line(&log).ends_with(message)); + } } diff --git a/crates/openshell-ocsf/tests/roundtrip.rs b/crates/openshell-ocsf/tests/roundtrip.rs new file mode 100644 index 0000000000..1c8a8bb307 --- /dev/null +++ b/crates/openshell-ocsf/tests/roundtrip.rs @@ -0,0 +1,221 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! `OcsfEvent` JSON round-trip fidelity. +//! +//! `Serialize` is written by hand and `Deserialize` dispatches on `class_uid` +//! into independent per-variant paths, so a field can serialize correctly and +//! still be dropped or rejected on the way back in. + +use std::net::{IpAddr, Ipv4Addr}; + +use openshell_ocsf::{ + ActionId, ActivityId, AiModel, ApiActivityBuilder, AppLifecycleBuilder, Attack, AuthTypeId, + BaseEventBuilder, ConfidenceId, ConfigStateChangeBuilder, ConnectionInfo, + DetectionFindingBuilder, DispositionId, Endpoint, FindingInfo, HttpActivityBuilder, HttpMethod, + HttpRequest, HttpResponse, LaunchTypeId, NetworkActivityBuilder, OcsfEvent, Process, + ProcessActivityBuilder, RiskLevelId, SandboxContext, SecurityLevelId, SeverityId, + SshActivityBuilder, StateId, StatusId, Url, +}; + +fn ctx() -> SandboxContext { + SandboxContext { + sandbox_id: "sb-7f3a9c2e14b8".to_string(), + sandbox_name: "agent-workspace-01".to_string(), + container_image: "ghcr.io/nvidia/openshell/sandbox:0.42.1".to_string(), + hostname: "openshell-sb-7f3a9c2e14b8".to_string(), + product_version: "0.42.1".to_string(), + proxy_ip: IpAddr::V4(Ipv4Addr::LOCALHOST), + proxy_port: 8888, + } +} + +/// Assert an event survives `to_json -> from_value -> to_json` unchanged. +fn assert_round_trips(label: &str, event: &OcsfEvent) { + let json = event.to_json().expect("serialize"); + + let decoded: OcsfEvent = serde_json::from_value(json.clone()) + .unwrap_or_else(|e| panic!("{label}: deserialize failed: {e}\njson: {json}")); + + let reserialized = decoded.to_json().expect("re-serialize"); + assert_eq!( + json, reserialized, + "{label}: JSON changed across round trip" + ); +} + +#[test] +fn network_activity_round_trips() { + let event = NetworkActivityBuilder::new(&ctx()) + .activity(ActivityId::Open) + .activity_name("Open") + .action(ActionId::Denied) + .disposition(DispositionId::Blocked) + .severity(SeverityId::Medium) + .status(StatusId::Failure) + .dst_endpoint(Endpoint::from_domain("api.example.com", 443)) + .src_endpoint_addr(IpAddr::V4(Ipv4Addr::new(10, 0, 0, 5)), 51234) + .actor_process( + Process::new("/usr/bin/curl", 4711) + .with_cmd_line("curl -sS https://api.example.com") + .with_parent(Process::new("/bin/bash", 4700)), + ) + .firewall_rule("default-deny-egress", "opa") + .connection_info(ConnectionInfo::new("tcp")) + .observation_point(3) + .status_detail("blocked by egress policy") + .log_source("/dev/kmsg") + .message("CONNECT denied api.example.com:443") + .unmapped("policy_version", 42) + .unmapped("engine", "opa") + .build(); + + assert_round_trips("network_activity", &event); +} + +#[test] +fn http_activity_round_trips() { + let event = HttpActivityBuilder::new(&ctx()) + .activity(ActivityId::Open) + .action(ActionId::Allowed) + .disposition(DispositionId::Allowed) + .severity(SeverityId::Informational) + .status(StatusId::Success) + .http_request(HttpRequest { + http_method: HttpMethod::Post, + url: Some(Url::new("https", "api.example.com", "/v1/items", 443)), + }) + .http_response(HttpResponse { code: 201 }) + .src_endpoint(Endpoint::from_ip( + IpAddr::V4(Ipv4Addr::new(10, 0, 0, 5)), + 51235, + )) + .dst_endpoint(Endpoint::from_domain("api.example.com", 443)) + .actor_process(Process::new("/usr/bin/node", 4712)) + .firewall_rule("allow-api", "l7") + .status_detail("allowed by L7 rule") + .message("POST /v1/items 201") + .unmapped("l7_decision", "allow") + .build(); + + assert_round_trips("http_activity", &event); +} + +#[test] +fn ssh_activity_round_trips() { + let event = SshActivityBuilder::new(&ctx()) + .activity(ActivityId::Open) + .auth_type(AuthTypeId::Other, "publickey-nonce") + .protocol_ver("SSH-2.0-OpenSSH_9.6") + .severity(SeverityId::Informational) + .status(StatusId::Success) + .src_endpoint_addr(IpAddr::V4(Ipv4Addr::new(10, 0, 0, 9)), 44321) + .dst_endpoint(Endpoint::from_domain("sandbox.local", 22)) + .message("ssh session accepted") + .build(); + + assert_round_trips("ssh_activity", &event); +} + +#[test] +fn process_activity_round_trips() { + let event = ProcessActivityBuilder::new(&ctx()) + .activity(ActivityId::Open) + .process( + Process::new("/usr/bin/python3", 4713) + .with_cmd_line("python3 -m pytest") + .with_parent(Process::new("/bin/sh", 4701)), + ) + .launch_type(LaunchTypeId::Other) + .exit_code(0) + .severity(SeverityId::Informational) + .status(StatusId::Success) + .message("process started") + .build(); + + assert_round_trips("process_activity", &event); +} + +#[test] +fn detection_finding_round_trips() { + let event = DetectionFindingBuilder::new(&ctx()) + .finding_info( + FindingInfo::new("finding-001", "Sandbox bypass attempt") + .with_desc("Process attempted to reach the host network directly"), + ) + .severity(SeverityId::High) + .is_alert(true) + .confidence(ConfidenceId::High) + .risk_level(RiskLevelId::High) + .attack(Attack::mitre( + "T1046", + "Network Service Discovery", + "TA0007", + "Discovery", + )) + .evidence_pairs(&[("dst_host", "169.254.169.254"), ("dst_port", "80")]) + .evidence("binary", "/usr/bin/curl") + .remediation("Tighten the egress policy for this sandbox") + .log_source("/dev/kmsg") + .message("bypass attempt detected") + .unmapped("detector", "bypass_monitor") + .build(); + + assert_round_trips("detection_finding", &event); +} + +#[test] +fn application_lifecycle_round_trips() { + let event = AppLifecycleBuilder::new(&ctx()) + .activity(ActivityId::Open) + .severity(SeverityId::Informational) + .message("supervisor started") + .build(); + + assert_round_trips("application_lifecycle", &event); +} + +#[test] +fn device_config_state_change_round_trips() { + let event = ConfigStateChangeBuilder::new(&ctx()) + .state(StateId::Other, "policy-loaded") + .security_level(SecurityLevelId::Secure) + .prev_security_level(SecurityLevelId::AtRisk) + .severity(SeverityId::Informational) + .status(StatusId::Success) + .message("policy reloaded") + .unmapped("policy_version", 7) + .build(); + + assert_round_trips("device_config_state_change", &event); +} + +#[test] +fn api_activity_round_trips() { + let event = ApiActivityBuilder::new(&ctx(), "chat.completions") + .severity(SeverityId::Informational) + .status(StatusId::Success) + .http_request(HttpRequest { + http_method: HttpMethod::Post, + url: Some(Url::new("https", "inference.local", "/v1/chat", 443)), + }) + .dst_endpoint(Endpoint::from_domain("inference.local", 443)) + .ai_model(AiModel::new("llama-3.1-8b", "nvidia")) + .message("inference request routed") + .unmapped("route", "system") + .build(); + + assert_round_trips("api_activity", &event); +} + +#[test] +fn base_event_round_trips() { + let event = BaseEventBuilder::new(&ctx()) + .activity_name("custom activity") + .severity(SeverityId::Low) + .message("base event") + .unmapped("detail", "value") + .build(); + + assert_round_trips("base_event", &event); +} diff --git a/crates/openshell-supervisor-process/src/log_push.rs b/crates/openshell-supervisor-process/src/log_push.rs index 01e373ba8e..256fbff4a4 100644 --- a/crates/openshell-supervisor-process/src/log_push.rs +++ b/crates/openshell-supervisor-process/src/log_push.rs @@ -27,10 +27,7 @@ pub struct LogPushLayer { impl LogPushLayer { pub fn new(sandbox_id: String, tx: mpsc::Sender) -> Self { - let max_level = std::env::var("OPENSHELL_LOG_PUSH_LEVEL") - .ok() - .and_then(|s| s.parse().ok()) - .unwrap_or(tracing::Level::INFO); + let max_level = parse_max_level(std::env::var("OPENSHELL_LOG_PUSH_LEVEL").ok().as_deref()); Self { sandbox_id, tx, @@ -39,6 +36,12 @@ impl LogPushLayer { } } +/// Resolve the push level filter, defaulting to `INFO` when unset or unparseable. +fn parse_max_level(raw: Option<&str>) -> tracing::Level { + raw.and_then(|s| s.parse().ok()) + .unwrap_or(tracing::Level::INFO) +} + impl Layer for LogPushLayer { fn on_event(&self, event: &Event<'_>, _ctx: Context<'_, S>) { let meta = event.metadata(); @@ -309,3 +312,209 @@ impl tracing::field::Visit for LogVisitor { } } } + +#[cfg(test)] +mod tests { + use super::*; + use openshell_ocsf::{ + ActionId, ActivityId, DispositionId, Endpoint, NetworkActivityBuilder, SandboxContext, + SeverityId, StatusId, ocsf_emit, + }; + use tracing_subscriber::layer::SubscriberExt; + + fn ocsf_ctx() -> SandboxContext { + SandboxContext { + sandbox_id: "sb-test".to_string(), + sandbox_name: "test-sandbox".to_string(), + container_image: "openshell/sandbox:test".to_string(), + hostname: "test-host".to_string(), + product_version: "0.0.0".to_string(), + proxy_ip: std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST), + proxy_port: 8888, + } + } + + /// Capture lines emitted by `f` with an `INFO` level filter. + fn capture(capacity: usize, f: impl FnOnce()) -> Vec { + let (tx, mut rx) = mpsc::channel::(capacity); + let layer = LogPushLayer { + sandbox_id: "sb-test".to_string(), + tx, + max_level: tracing::Level::INFO, + }; + let subscriber = tracing_subscriber::registry().with(layer); + tracing::subscriber::with_default(subscriber, f); + + let mut out = Vec::new(); + while let Ok(line) = rx.try_recv() { + out.push(line); + } + out + } + + #[test] + fn ocsf_events_push_shorthand_with_ocsf_level_and_no_fields() { + let event = NetworkActivityBuilder::new(&ocsf_ctx()) + .activity(ActivityId::Open) + .action(ActionId::Denied) + .disposition(DispositionId::Blocked) + .severity(SeverityId::Medium) + .status(StatusId::Failure) + .dst_endpoint(Endpoint::from_domain("blocked.example.com", 443)) + .message("CONNECT denied blocked.example.com:443".to_string()) + .build(); + let expected_shorthand = event.format_shorthand(); + + let lines = capture(16, || ocsf_emit!(event)); + + assert_eq!(lines.len(), 1); + let line = &lines[0]; + assert_eq!(line.level, "OCSF"); + assert_eq!(line.target, openshell_ocsf::OCSF_TARGET); + assert_eq!(line.source, "sandbox"); + assert_eq!(line.sandbox_id, "sb-test"); + assert_eq!(line.message, expected_shorthand); + assert!(line.fields.is_empty()); + assert!(line.timestamp_ms > 0); + } + + #[test] + fn non_ocsf_events_use_visitor_extraction() { + let lines = capture(16, || { + tracing::info!(target: "test_target", answer = 42, name = "widget", "hello"); + }); + + assert_eq!(lines.len(), 1); + let line = &lines[0]; + assert_eq!(line.level, "INFO"); + assert_eq!(line.target, "test_target"); + assert_eq!(line.source, "sandbox"); + assert_eq!(line.message, "hello"); + assert_eq!(line.fields.get("name").map(String::as_str), Some("widget")); + assert_eq!(line.fields.get("answer").map(String::as_str), Some("42")); + assert!(!line.fields.contains_key("message")); + } + + #[test] + fn events_without_a_message_field_fall_back_to_the_event_name() { + let lines = capture(16, || { + tracing::info!(target: "test_target", answer = 1); + }); + + assert_eq!(lines.len(), 1); + assert!( + lines[0].message.starts_with("event "), + "expected event-name fallback, got {:?}", + lines[0].message + ); + } + + #[test] + fn events_below_the_max_level_are_filtered() { + let lines = capture(16, || { + tracing::debug!(target: "test_target", "debug line"); + tracing::trace!(target: "test_target", "trace line"); + tracing::info!(target: "test_target", "info line"); + tracing::warn!(target: "test_target", "warn line"); + }); + + let messages: Vec<_> = lines.iter().map(|l| l.message.as_str()).collect(); + assert_eq!(messages, vec!["info line", "warn line"]); + } + + #[test] + fn lines_are_dropped_when_the_channel_is_full() { + let lines = capture(2, || { + for i in 0..3 { + tracing::info!(target: "test_target", "line {i}"); + } + }); + + assert_eq!(lines.len(), 2); + assert_eq!(lines[0].message, "line 0"); + assert_eq!(lines[1].message, "line 1"); + } + + #[test] + fn parse_max_level_defaults_to_info() { + assert_eq!(parse_max_level(None), tracing::Level::INFO); + assert_eq!(parse_max_level(Some("not-a-level")), tracing::Level::INFO); + assert_eq!(parse_max_level(Some("debug")), tracing::Level::DEBUG); + assert_eq!(parse_max_level(Some("TRACE")), tracing::Level::TRACE); + assert_eq!(parse_max_level(Some("warn")), tracing::Level::WARN); + } + + fn test_line(message: &str) -> SandboxLogLine { + SandboxLogLine { + sandbox_id: "sb-test".to_string(), + timestamp_ms: 1, + level: "INFO".to_string(), + target: "t".to_string(), + message: message.to_string(), + source: "sandbox".to_string(), + fields: std::collections::HashMap::new(), + } + } + + #[tokio::test] + async fn drain_during_backoff_buffers_up_to_the_cap_and_drops_the_rest() { + let (tx, mut rx) = mpsc::channel::(1024); + for i in 0..250 { + tx.try_send(test_line(&format!("line {i}"))).unwrap(); + } + drop(tx); + + let mut batch = Vec::new(); + drain_during_backoff(&mut rx, &mut batch, tokio::time::Duration::from_secs(30)).await; + + assert_eq!(batch.len(), 200); + assert_eq!(batch[0].message, "line 0"); + assert_eq!(batch[199].message, "line 199"); + } + + #[tokio::test] + async fn drain_during_backoff_preserves_an_existing_batch() { + let (tx, mut rx) = mpsc::channel::(16); + tx.try_send(test_line("new")).unwrap(); + drop(tx); + + let mut batch = vec![test_line("buffered")]; + drain_during_backoff(&mut rx, &mut batch, tokio::time::Duration::from_secs(30)).await; + + assert_eq!(batch.len(), 2); + assert_eq!(batch[0].message, "buffered"); + assert_eq!(batch[1].message, "new"); + } + + #[tokio::test] + async fn drain_during_backoff_returns_early_when_the_channel_closes() { + let (tx, mut rx) = mpsc::channel::(16); + tx.try_send(test_line("last")).unwrap(); + drop(tx); + + let mut batch = Vec::new(); + tokio::time::timeout( + tokio::time::Duration::from_secs(5), + drain_during_backoff(&mut rx, &mut batch, tokio::time::Duration::from_secs(30)), + ) + .await + .expect("closed channel should end the backoff drain"); + + assert_eq!(batch.len(), 1); + } + + #[test] + fn log_visitor_into_parts_uses_the_fallback_only_without_a_message() { + let visitor = LogVisitor { + message: Some("explicit".to_string()), + fields: vec![("k".to_string(), "v".to_string())], + }; + let (msg, fields) = visitor.into_parts("fallback"); + assert_eq!(msg, "explicit"); + assert_eq!(fields.get("k").map(String::as_str), Some("v")); + + let (msg, fields) = LogVisitor::default().into_parts("fallback"); + assert_eq!(msg, "fallback"); + assert!(fields.is_empty()); + } +} From 5c541e1e0e0cfed3a631ee438916cbc71e7b1c6b Mon Sep 17 00:00:00 2001 From: "John T. Myers" <9696606+johntmyers@users.noreply.github.com> Date: Mon, 31 Aug 2026 23:40:15 +0000 Subject: [PATCH 2/3] fix(kubernetes): prevent stop-start relay race (#3064) Signed-off-by: John Myers <9696606+johntmyers@users.noreply.github.com> --- crates/openshell-driver-kubernetes/README.md | 6 +- .../openshell-driver-kubernetes/src/driver.rs | 70 ++++++++++++++++--- crates/openshell-server/src/compute/mod.rs | 15 ++++ docs/reference/sandbox-compute-drivers.mdx | 4 +- 4 files changed, 81 insertions(+), 14 deletions(-) diff --git a/crates/openshell-driver-kubernetes/README.md b/crates/openshell-driver-kubernetes/README.md index 0d0186ae11..02dcfe5e87 100644 --- a/crates/openshell-driver-kubernetes/README.md +++ b/crates/openshell-driver-kubernetes/README.md @@ -79,9 +79,9 @@ its pod. The driver sets `spec.operatingMode: Suspended` for `v1beta1` or `spec.replicas: 0` for `v1alpha1`. Start sets `Running` or one replica for the same resource, so the replacement pod mounts the existing claim. Delete is the only lifecycle operation that removes the Sandbox resource and its owned -storage. The driver confirms the stop from the published `Suspended` -condition when available. Legacy `v1alpha1` controllers omit a zero replica -count from status, so the driver confirms that their backing pod is gone. +storage. The driver confirms the stop from both the published `Suspended` +condition and deletion of the backing pod. Legacy `v1alpha1` controllers omit +a usable stopped condition, so pod deletion alone confirms their stop. The workspace PVC size defaults to `workspace_default_storage_size`. Set `workspace_storage_class` to pin the PVC to a specific `StorageClass`; an empty diff --git a/crates/openshell-driver-kubernetes/src/driver.rs b/crates/openshell-driver-kubernetes/src/driver.rs index f4addd384a..484cd07708 100644 --- a/crates/openshell-driver-kubernetes/src/driver.rs +++ b/crates/openshell-driver-kubernetes/src/driver.rs @@ -1623,8 +1623,7 @@ impl KubernetesComputeDriver { let (agent_sandbox_api, kube_name, pod_name, namespace, stop_timeout) = self .patch_sandbox_operating_state(sandbox_id, false) .await?; - let legacy_pod_api = (agent_sandbox_api.resource.version == SANDBOX_VERSION_V1ALPHA1) - .then(|| Api::::namespaced(self.client.clone(), &namespace)); + let pod_api = Api::::namespaced(self.client.clone(), &namespace); let deadline = tokio::time::Instant::now() + stop_timeout; let mut poll_interval = STOP_INITIAL_POLL_INTERVAL; @@ -1649,17 +1648,18 @@ impl KubernetesComputeDriver { )) })? .map_err(KubernetesDriverError::from_kube)?; - if kubernetes_sandbox_has_stopped_condition(&object) { - return Ok(()); - } if let Some(error) = kubernetes_sandbox_stop_failure(&object) { return Err(KubernetesDriverError::Message(error)); } - if let Some(pod_api) = legacy_pod_api.as_ref() - && kubernetes_sandbox_pod_is_gone(pod_api, &pod_name, deadline) - .await - .map_err(KubernetesDriverError::Message)? - { + let pod_is_gone = kubernetes_sandbox_pod_is_gone(&pod_api, &pod_name, deadline) + .await + .map_err(KubernetesDriverError::Message)?; + let stop_is_complete = kubernetes_sandbox_stop_is_complete( + &agent_sandbox_api.resource.version, + &object, + pod_is_gone, + ); + if stop_is_complete { return Ok(()); } let now = tokio::time::Instant::now(); @@ -4560,6 +4560,19 @@ fn kubernetes_sandbox_has_stopped_condition(obj: &DynamicObject) -> bool { }) } +fn kubernetes_sandbox_stop_is_complete( + api_version: &str, + obj: &DynamicObject, + pod_is_gone: bool, +) -> bool { + if api_version == SANDBOX_VERSION_V1ALPHA1 { + // v1alpha1 omits a usable stopped condition. + pod_is_gone + } else { + kubernetes_sandbox_has_stopped_condition(obj) && pod_is_gone + } +} + fn kubernetes_sandbox_stop_failure(obj: &DynamicObject) -> Option { obj.data .get("status")? @@ -5392,6 +5405,43 @@ mod tests { assert!(kubernetes_sandbox_has_stopped_condition(&sandbox)); } + #[test] + fn beta_stop_requires_suspended_condition_and_deleted_pod() { + let resource = ApiResource::from_gvk(&GroupVersionKind::gvk( + SANDBOX_GROUP, + SANDBOX_VERSION_V1BETA1, + SANDBOX_KIND, + )); + let mut sandbox = DynamicObject::new("sandbox", &resource); + + assert!(!kubernetes_sandbox_stop_is_complete( + SANDBOX_VERSION_V1BETA1, + &sandbox, + true, + )); + + sandbox.data = serde_json::json!({ + "status": { + "conditions": [{"type": "Suspended", "status": "True"}] + } + }); + assert!(!kubernetes_sandbox_stop_is_complete( + SANDBOX_VERSION_V1BETA1, + &sandbox, + false, + )); + assert!(kubernetes_sandbox_stop_is_complete( + SANDBOX_VERSION_V1BETA1, + &sandbox, + true, + )); + assert!(kubernetes_sandbox_stop_is_complete( + SANDBOX_VERSION_V1ALPHA1, + &DynamicObject::new("sandbox", &resource), + true, + )); + } + #[test] fn stop_failure_only_rejects_terminal_suspension_condition() { let resource = ApiResource::from_gvk(&GroupVersionKind::gvk( diff --git a/crates/openshell-server/src/compute/mod.rs b/crates/openshell-server/src/compute/mod.rs index 3181f339a9..2dd1f7cd2e 100644 --- a/crates/openshell-server/src/compute/mod.rs +++ b/crates/openshell-server/src/compute/mod.rs @@ -3183,6 +3183,17 @@ impl ComputeRuntime { else { return Ok(()); }; + let phase = SandboxPhase::try_from(sandbox.phase()).unwrap_or(SandboxPhase::Unknown); + if matches!( + phase, + SandboxPhase::Deleting | SandboxPhase::Stopping | SandboxPhase::Stopped + ) { + // Lifecycle shutdown intentionally discards the canonical process + // result. Finalization must still acknowledge that discarded + // result so the supervisor can exit before the compute backend's + // termination grace period expires. + return Ok(()); + } let Some(status) = sandbox.status.as_ref() else { return Err("main-process exit has not been reported".to_string()); }; @@ -5600,6 +5611,10 @@ mod tests { .main_process_exited(id, "instance-1", 143) .await .unwrap(); + runtime + .finalize_main_process_exit(id, "instance-1") + .await + .expect("intentional shutdown finalization should be acknowledged"); let stored = runtime .store diff --git a/docs/reference/sandbox-compute-drivers.mdx b/docs/reference/sandbox-compute-drivers.mdx index 03da703ee4..82aa68a956 100644 --- a/docs/reference/sandbox-compute-drivers.mdx +++ b/docs/reference/sandbox-compute-drivers.mdx @@ -436,7 +436,9 @@ The Kubernetes driver creates namespaced `agents.x-k8s.io` `Sandbox` resources f Stop patches the existing resource rather than deleting it. For `v1beta1`, the driver sets `spec.operatingMode` to `Suspended` or `Running`. For `v1alpha1`, it sets `spec.replicas` to `0` or `1`. The Sandbox resource and its -workspace PVC keep their identity across both operations. +workspace PVC keep their identity across both operations. Stop returns only +after the controller reports suspension and deletes the old pod, so an +immediate start cannot race the prior pod's termination. If Agent Sandbox is upgraded in place, restart the OpenShell gateway after the controller and CRD rollout completes so the gateway can detect the served API versions again. From 8ffc6c2a13cd482dea9e2195058309344c274756 Mon Sep 17 00:00:00 2001 From: "John T. Myers" <9696606+johntmyers@users.noreply.github.com> Date: Tue, 1 Sep 2026 01:04:13 +0000 Subject: [PATCH 3/3] fix(policy): compose advisor proposals with provider endpoints (#2935) Signed-off-by: John Myers <9696606+johntmyers@users.noreply.github.com> --- architecture/security-policy.md | 16 +++++ crates/openshell-policy/src/ambiguity.rs | 15 ++-- crates/openshell-policy/src/merge.rs | 44 ++++++++++-- crates/openshell-server/src/grpc/policy.rs | 72 ++++++++++++++++--- .../src/policy_local.rs | 1 + docs/sandboxes/policies.mdx | 2 + docs/sandboxes/policy-advisor.mdx | 21 +++++- 7 files changed, 151 insertions(+), 20 deletions(-) diff --git a/architecture/security-policy.md b/architecture/security-policy.md index 3f582eb25d..9203ba3178 100644 --- a/architecture/security-policy.md +++ b/architecture/security-policy.md @@ -268,6 +268,22 @@ After any successful policy write, pending chunks already covered by the new live effective policy are rejected as redundant. This keeps the review inbox aligned with what the sandbox currently enforces. +Endpoint and binary advisor markers are provenance, not authorization or +connection metadata. Provider- or user-authored declarations carry explicit +provenance; `policy.local` declarations carry advisor provenance. A difference +in endpoint provenance alone is compatible during effective-policy ambiguity +validation. When identical endpoint or binary identities merge, an explicit +declaration dominates an advisor declaration. Proposal coverage likewise +ignores provenance so an approved overlay converges when an existing explicit +declaration already supplies the same identity. + +This compatibility does not weaken SSRF classification. Exact-host trust +requires one matching rule to contain both an exact explicit endpoint and an +explicit binary identity. An advisor-only endpoint or binary cannot assemble +that trust from unrelated rules. A provider rule may independently establish +trust for its own explicit endpoint and binary pair, but an advisor overlay +does not broaden that pair to a different binary. + ### Security-notes gate Separately from the prover, each chunk carries advisory `security_notes`. diff --git a/crates/openshell-policy/src/ambiguity.rs b/crates/openshell-policy/src/ambiguity.rs index 5c2b9d9177..2c0b1b1944 100644 --- a/crates/openshell-policy/src/ambiguity.rs +++ b/crates/openshell-policy/src/ambiguity.rs @@ -181,12 +181,6 @@ fn connection_conflicts(left: &NetworkEndpoint, right: &NetworkEndpoint) -> Vec< &normalized_strings(&left.allowed_ips), &normalized_strings(&right.allowed_ips), ); - push_conflict( - &mut conflicts, - "advisor_proposed", - &left.advisor_proposed, - &right.advisor_proposed, - ); conflicts } @@ -787,6 +781,15 @@ mod tests { assert!(find_endpoint_ambiguities(&policy_with(left, right)).is_empty()); } + #[test] + fn advisor_provenance_does_not_make_endpoints_ambiguous() { + let explicit = endpoint("api.example.com", 443); + let mut proposed = explicit.clone(); + proposed.advisor_proposed = true; + + assert!(find_endpoint_ambiguities(&policy_with(explicit, proposed)).is_empty()); + } + #[test] fn plain_l4_endpoint_does_not_compete_with_l7_endpoint_metadata() { let left = endpoint("api.example.com", 443); diff --git a/crates/openshell-policy/src/merge.rs b/crates/openshell-policy/src/merge.rs index 12026bbea3..a87defa340 100644 --- a/crates/openshell-policy/src/merge.rs +++ b/crates/openshell-policy/src/merge.rs @@ -632,7 +632,8 @@ fn endpoint_attributes_cover(loaded: &NetworkEndpoint, proposed: &NetworkEndpoin return false; } - // Widened fields (list appends and `|=` flags) use containment: merging + // Widened fields (list appends and authorization flags) use containment: + // merging // into an endpoint that already carries them leaves the loaded copy a // superset of the proposal, so equality would report "not covered" for a // proposal that did land. @@ -648,7 +649,6 @@ fn endpoint_attributes_cover(loaded: &NetworkEndpoint, proposed: &NetworkEndpoin loaded.request_body_credential_rewrite, proposed.request_body_credential_rewrite, ) - && flag_covers(loaded.advisor_proposed, proposed.advisor_proposed) // Fields the merge neither widens nor retains: it drops them entirely. // An unset proposal value asks for nothing and is satisfied by whatever // is loaded; a set value that differs was dropped, so the proposal is @@ -1374,7 +1374,11 @@ fn merge_endpoint( existing.websocket_credential_rewrite |= incoming.websocket_credential_rewrite; existing.request_body_credential_rewrite |= incoming.request_body_credential_rewrite; existing.allow_uninspected_credentials |= incoming.allow_uninspected_credentials; - existing.advisor_proposed |= incoming.advisor_proposed; + // Provenance is not an authorization bit. If either declaration came + // directly from a user or provider, keep the endpoint explicit. This + // mirrors binary provenance and prevents an advisor overlay from tainting + // an already explicit endpoint for exact-host SSRF evaluation. + existing.advisor_proposed &= incoming.advisor_proposed; normalize_endpoint(existing); Ok(()) } @@ -3025,7 +3029,7 @@ mod tests { } #[test] - fn policy_coverage_requires_endpoint_advisor_provenance_to_be_loaded() { + fn policy_coverage_ignores_endpoint_advisor_provenance() { let loaded_endpoint = endpoint("api.example.com", 443); let mut proposed_endpoint = loaded_endpoint.clone(); proposed_endpoint.advisor_proposed = true; @@ -3036,7 +3040,37 @@ mod tests { let proposed = rule_with_authorizations("proposed", vec![proposed_endpoint], &["/usr/bin/client"]); - assert!(!policy_covers_rule(&loaded, &proposed)); + assert!(policy_covers_rule(&loaded, &proposed)); + } + + #[test] + fn explicit_endpoint_provenance_wins_in_either_merge_order() { + let explicit_endpoint = endpoint("api.example.com", 443); + let mut proposed_endpoint = explicit_endpoint.clone(); + proposed_endpoint.advisor_proposed = true; + + for (existing_endpoint, incoming_endpoint) in [ + (explicit_endpoint.clone(), proposed_endpoint.clone()), + (proposed_endpoint, explicit_endpoint), + ] { + let incoming = + rule_with_authorizations("api", vec![incoming_endpoint], &["/usr/bin/client"]); + let merged = merge_policy( + policy_with_rule( + "api", + rule_with_authorizations("api", vec![existing_endpoint], &["/usr/bin/client"]), + ), + &[PolicyMergeOp::AddRule { + rule_name: "api".to_string(), + rule: incoming.clone(), + }], + ) + .expect("compatible explicit and advisor rules should merge"); + + let endpoint = &merged.policy.network_policies["api"].endpoints[0]; + assert!(!endpoint.advisor_proposed); + assert!(policy_covers_rule(&merged.policy, &incoming)); + } } #[test] diff --git a/crates/openshell-server/src/grpc/policy.rs b/crates/openshell-server/src/grpc/policy.rs index 0bda93a15f..6db1d12cc5 100644 --- a/crates/openshell-server/src/grpc/policy.rs +++ b/crates/openshell-server/src/grpc/policy.rs @@ -11378,7 +11378,7 @@ mod tests { } #[tokio::test] - async fn approve_all_skips_later_batch_conflict_and_applies_compatible_prefix() { + async fn approve_all_skips_later_tls_conflict_and_applies_compatible_prefix() { let state = test_server_state().await; let sandbox_id = "sb-approve-all-conflict"; let sandbox_name = "approve-all-conflict"; @@ -11425,6 +11425,7 @@ mod tests { endpoints: vec![NetworkEndpoint { host: "shared.example.com".to_string(), port: 443, + tls: "skip".to_string(), advisor_proposed: true, ..Default::default() }], @@ -14400,10 +14401,11 @@ mod tests { .await .unwrap(); + let sandbox_id = "sb-agent-provider-effective-policy"; let sandbox_name = "agent-provider-effective-policy".to_string(); let mut sandbox = Sandbox { metadata: Some(openshell_core::proto::datamodel::v1::ObjectMeta { - id: "sb-agent-provider-effective-policy".to_string(), + id: sandbox_id.to_string(), name: sandbox_name.clone(), created_at_ms: 1_000_000, labels: HashMap::new(), @@ -14429,6 +14431,7 @@ mod tests { sandbox.set_phase(SandboxPhase::Ready as i32); state.store.put_message(&sandbox).await.unwrap(); + #[allow(deprecated)] let proposed_rule = NetworkPolicyRule { name: "github_contents_write".to_string(), endpoints: vec![NetworkEndpoint { @@ -14446,15 +14449,16 @@ mod tests { ..Default::default() }), }], + advisor_proposed: true, ..Default::default() }], binaries: vec![NetworkBinary { path: "/usr/bin/curl".to_string(), - ..Default::default() + harness: true, }], }; - handle_submit_policy_analysis( + let submit = handle_submit_policy_analysis( &state, with_user(Request::new(SubmitPolicyAnalysisRequest { name: sandbox_name.clone(), @@ -14469,12 +14473,16 @@ mod tests { })), ) .await - .unwrap(); + .unwrap() + .into_inner(); + assert_eq!(submit.accepted_chunks, 1); + assert_eq!(submit.rejected_chunks, 0); + let chunk_id = submit.accepted_chunk_ids[0].clone(); let draft = handle_get_draft_policy( &state, with_user(Request::new(GetDraftPolicyRequest { - name: sandbox_name, + name: sandbox_name.clone(), status_filter: String::new(), workspace: "default".to_string(), })), @@ -14482,7 +14490,13 @@ mod tests { .await .unwrap() .into_inner(); - let verdict = &draft.chunks[0].validation_result; + let chunk = draft + .chunks + .iter() + .find(|chunk| chunk.id == chunk_id) + .expect("provider-overlap proposal should reach the draft inbox"); + assert_eq!(chunk.status, "pending"); + let verdict = &chunk.validation_result; let first_line = verdict.lines().next().unwrap_or(""); assert!( first_line.starts_with("prover: "), @@ -14492,7 +14506,49 @@ mod tests { assert!( !verdict.contains("validation unavailable"), "providers-v2 composition must not break the prover pipeline; \ - got: {verdict}" + got: {verdict}" + ); + + handle_approve_draft_chunk( + &state, + authed_request(ApproveDraftChunkRequest { + name: sandbox_name, + chunk_id, + workspace: "default".to_string(), + review_token: chunk.review_token.clone(), + }), + ) + .await + .expect("provider-overlap proposal should approve"); + + let stored = state + .store + .get_latest_policy(sandbox_id) + .await + .unwrap() + .expect("approval should persist a base-policy revision"); + let base_policy = ProtoSandboxPolicy::decode(stored.policy_payload.as_slice()).unwrap(); + assert!( + base_policy + .network_policies + .contains_key("github_contents_write") + ); + assert!( + !base_policy + .network_policies + .contains_key("_provider_work_custom"), + "provider-composed rules must not be copied into the mutable base policy" + ); + + let effective_policy = get_sandbox_policy(&state, sandbox_id).await; + let provider_rule = &effective_policy.network_policies["_provider_work_custom"]; + assert_eq!(provider_rule.endpoints[0].access, "full"); + assert_eq!(provider_rule.endpoints[0].deny_rules.len(), 1); + assert!(!provider_rule.endpoints[0].advisor_proposed); + assert!( + effective_policy + .network_policies + .contains_key("github_contents_write") ); } diff --git a/crates/openshell-supervisor-network/src/policy_local.rs b/crates/openshell-supervisor-network/src/policy_local.rs index 908587ed31..ef899b666e 100644 --- a/crates/openshell-supervisor-network/src/policy_local.rs +++ b/crates/openshell-supervisor-network/src/policy_local.rs @@ -1440,6 +1440,7 @@ mod tests { assert_eq!(rule.endpoints[0].port, 443); assert_eq!(rule.endpoints[0].ports, vec![443]); assert_eq!(rule.endpoints[0].protocol, "rest"); + assert!(rule.endpoints[0].advisor_proposed); #[allow(deprecated)] { assert!(rule.binaries[0].harness); diff --git a/docs/sandboxes/policies.mdx b/docs/sandboxes/policies.mdx index a85bbd9b9d..16202751f8 100644 --- a/docs/sandboxes/policies.mdx +++ b/docs/sandboxes/policies.mdx @@ -236,6 +236,8 @@ The following steps outline the hot-reload policy update workflow. OpenShell validates a complete candidate policy before activating any part of it. Endpoints may overlap when their connection and request-processing metadata agree. For example, two `api.example.com:443` REST entries can contribute different allow and deny rules when they use the same TLS, destination, credential, parser, and enforcement settings. A plain L4 endpoint may overlap an L7 endpoint because it authorizes the destination without contributing request-processing metadata. A more-specific path endpoint may override request-processing metadata from a broader endpoint, such as a `/graphql` GraphQL endpoint alongside a general REST endpoint for the same host. OpenShell rejects the candidate when overlapping exact or wildcard host selectors can both contribute equally specific endpoint configuration and disagree on those fields. +Internal policy-advisor provenance does not make otherwise compatible endpoints ambiguous. This lets an advisor proposal extend a provider-covered host without modifying the provider rule. TLS, destination IP constraints, credential handling, protocol, parser, and equally specific enforcement settings must still agree. + When the gateway knows the affected sandbox scope, it validates the complete effective candidate before persistence. This covers direct policy replacement, incremental merges and proposal approvals, provider attachment, and diff --git a/docs/sandboxes/policy-advisor.mdx b/docs/sandboxes/policy-advisor.mdx index b4d607cb33..35e0073ec3 100644 --- a/docs/sandboxes/policy-advisor.mdx +++ b/docs/sandboxes/policy-advisor.mdx @@ -131,6 +131,25 @@ OpenShell has two proposal paths: | Mechanistic mapper | Aggregated denial summaries from the sandbox. | Groups by host, port, and binary. If L7 request samples are available, it can draft REST method and path rules. Otherwise it drafts an L4 endpoint. | | Agent-authored proposal | The in-sandbox agent, using `policy.local`. | Usually a REST `addRule` with exact host, port, binary, method, and path from the structured denial. It can also propose L4 rules for opaque protocols. | +### How proposal provenance works + +OpenShell tracks whether an endpoint and binary came from policy advisor. This is internal provenance; it is not a policy YAML field that authors set. Think of each marker as answering “who introduced this identity?” rather than “what traffic does this allow?” + +| Marker | `false` | `true` | When both declarations meet | +|---|---|---|---| +| Endpoint provenance | A user or provider explicitly declared the endpoint. | Policy advisor proposed the endpoint. | The values do not conflict by themselves. The explicit declaration wins if the endpoints merge. | +| Binary provenance | A user or provider explicitly declared the binary path. | Policy advisor proposed the binary path. | The explicit declaration wins if the same path merges. | + +For example, a GitHub provider can explicitly declare `api.github.com:443` for read operations. An agent can then propose `PUT /repos/NVIDIA/OpenShell/contents/docs/**` for the same endpoint. The provider endpoint has provenance `false`; the proposal endpoint has provenance `true`. OpenShell allows that overlap, keeps the provider rule immutable, and stores an approved write rule in the sandbox policy layer. + +Provenance does not hide a real endpoint conflict. The same two declarations still fail validation if they disagree on connection or request-processing behavior that must have one value, such as TLS mode, `allowed_ips`, an equally specific L7 protocol or parser contract, credential binding, or enforcement mode. Authorization fields such as compatible allow and deny rules can combine. + +Exact-host SSRF trust requires an exact endpoint and the matching binary identity to be explicit in the same rule. An advisor-only endpoint or binary does not create that stronger trust. For example: + +- A provider rule that explicitly declares both `/usr/bin/gh` and `api.github.com:443` already establishes exact-host trust for that pair. A later advisor proposal does not create or broaden that trust. +- If the provider declares `api.github.com:443` for `/usr/bin/gh`, but the advisor proposes the endpoint for `/usr/bin/curl`, `curl` does not inherit the provider's binary identity. Its proposed rule remains subject to the normal SSRF checks. +- If an advisor proposes `internal-api.example:443` and it resolves to a private address, approval alone is not enough. A developer must explicitly authorize the intended address range with `allowed_ips`. + For REST APIs, prefer L7 rules over broad L4 access. A good proposal allows one method and the smallest safe path: ```json @@ -172,7 +191,7 @@ For REST APIs, prefer L7 rules over broad L4 access. A good proposal allows one The current `policy.local` JSON shape covers L4 endpoints and REST method or path rules. Use [Customize Sandbox Policies](/sandboxes/policies) or [Policy Schema Reference](/reference/policy-schema) for policy fields that are not part of the agent-authored proposal surface, such as WebSocket credential rewrite, GraphQL operation matching, endpoint path scoping, and provider-owned policy bundles. -Policy advisor proposals do not add `allowed_ips` automatically. If an advisor-proposed hostname resolves to an internal or private address, OpenShell's SSRF protections still block the connection until a developer explicitly adds the required `allowed_ips` entry. Exact hostname trust for user-declared policy endpoints does not apply to advisor-generated proposal binaries. +Policy advisor proposals do not add `allowed_ips` automatically. If an advisor-proposed hostname resolves to an internal or private address, OpenShell's SSRF protections still block the connection until a developer explicitly adds the required `allowed_ips` entry. Private RFC 1918, CGNAT, IPv6 ULA, and other special-use destinations classified as internal produce advisory security notes when they appear as literal endpoint IPs or in `allowed_ips`. CIDR intersections are included, and hostless `allowed_ips` rules receive an additional warning because they can match any hostname resolving into the configured range.