From 31207d6caaf0b1c275ea779296d536e30d4430ac Mon Sep 17 00:00:00 2001 From: Kris Hicks Date: Tue, 3 Nov 2026 17:18:02 -0800 Subject: [PATCH] feat(supervisor): record launch and exit of sandbox sessions The entrypoint's launch reached only the sandbox container's stdout, and no process the runtime started had an exit event: the entrypoint's exit code reached the gateway only as sandbox state, and an exec or SSH session's status went only to its caller. The runtime is the parent of the entrypoint and of each exec or SSH session process and reaps each with its exact status, so it records their launches and exits, with the time it observed them, in a bounded log with sequence numbers. Runtimes that advertise openshell.sandbox.process-events serve the log through ReadProcessEvents, a long poll with a sequence cursor that caps each response by size and reports how many events it no longer retains. A read acknowledges the events before its cursor, and a read without one resumes after the last acknowledged event, so a replacement supervisor does not report again what its predecessor read. The supervisor reads the log for the life of the boundary and emits OCSF Process Activity: Launch with the process's pid, start time, and parent, and Terminate with its exit code, 128 plus the signal number when a signal ended it, and a Failure status when that code is not 0. Before the boundary goes away it reads once more without waiting, so the final exits are reported. Each event keeps the time the runtime observed it and a metadata.uid derived from the process instance, so the few events a replacement supervisor can report twice are ones consumers can drop. The runtime's own entrypoint Launch on stdout names the same executable path. Refs #4268 Signed-off-by: Kris Hicks --- crates/openshell-binary-identity/src/lib.rs | 25 ++ crates/openshell-ocsf/src/builders/process.rs | 47 ++- .../src/boundary_protocol.rs | 37 ++ .../src/isolation_protocol.rs | 3 + crates/openshell-sandbox-backend/src/lib.rs | 2 +- .../openshell-sandbox-backend/src/protobuf.rs | 150 ++++++- .../openshell-sandbox-backend/src/runtime.rs | 85 ++++ crates/openshell-sandbox/src/boundary_exec.rs | 48 +++ .../openshell-sandbox/src/boundary_server.rs | 45 ++- crates/openshell-sandbox/src/delegated.rs | 15 +- crates/openshell-sandbox/src/lib.rs | 2 + .../openshell-sandbox/src/process_events.rs | 379 ++++++++++++++++++ crates/openshell-supervisor/src/lib.rs | 22 +- .../src/process_activity.rs | 284 +++++++++++++ docs/observability/logging.mdx | 8 +- docs/observability/ocsf-json-export.mdx | 2 +- proto/sandbox_protocol.proto | 33 ++ 17 files changed, 1153 insertions(+), 34 deletions(-) create mode 100644 crates/openshell-sandbox/src/process_events.rs create mode 100644 crates/openshell-supervisor/src/process_activity.rs diff --git a/crates/openshell-binary-identity/src/lib.rs b/crates/openshell-binary-identity/src/lib.rs index a82dda55c9..98a668fed9 100644 --- a/crates/openshell-binary-identity/src/lib.rs +++ b/crates/openshell-binary-identity/src/lib.rs @@ -156,6 +156,19 @@ fn resolve_linux_process( }) } +/// The process `pid` names, as procfs reports it now. `None` when procfs does +/// not report it. +#[cfg(target_os = "linux")] +#[must_use] +pub fn observe_process(pid: u32) -> Option { + let (parent_pid, start_time) = process_stat(pid).ok()?; + Some(ProcessInstance { + pid: thread_group_id(pid).ok()?, + parent_pid, + start_time_ms: start_time_ms(start_time)?, + }) +} + /// The process that owns `snapshot`'s task. A connection's task can be any /// thread, so the PID and start time are the thread-group leader's. Audit /// context only: unreadable values leave the identity without a process. @@ -824,6 +837,18 @@ mod tests { assert!(now_ms - leader.start_time_ms < 600_000); } + #[test] + fn observed_process_matches_the_resolved_identity() { + let pid = std::process::id(); + let resolved = ProcfsIdentityResolver::for_process_tree(pid) + .resolve(pid) + .expect("resolve") + .process; + assert!(resolved.is_some()); + assert_eq!(observe_process(pid), resolved); + assert_eq!(observe_process(u32::MAX), None); + } + #[test] fn process_tree_root_does_not_escape_into_host_ancestry() { let pid = std::process::id(); diff --git a/crates/openshell-ocsf/src/builders/process.rs b/crates/openshell-ocsf/src/builders/process.rs index ae6a6dfe14..ed7ae2705f 100644 --- a/crates/openshell-ocsf/src/builders/process.rs +++ b/crates/openshell-ocsf/src/builders/process.rs @@ -22,6 +22,8 @@ pub struct ProcessActivityBuilder<'a, ActorState = MissingActor> { launch_type: Option, exit_code: Option, message: Option, + time_ms: Option, + uid: Option, actor_state: std::marker::PhantomData, } @@ -55,6 +57,8 @@ impl<'a> ProcessActivityBuilder<'a, MissingActor> { launch_type: None, exit_code: None, message: None, + time_ms: None, + uid: None, actor_state: std::marker::PhantomData, } } @@ -74,6 +78,8 @@ impl<'a> ProcessActivityBuilder<'a, MissingActor> { launch_type: self.launch_type, exit_code: self.exit_code, message: self.message, + time_ms: self.time_ms, + uid: self.uid, actor_state: std::marker::PhantomData, } } @@ -100,6 +106,19 @@ impl ProcessActivityBuilder<'_, ActorState> { self.exit_code = Some(code); self } + /// When the activity happened, if not when the event is built. + #[must_use] + pub fn time(mut self, time_ms: i64) -> Self { + self.time_ms = Some(time_ms); + self + } + /// Replace the random event identifier with one that repeats when the + /// same activity is reported again. + #[must_use] + pub fn uid(mut self, uid: impl Into) -> Self { + self.uid = Some(uid.into()); + self + } } impl_activity_setter!(ProcessActivityBuilder); @@ -110,6 +129,12 @@ impl ProcessActivityBuilder<'_, HasActor> { #[must_use] pub fn build(self) -> OcsfEvent { let activity_name = self.activity.process_label().to_string(); + let mut metadata = self + .ctx + .metadata(&["security_control", "container", "host"]); + if let Some(uid) = self.uid { + metadata.uid = Some(uid); + } let mut base = BaseEventData::new( 1007, "Process Activity", @@ -118,9 +143,11 @@ impl ProcessActivityBuilder<'_, HasActor> { self.activity.as_u8(), &activity_name, self.severity, - self.ctx - .metadata(&["security_control", "container", "host"]), + metadata, ); + if let Some(time_ms) = self.time_ms { + base.set_time(time_ms); + } self.ctx .apply_common_fields(&mut base, self.status, self.message); @@ -176,4 +203,20 @@ mod tests { let json = event.to_json().unwrap(); assert_eq!(json["exit_code"], 0); } + + #[test] + fn process_activity_carries_occurrence_time_and_event_uid() { + let ctx = test_sandbox_context(); + let event = ProcessActivityBuilder::new(&ctx) + .activity(ActivityId::Close) + .process(Process::new("python3", 42)) + .actor_process(Process::new("openshell-sandbox", 1)) + .time(1_793_750_401_000) + .uid("proc:42:1793750400123:exit") + .build(); + + let json = event.to_json().unwrap(); + assert_eq!(json["time"], 1_793_750_401_000_i64); + assert_eq!(json["metadata"]["uid"], "proc:42:1793750400123:exit"); + } } diff --git a/crates/openshell-sandbox-backend/src/boundary_protocol.rs b/crates/openshell-sandbox-backend/src/boundary_protocol.rs index 17aa9f9a1e..0c9ae2578d 100644 --- a/crates/openshell-sandbox-backend/src/boundary_protocol.rs +++ b/crates/openshell-sandbox-backend/src/boundary_protocol.rs @@ -862,6 +862,11 @@ pub enum Request { /// plane. OpenMediation, AcceptNetwork, + ReadProcessEvents { + /// `None` resumes after the last sequence a reader acknowledged. + after_sequence: Option, + wait: bool, + }, } impl Request { @@ -975,6 +980,14 @@ impl fmt::Debug for Request { .finish(), Self::OpenMediation => formatter.write_str("OpenMediation"), Self::AcceptNetwork => formatter.write_str("AcceptNetwork"), + Self::ReadProcessEvents { + after_sequence, + wait, + } => formatter + .debug_struct("ReadProcessEvents") + .field("after_sequence", after_sequence) + .field("wait", wait) + .finish(), } } } @@ -1040,6 +1053,30 @@ pub enum Response { kind: BoundaryErrorKind, message: String, }, + ProcessEvents { + events: Vec, + /// Events after the requested sequence that are no longer retained. + lost: u64, + }, +} + +/// A workload process the runtime started directly, launched or exited. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ProcessEventWire { + pub sequence: u64, + pub process: ProcessInstance, + pub executable: String, + pub kind: ProcessEventKindWire, + /// When the runtime observed the event, in milliseconds since the epoch. + pub time_ms: i64, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ProcessEventKindWire { + Launched, + Exited(ExitStatusWire), } /// Sandbox-monotonic timing carried across the boundary protocol. diff --git a/crates/openshell-sandbox-backend/src/isolation_protocol.rs b/crates/openshell-sandbox-backend/src/isolation_protocol.rs index 6576d8a24f..a3013651ed 100644 --- a/crates/openshell-sandbox-backend/src/isolation_protocol.rs +++ b/crates/openshell-sandbox-backend/src/isolation_protocol.rs @@ -20,6 +20,8 @@ pub const SUSPEND_RESUME_CAPABILITY: &str = "openshell.sandbox.suspend-resume"; /// runtime advertises this; an older runtime keeps rejecting replacement /// supervisors. pub const SUPERVISOR_TAKEOVER_CAPABILITY: &str = "openshell.sandbox.supervisor-takeover"; +/// Optional: the runtime serves `ReadProcessEvents`. +pub const PROCESS_EVENTS_CAPABILITY: &str = "openshell.sandbox.process-events"; const PROTOCOL_VERSION: ProtocolVersion = ProtocolVersion { major: 1, minor: 1 }; /// The built-in runtime supports fresh launches and supervisor takeover; @@ -34,6 +36,7 @@ pub fn metadata(implementation: &str) -> PeerMetadata { supported_capabilities: vec![ SANDBOX_PROTOCOL_CAPABILITY.to_string(), SUPERVISOR_TAKEOVER_CAPABILITY.to_string(), + PROCESS_EVENTS_CAPABILITY.to_string(), ], required_capabilities: required, } diff --git a/crates/openshell-sandbox-backend/src/lib.rs b/crates/openshell-sandbox-backend/src/lib.rs index 3df3f90ef7..ec838e3494 100644 --- a/crates/openshell-sandbox-backend/src/lib.rs +++ b/crates/openshell-sandbox-backend/src/lib.rs @@ -27,7 +27,7 @@ pub use runtime::{ BoundBoundary, BoundaryExec, BoundaryLaunchOutcome, BoundaryLoopbackConnector, BoundaryProcess, BoundaryTakeover, BoundaryTerminal, ConfirmedBoundary, ExecSession, MAX_RESTORE_REFERENCE_BYTES, NetworkMediationSource, OpenShellRuntimeBackend, - ProcessAttachment, ReadyBoundary, ResumeLaunch, RunningBoundary, + ProcessAttachment, ProcessEventSource, ReadyBoundary, ResumeLaunch, RunningBoundary, }; pub use runtime::{BoundaryTransport, BoundaryTransportConnector, validate_runtime_coordinates}; diff --git a/crates/openshell-sandbox-backend/src/protobuf.rs b/crates/openshell-sandbox-backend/src/protobuf.rs index aeaae1e530..2331896a33 100644 --- a/crates/openshell-sandbox-backend/src/protobuf.rs +++ b/crates/openshell-sandbox-backend/src/protobuf.rs @@ -272,17 +272,7 @@ impl WireMessage for w::BinaryIdentityWire { .iter() .map(|v| path(v)) .collect::>()?, - process: process - .map(|v| -> Result<_, FrameError> { - Ok(p::ProcessInstance { - pid: v.pid, - parent_pid: v.parent_pid, - start_time: Some(timestamp( - u64::try_from(v.start_time_ms).map_err(invalid)?, - )?), - }) - }) - .transpose()?, + process: process.as_ref().map(process_to_proto).transpose()?, }), Self::Failed { message } => R::Failed(message.clone()), }), @@ -299,17 +289,7 @@ impl WireMessage for w::BinaryIdentityWire { .map(w::ExecutableIdentityWire::from_proto) .collect::>()?, cmdline_paths: v.cmdline_paths.into_iter().map(PathBuf::from).collect(), - process: v - .process - .map(|v| -> Result<_, FrameError> { - Ok(c::ProcessInstance { - pid: v.pid, - parent_pid: v.parent_pid, - start_time_ms: i64::try_from(millis(required(v.start_time)?)?) - .map_err(invalid)?, - }) - }) - .transpose()?, + process: v.process.map(process_from_proto).transpose()?, }, R::Failed(message) => Self::Failed { message }, }) @@ -453,6 +433,51 @@ impl WireMessage for w::SessionSnapshotWire { }) } } +fn process_to_proto(v: &c::ProcessInstance) -> Result { + Ok(p::ProcessInstance { + pid: v.pid, + parent_pid: v.parent_pid, + start_time: Some(timestamp(u64::try_from(v.start_time_ms).map_err(invalid)?)?), + }) +} +fn process_from_proto(v: p::ProcessInstance) -> Result { + Ok(c::ProcessInstance { + pid: v.pid, + parent_pid: v.parent_pid, + start_time_ms: i64::try_from(millis(required(v.start_time)?)?).map_err(invalid)?, + }) +} +impl WireMessage for w::ProcessEventWire { + type Proto = p::ProcessEvent; + fn to_proto(&self) -> Result { + use p::process_event::Event as E; + Ok(p::ProcessEvent { + sequence: self.sequence, + process: Some(process_to_proto(&self.process)?), + executable: self.executable.clone(), + event: Some(match self.kind { + w::ProcessEventKindWire::Launched => E::Launched(p::ProcessLaunched {}), + w::ProcessEventKindWire::Exited(status) => E::Exited(status.to_proto()?), + }), + time: Some(timestamp(u64::try_from(self.time_ms).map_err(invalid)?)?), + }) + } + fn from_proto(v: Self::Proto) -> Result { + use p::process_event::Event as E; + Ok(Self { + sequence: v.sequence, + process: process_from_proto(required(v.process)?)?, + executable: v.executable, + kind: match required(v.event)? { + E::Launched(_) => w::ProcessEventKindWire::Launched, + E::Exited(status) => { + w::ProcessEventKindWire::Exited(w::ExitStatusWire::from_proto(status)?) + } + }, + time_ms: i64::try_from(millis(required(v.time)?)?).map_err(invalid)?, + }) + } +} fn timestamp(v: u64) -> Result { let seconds = number(v / 1000)?; if seconds > 253_402_300_799 { @@ -561,6 +586,13 @@ impl WireMessage for w::RequestEnvelope { }), W::OpenMediation => P::OpenMediation(p::OpenMediation {}), W::AcceptNetwork => P::AcceptNetwork(p::AcceptNetwork {}), + W::ReadProcessEvents { + after_sequence, + wait, + } => P::ReadProcessEvents(p::ReadProcessEvents { + after_sequence: *after_sequence, + wait: *wait, + }), }; Ok(p::RequestEnvelope { request_id: self.request_id.clone(), @@ -629,6 +661,10 @@ impl WireMessage for w::RequestEnvelope { }, P::OpenMediation(_) => W::OpenMediation, P::AcceptNetwork(_) => W::AcceptNetwork, + P::ReadProcessEvents(v) => W::ReadProcessEvents { + after_sequence: v.after_sequence, + wait: v.wait, + }, }; // The server derives a fingerprint from decoded typed fields. Clients // supply only the random ID; protobuf map order never changes a replay. @@ -714,6 +750,13 @@ impl WireMessage for w::ResponseEnvelope { kind: kind.to_proto()? as i32, message: message.clone(), }), + W::ProcessEvents { events, lost } => P::ProcessEvents(p::ProcessEvents { + events: events + .iter() + .map(WireMessage::to_proto) + .collect::>()?, + lost: *lost, + }), }; Ok(p::ResponseEnvelope { request_id: self.request_id.clone(), @@ -777,6 +820,14 @@ impl WireMessage for w::ResponseEnvelope { kind: w::BoundaryErrorKind::from_proto(enum_value(v.kind)?)?, message: v.message, }, + P::ProcessEvents(v) => W::ProcessEvents { + events: v + .events + .into_iter() + .map(w::ProcessEventWire::from_proto) + .collect::>()?, + lost: v.lost, + }, }; Ok(Self { request_id: v.request_id, @@ -998,6 +1049,61 @@ mod tests { assert!(w::BinaryIdentityWire::from_proto(missing_start).is_err()); } + #[test] + fn process_events_round_trip() { + let process = c::ProcessInstance { + pid: 57, + parent_pid: 1, + start_time_ms: 1_793_750_400_123, + }; + let response = w::ResponseEnvelope { + request_id: "r".to_string(), + response: w::Response::ProcessEvents { + events: vec![ + w::ProcessEventWire { + sequence: 4, + process, + executable: "/usr/bin/sh".to_string(), + kind: w::ProcessEventKindWire::Launched, + time_ms: 1_793_750_400_200, + }, + w::ProcessEventWire { + sequence: 5, + process, + executable: "/usr/bin/sh".to_string(), + kind: w::ProcessEventKindWire::Exited(w::ExitStatusWire::Signaled(9)), + time_ms: 1_793_750_401_000, + }, + ], + lost: 3, + }, + }; + assert_eq!( + w::ResponseEnvelope::from_proto(response.to_proto().unwrap()).unwrap(), + response + ); + + for request in [ + w::Request::ReadProcessEvents { + after_sequence: Some(3), + wait: true, + }, + w::Request::ReadProcessEvents { + after_sequence: None, + wait: false, + }, + ] { + let envelope = w::RequestEnvelope { + request_id: uuid::Uuid::new_v4().to_string(), + payload_digest: String::new(), + exec_admission_deadline_unix_ms: None, + request: request.clone(), + }; + let decoded = w::RequestEnvelope::from_proto(envelope.to_proto().unwrap()).unwrap(); + assert_eq!(decoded.request, request); + } + } + #[test] fn resize_rejects_values_outside_the_rust_contract() { let value = p::RequestEnvelope { diff --git a/crates/openshell-sandbox-backend/src/runtime.rs b/crates/openshell-sandbox-backend/src/runtime.rs index 578460504f..0efd9a6f93 100644 --- a/crates/openshell-sandbox-backend/src/runtime.rs +++ b/crates/openshell-sandbox-backend/src/runtime.rs @@ -983,6 +983,36 @@ impl ReadyBoundary { } } +/// Reads the runtime's process events with a sequence cursor. +#[derive(Clone)] +pub struct ProcessEventSource { + client: Arc, +} + +impl ProcessEventSource { + /// Events after `after_sequence`, or after the last sequence a reader + /// acknowledged when `None`, and how many of those the runtime no longer + /// retains. With `wait`, returns empty when none arrive within the + /// runtime's read wait; without it, at once. + pub async fn read( + &self, + after_sequence: Option, + wait: bool, + ) -> Result<(Vec, u64), BackendError> { + let response = self + .client + .call_wait(Request::ReadProcessEvents { + after_sequence, + wait, + }) + .await?; + let Response::ProcessEvents { events, lost } = response else { + return Err(unexpected_response("process_events", &response)); + }; + Ok((events, lost)) + } +} + pub struct RunningBoundary { process: Arc, /// Exec processes a replacement supervisor adopted from the runtime. @@ -1023,6 +1053,19 @@ impl RunningBoundary { self.loopback_connector.clone() } + /// Launch and exit events of the processes the runtime starts directly, + /// when the runtime serves them. + #[must_use] + pub fn process_events(&self) -> Option { + self.process + .client + .backend_supports_process_events + .load(Ordering::Acquire) + .then(|| ProcessEventSource { + client: self.process.client.clone(), + }) + } + pub async fn terminate(&self) -> Result<(), BackendError> { let response = self .process @@ -1662,6 +1705,7 @@ struct BoundaryClient { resume: Option, launch_outcome: std::sync::OnceLock, backend_supports_suspend: AtomicBool, + backend_supports_process_events: AtomicBool, supervisor_instance_id: crate::boundary_protocol::SupervisorInstanceId, sandbox_bearer: openshell_core::jwt::SessionBearerTokenSlot, attach_request_timeout: Duration, @@ -1869,6 +1913,7 @@ impl BoundaryClient { resume: None, launch_outcome: std::sync::OnceLock::new(), backend_supports_suspend: AtomicBool::new(false), + backend_supports_process_events: AtomicBool::new(false), supervisor_instance_id: crate::boundary_protocol::SupervisorInstanceId::new(), sandbox_bearer, attach_request_timeout: ATTACH_REQUEST_TIMEOUT, @@ -2713,6 +2758,12 @@ impl BoundaryClient { } self.backend_supports_suspend .store(supports_suspend, Ordering::Release); + self.backend_supports_process_events.store( + backend.supported_capabilities.iter().any(|capability| { + capability == crate::isolation_protocol::PROCESS_EVENTS_CAPABILITY + }), + Ordering::Release, + ); Ok(()) } @@ -3504,6 +3555,36 @@ mod tests { server.abort(); } + #[tokio::test] + async fn process_events_are_read_only_from_a_runtime_that_serves_them() { + let (client, server) = + isolation_control_client(TestIsolationBackend::default(), None).await; + client.grpc_channel().await.unwrap(); + assert!( + client + .backend_supports_process_events + .load(Ordering::Acquire) + ); + server.abort(); + + let mut legacy = crate::isolation_protocol::metadata("legacy/runtime"); + legacy.supported_capabilities.retain(|capability| { + capability != crate::isolation_protocol::PROCESS_EVENTS_CAPABILITY + }); + let service = TestIsolationBackend { + metadata: Some(legacy), + ..TestIsolationBackend::default() + }; + let (client, server) = isolation_control_client(service, None).await; + client.grpc_channel().await.unwrap(); + assert!( + !client + .backend_supports_process_events + .load(Ordering::Acquire) + ); + server.abort(); + } + #[tokio::test] async fn suspend_sends_boundary_coordinates_and_returns_reference() { let service = TestIsolationBackend::suspendable(LaunchOutcome::Fresh); @@ -3838,6 +3919,10 @@ mod tests { kind: crate::boundary_protocol::BoundaryErrorKind::Unavailable, message: "no pending network request".to_string(), }, + Request::ReadProcessEvents { .. } => Response::ProcessEvents { + events: Vec::new(), + lost: 0, + }, }, }) { Ok(response) => response, diff --git a/crates/openshell-sandbox/src/boundary_exec.rs b/crates/openshell-sandbox/src/boundary_exec.rs index 40c433adff..8841048ba7 100644 --- a/crates/openshell-sandbox/src/boundary_exec.rs +++ b/crates/openshell-sandbox/src/boundary_exec.rs @@ -241,6 +241,7 @@ impl LocalBoundaryExec { fn spawn_piped(&self, spec: &ExecSpec) -> Result { self.runtime.ensure_active()?; let mut command = self.command(spec)?; + let program = command.get_program().to_string_lossy().into_owned(); command .stdin(Stdio::piped()) .stdout(Stdio::piped()) @@ -333,6 +334,7 @@ impl LocalBoundaryExec { let process = Arc::new(LocalExecProcess::new( child, pid, + &program, self.runtime.clone(), process_terminal, signal_lock, @@ -382,6 +384,7 @@ impl LocalBoundaryExec { .try_clone() .map_err(|error| BackendError::Process(error.to_string()))?; let mut command = self.command(spec)?; + let program = command.get_program().to_string_lossy().into_owned(); command.stdin(stdin).stdout(stdout).stderr(slave); let effective_workdir = spec.workdir.as_deref().or(self.base_workdir.as_deref()); #[cfg(target_os = "linux")] @@ -432,6 +435,7 @@ impl LocalBoundaryExec { let process = Arc::new(LocalExecProcess::new( child, pid, + &program, self.runtime.clone(), process_terminal, signal_lock, @@ -702,6 +706,7 @@ impl LocalExecProcess { fn new( child: Child, pid: u32, + program: &str, runtime: Arc, terminal: Arc, signal_lock: Arc>, @@ -716,6 +721,7 @@ impl LocalExecProcess { let registration_terminal = terminal.clone(); #[cfg(target_os = "linux")] let signal_lock_for_wait = signal_lock.clone(); + let launched = crate::process_events::record_launch(pid, program); tokio::spawn(async move { let waited = tokio::task::spawn_blocking(move || { let mut child = child; @@ -760,6 +766,13 @@ impl LocalExecProcess { } BoundaryExitStatus::Exited(status.code().unwrap_or(1)) }); + match (&launched, &waited) { + (Some(launched), Ok(status)) => launched.record_exit((*status).into()), + (Some(_), Err(error)) => { + tracing::warn!(pid, %error, "exec exit status unavailable; no exit event recorded"); + } + (None, _) => {} + } runtime_for_wait.unregister_process_group(pid, ®istration_terminal); if let Ok(mut slot) = result_for_wait.lock() { *slot = Some(waited); @@ -1353,6 +1366,41 @@ mod tests { assert_eq!(runtime.registered_process_group_count(), 0); } + #[tokio::test] + async fn exec_records_its_launch_and_exit() { + use openshell_sandbox_backend::boundary_protocol::{ExitStatusWire, ProcessEventKindWire}; + + let session = executor() + .exec(ExecSpec { + program: "/bin/sh".to_string(), + args: vec!["-c".to_string(), "exit 43".to_string()], + shell: None, + runtime_helper: None, + env: vec![], + workdir: None, + pty: false, + }) + .await + .expect("spawn exec"); + session.process.wait().await.unwrap(); + + let (events, _) = + crate::process_events::log().read(Some(0), usize::MAX, std::time::Duration::ZERO); + let exit = events + .iter() + .find(|event| event.kind == ProcessEventKindWire::Exited(ExitStatusWire::Exited(43))) + .expect("exit recorded"); + let launch = events + .iter() + .find(|event| { + event.kind == ProcessEventKindWire::Launched && event.process == exit.process + }) + .expect("launch recorded"); + assert!(launch.sequence < exit.sequence); + assert_eq!(exit.process.parent_pid, std::process::id()); + assert!(launch.executable.ends_with("sh"), "{}", launch.executable); + } + #[tokio::test] async fn pty_exec_exposes_resize_and_stable_wait() { let session = executor() diff --git a/crates/openshell-sandbox/src/boundary_server.rs b/crates/openshell-sandbox/src/boundary_server.rs index 7a74565139..e5cb8ba77c 100644 --- a/crates/openshell-sandbox/src/boundary_server.rs +++ b/crates/openshell-sandbox/src/boundary_server.rs @@ -311,6 +311,7 @@ mod linux { runtime: Arc, ) -> Result<(), String> { let result = serve(config, runtime); + crate::process_events::log().close(); process_runtime.shutdown_timeout(PROCESS_RUNTIME_SHUTDOWN_TIMEOUT); result } @@ -2969,7 +2970,7 @@ mod linux { .map(|()| true) .map_err(|error| error.to_string()), // Waiting reads status and may block for the process lifetime. - Request::Wait { .. } => self + Request::Wait { .. } | Request::ReadProcessEvents { .. } => self .connections .require_active(principal) .map(|()| true) @@ -3485,6 +3486,21 @@ mod linux { provider_files, ), Request::Wait { process_id } => self.wait(&process_id), + Request::ReadProcessEvents { + after_sequence, + wait, + } => { + let (events, lost) = crate::process_events::log().read( + after_sequence, + crate::process_events::MAX_READ, + if wait { + crate::process_events::READ_WAIT + } else { + Duration::ZERO + }, + ); + Response::ProcessEvents { events, lost } + } Request::Signal { process_id, signal } => self.signal(&process_id, signal), Request::Terminate { process_id } => self.terminate(&process_id), Request::Resize { @@ -9324,6 +9340,26 @@ mod linux { .all(|process| process.kind == ProcessKindWire::Main) ); + // Reading process events holds no ownership guard, so a long + // poll never delays a promotion. Only the owner in force starts a + // read; one already waiting at promotion can still return events + // to the previous owner. + let read_events = Request::ReadProcessEvents { + after_sequence: None, + wait: true, + }; + assert!( + boundary + .authorize_request(&old, &read_events) + .expect("the owner reads process events") + .is_none() + ); + assert!( + boundary + .authorize_request(&candidate, &read_events) + .is_err() + ); + // The owner is authorized for an operation and, still holding // that authorization, starts an exec the replacement's staged // snapshot does not show. @@ -9397,9 +9433,16 @@ mod linux { provider_files: std::collections::HashMap::new(), }, Request::TerminateBoundary, + read_events.clone(), ] { assert!(boundary.authorize_request(&old, &request).is_err()); } + assert!( + boundary + .authorize_request(&candidate, &read_events) + .expect("the promoted owner reads process events") + .is_none() + ); let resumed = boundary.running_process(&process_id).expect("workload"); assert!(!resumed.has_exited()); diff --git a/crates/openshell-sandbox/src/delegated.rs b/crates/openshell-sandbox/src/delegated.rs index 7b3ec12b16..1899e2870b 100644 --- a/crates/openshell-sandbox/src/delegated.rs +++ b/crates/openshell-sandbox/src/delegated.rs @@ -18,6 +18,7 @@ use openshell_ocsf::{ ActionId, ActivityId, DispositionId, LaunchTypeId, Process as OcsfProcess, ProcessActivityBuilder, SeverityId, StatusId, ocsf_emit, }; +use openshell_sandbox_backend::boundary_protocol::ExitStatusWire; use crate::process::{ProcessHandle, ProcessStatus, ResolvedWorkspace}; @@ -129,6 +130,10 @@ pub async fn spawn_workload( .register_process_group(handle.pid(), terminal.clone(), signal_lock.clone()) .map_err(|error| miette::miette!(error.to_string()))?; + let recorded_launch = crate::process_events::record_launch(handle.pid(), program); + let executable = recorded_launch + .as_ref() + .map_or(program, crate::process_events::Launched::executable); ocsf_emit!( ProcessActivityBuilder::new(ocsf_ctx()) .activity(ActivityId::Open) @@ -137,7 +142,7 @@ pub async fn spawn_workload( .severity(SeverityId::Informational) .status(StatusId::Success) .launch_type(LaunchTypeId::Spawn) - .process(OcsfProcess::new(program, i64::from(handle.pid()))) + .process(OcsfProcess::new(executable, i64::from(handle.pid()))) .actor_process(crate::process::ocsf_launcher_process()) .message(format!("Process started: pid={}", handle.pid())) .build() @@ -145,6 +150,7 @@ pub async fn spawn_workload( Ok(SpawnedAgent { handle, + launched: recorded_launch, timeout_secs, terminal, signal_lock, @@ -158,6 +164,7 @@ pub async fn spawn_workload( /// Owned workload process and its live boundary capabilities. pub struct SpawnedAgent { handle: ProcessHandle, + launched: Option, timeout_secs: u64, terminal: Arc, signal_lock: Arc>, @@ -213,6 +220,12 @@ impl SpawnedAgent { }; self.boundary_runtime .unregister_process_group(self.handle.pid(), &self.terminal); + if let Some(launched) = self.launched.take() { + launched.record_exit(status.signal().map_or_else( + || ExitStatusWire::Exited(status.code()), + ExitStatusWire::Signaled, + )); + } let _ = self.main_session.finish(status.code(), false).await; self.main_session.mark_terminal_reported(); Ok(status) diff --git a/crates/openshell-sandbox/src/lib.rs b/crates/openshell-sandbox/src/lib.rs index 3c280cc977..e5fc7b4414 100644 --- a/crates/openshell-sandbox/src/lib.rs +++ b/crates/openshell-sandbox/src/lib.rs @@ -34,6 +34,8 @@ pub mod perf; #[cfg(target_os = "linux")] pub mod process; #[cfg(target_os = "linux")] +pub mod process_events; +#[cfg(target_os = "linux")] mod provider_files; #[cfg(target_os = "linux")] mod pty; diff --git a/crates/openshell-sandbox/src/process_events.rs b/crates/openshell-sandbox/src/process_events.rs new file mode 100644 index 0000000000..8fffe0c90c --- /dev/null +++ b/crates/openshell-sandbox/src/process_events.rs @@ -0,0 +1,379 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Bounded log of launch and exit events for the workload processes this +//! runtime starts, read by the supervisor with a sequence cursor. + +use std::collections::VecDeque; +use std::sync::{Condvar, LazyLock, Mutex}; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use openshell_isolation_interface::contract::ProcessInstance; +use openshell_sandbox_backend::boundary_protocol::{ + ExitStatusWire, ProcessEventKindWire, ProcessEventWire, +}; +use openshell_sandbox_backend::protobuf::WireMessage; + +const CAPACITY: usize = 4096; +/// Most events in one response. +pub const MAX_READ: usize = 256; +/// Encoded size one response stays under, half the control message limit. +const MAX_READ_BYTES: usize = 512 * 1024; +/// How long a read with nothing to return waits for an event. +pub const READ_WAIT: Duration = Duration::from_secs(30); + +static LOG: LazyLock = LazyLock::new(|| ProcessEventLog::new(CAPACITY)); + +/// The runtime's process event log. +pub fn log() -> &'static ProcessEventLog { + &LOG +} + +/// A launch recorded in the log, kept until the runtime reaps the process. +pub struct Launched { + process: ProcessInstance, + executable: String, +} + +/// Record the launch of a process the runtime just spawned from `program`. +/// `None` when procfs no longer reports it. +pub fn record_launch(pid: u32, program: &str) -> Option { + let Some(process) = openshell_binary_identity::observe_process(pid) else { + tracing::warn!( + pid, + "process not visible in procfs; launch and exit not recorded" + ); + return None; + }; + // A process that already exited has no readable executable link. + let executable = std::fs::read_link(format!("/proc/{pid}/exe")) + .map_or_else(|_| program.to_string(), |path| path.display().to_string()); + log().record(process, &executable, ProcessEventKindWire::Launched); + Some(Launched { + process, + executable, + }) +} + +impl Launched { + /// The executable recorded with the launch. + pub fn executable(&self) -> &str { + &self.executable + } + + pub fn record_exit(&self, status: ExitStatusWire) { + log().record( + self.process, + &self.executable, + ProcessEventKindWire::Exited(status), + ); + } +} + +pub struct ProcessEventLog { + capacity: usize, + state: Mutex, + changed: Condvar, +} + +struct State { + events: VecDeque, + next_sequence: u64, + /// The highest sequence a reader has read past. + acknowledged: u64, + closed: bool, +} + +impl ProcessEventLog { + fn new(capacity: usize) -> Self { + Self { + capacity, + state: Mutex::new(State { + events: VecDeque::new(), + next_sequence: 1, + acknowledged: 0, + closed: false, + }), + changed: Condvar::new(), + } + } + + pub fn record(&self, process: ProcessInstance, executable: &str, kind: ProcessEventKindWire) { + let time_ms = SystemTime::now() + .duration_since(UNIX_EPOCH) + .ok() + .and_then(|elapsed| i64::try_from(elapsed.as_millis()).ok()) + .unwrap_or_default(); + let mut event = ProcessEventWire { + sequence: 0, + process, + executable: executable.to_string(), + kind, + time_ms, + }; + // An event the protocol cannot carry would fail every read after it. + if let Err(error) = event.to_proto() { + tracing::warn!(pid = process.pid, %error, "process event not recorded"); + return; + } + let mut state = self.lock(); + event.sequence = state.next_sequence; + state.next_sequence += 1; + if state.events.len() == self.capacity { + state.events.pop_front(); + } + state.events.push_back(event); + drop(state); + self.changed.notify_all(); + } + + /// Up to `max` events after `after` that fit the response budget, and how + /// many events after `after` were evicted. Reading after a sequence + /// acknowledges it; `None` reads after the last acknowledged sequence. + /// Waits up to `wait` when there is nothing to return. + pub fn read( + &self, + after: Option, + max: usize, + wait: Duration, + ) -> (Vec, u64) { + let mut state = self.lock(); + let after = match after { + Some(after) => { + let read = after.min(state.next_sequence - 1); + state.acknowledged = state.acknowledged.max(read); + after + } + None => state.acknowledged, + }; + let (state, _) = self + .changed + .wait_timeout_while(state, wait, |state| { + !state.closed && state.next_sequence <= after.saturating_add(1) + }) + .unwrap_or_else(std::sync::PoisonError::into_inner); + let first = state + .events + .front() + .map_or(state.next_sequence, |event| event.sequence); + let lost = first.saturating_sub(after.saturating_add(1)); + let mut budget = MAX_READ_BYTES; + let events = state + .events + .iter() + .filter(|event| event.sequence > after) + .take(max) + .enumerate() + .take_while(|(index, event)| { + let size = encoded_size(event); + let fits = *index == 0 || size <= budget; + budget = budget.saturating_sub(size); + fits + }) + .map(|(_, event)| event.clone()) + .collect(); + (events, lost) + } + + /// Wake pending reads and stop later ones from waiting. + pub fn close(&self) { + self.lock().closed = true; + self.changed.notify_all(); + } + + fn lock(&self) -> std::sync::MutexGuard<'_, State> { + self.state + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + } +} + +/// An upper bound on one event's encoded size. +fn encoded_size(event: &ProcessEventWire) -> usize { + event.executable.len() + 128 +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::Arc; + use std::time::Instant; + + fn process(pid: u32) -> ProcessInstance { + ProcessInstance { + pid, + parent_pid: 1, + start_time_ms: 1_000, + } + } + + #[test] + fn read_returns_events_after_the_cursor_in_order() { + let log = ProcessEventLog::new(8); + log.record(process(10), "/bin/sh", ProcessEventKindWire::Launched); + log.record( + process(10), + "/bin/sh", + ProcessEventKindWire::Exited(ExitStatusWire::Exited(3)), + ); + log.record(process(11), "/bin/true", ProcessEventKindWire::Launched); + + let (events, lost) = log.read(Some(1), MAX_READ, Duration::ZERO); + assert_eq!(lost, 0); + assert_eq!( + events + .iter() + .map(|event| event.sequence) + .collect::>(), + [2, 3] + ); + assert_eq!( + events[0].kind, + ProcessEventKindWire::Exited(ExitStatusWire::Exited(3)) + ); + assert_eq!(events[1].process.pid, 11); + + let (events, _) = log.read(Some(0), 1, Duration::ZERO); + assert_eq!(events.len(), 1); + assert_eq!(events[0].sequence, 1); + } + + #[test] + fn evicted_events_after_the_cursor_are_counted_as_lost() { + let log = ProcessEventLog::new(2); + for pid in 1..=5 { + log.record(process(pid), "/bin/true", ProcessEventKindWire::Launched); + } + + let (events, lost) = log.read(Some(1), MAX_READ, Duration::ZERO); + assert_eq!(lost, 2); + assert_eq!( + events + .iter() + .map(|event| event.sequence) + .collect::>(), + [4, 5] + ); + let (_, lost) = log.read(Some(4), MAX_READ, Duration::ZERO); + assert_eq!(lost, 0); + } + + #[test] + fn a_read_stops_before_the_response_byte_budget() { + let log = ProcessEventLog::new(MAX_READ); + let path = format!("/{}", "a".repeat(4095)); + for pid in 1..=u32::try_from(MAX_READ).unwrap() { + log.record(process(pid), &path, ProcessEventKindWire::Launched); + } + + let (events, _) = log.read(Some(0), MAX_READ, Duration::ZERO); + assert!(!events.is_empty()); + assert!(events.len() < MAX_READ); + let bytes: usize = events.iter().map(encoded_size).sum(); + assert!(bytes <= MAX_READ_BYTES); + + let mut read = events.len(); + let mut after = events.last().unwrap().sequence; + loop { + let (events, _) = log.read(Some(after), MAX_READ, Duration::ZERO); + let Some(last) = events.last() else { break }; + after = last.sequence; + read += events.len(); + } + assert_eq!(read, MAX_READ); + } + + #[test] + fn an_event_records_when_it_happened() { + let log = ProcessEventLog::new(8); + let before = now_ms(); + log.record(process(7), "/bin/sh", ProcessEventKindWire::Launched); + let (events, _) = log.read(Some(0), MAX_READ, Duration::ZERO); + assert!(events[0].time_ms >= before); + assert!(events[0].time_ms <= now_ms()); + } + + fn now_ms() -> i64 { + i64::try_from( + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_millis(), + ) + .unwrap() + } + + fn sequences(events: &[ProcessEventWire]) -> Vec { + events.iter().map(|event| event.sequence).collect() + } + + #[test] + fn a_read_without_a_cursor_resumes_after_the_last_acknowledged_sequence() { + let log = ProcessEventLog::new(8); + for pid in 1..=5 { + log.record(process(pid), "/bin/true", ProcessEventKindWire::Launched); + } + let (events, _) = log.read(None, MAX_READ, Duration::ZERO); + assert_eq!(sequences(&events), [1, 2, 3, 4, 5]); + + log.read(Some(3), MAX_READ, Duration::ZERO); + let (events, lost) = log.read(None, MAX_READ, Duration::ZERO); + assert_eq!(lost, 0); + assert_eq!(sequences(&events), [4, 5]); + + log.read(Some(1), MAX_READ, Duration::ZERO); + log.read(Some(99), MAX_READ, Duration::ZERO); + log.record(process(6), "/bin/true", ProcessEventKindWire::Launched); + let (events, _) = log.read(None, MAX_READ, Duration::ZERO); + assert_eq!(sequences(&events), [6]); + } + + #[test] + fn closing_the_log_wakes_a_pending_read() { + let log = Arc::new(ProcessEventLog::new(8)); + let closer = log.clone(); + let closing = std::thread::spawn(move || { + std::thread::sleep(Duration::from_millis(20)); + closer.close(); + }); + let started = Instant::now(); + let (events, _) = log.read(Some(0), MAX_READ, Duration::from_secs(10)); + closing.join().unwrap(); + assert!(events.is_empty()); + assert!(started.elapsed() < Duration::from_secs(5)); + } + + #[test] + fn an_event_that_cannot_be_encoded_is_not_recorded() { + let log = ProcessEventLog::new(8); + let mut unencodable = process(9); + unencodable.start_time_ms = -1; + log.record(unencodable, "/bin/sh", ProcessEventKindWire::Launched); + log.record(process(10), "/bin/sh", ProcessEventKindWire::Launched); + + let (events, lost) = log.read(Some(0), MAX_READ, Duration::ZERO); + assert_eq!(lost, 0); + assert_eq!(sequences(&events), [1]); + assert_eq!(events[0].process.pid, 10); + } + + #[test] + fn an_empty_read_waits_for_the_next_event() { + let log = Arc::new(ProcessEventLog::new(8)); + let started = Instant::now(); + let (events, lost) = log.read(Some(0), MAX_READ, Duration::from_millis(50)); + assert!(events.is_empty()); + assert_eq!(lost, 0); + assert!(started.elapsed() >= Duration::from_millis(50)); + + let writer = log.clone(); + let recorder = std::thread::spawn(move || { + std::thread::sleep(Duration::from_millis(20)); + writer.record(process(7), "/bin/sh", ProcessEventKindWire::Launched); + }); + let (events, _) = log.read(Some(0), MAX_READ, Duration::from_secs(10)); + recorder.join().unwrap(); + assert_eq!(events.len(), 1); + assert_eq!(events[0].process.pid, 7); + } +} diff --git a/crates/openshell-supervisor/src/lib.rs b/crates/openshell-supervisor/src/lib.rs index 6278307846..b9e6327d15 100644 --- a/crates/openshell-supervisor/src/lib.rs +++ b/crates/openshell-supervisor/src/lib.rs @@ -26,6 +26,7 @@ mod endpoint_status; mod mechanistic_mapper; mod otlp_relay; mod policy_runtime; +mod process_activity; mod provider_readiness; pub mod sandbox_instance_host; pub mod shared_host; @@ -1783,6 +1784,7 @@ pub async fn run_sandbox_instance( } let _app_listener = app_instance.map(|instance| instance.start(running.loopback_connector())); + let mut process_activity = running.process_events().map(process_activity::start); let agent = running.agent(); let boundary_access = openshell_supervisor_process::delegated::start_boundary_access( sandbox_id.as_deref(), @@ -1854,12 +1856,18 @@ pub async fn run_sandbox_instance( let _ = agent .signal(openshell_isolation_interface::contract::BoundarySignal::Term) .await; - if let Ok(result) = timeout(WORKLOAD_TERM_GRACE, agent.wait()).await { - result - } else { - let _ = agent.terminate().await; - agent.wait().await + let result = + if let Ok(result) = timeout(WORKLOAD_TERM_GRACE, agent.wait()).await { + result + } else { + let _ = agent.terminate().await; + agent.wait().await + }; + // Report the workload's exit before the boundary goes. + if let Some(relay) = process_activity.take() { + relay.finish(process_activity::FINISH_TIMEOUT).await; } + result }; let exit_code = Box::pin(stop_workload(wait, || running.terminate(), shutdown_deadline)) @@ -1886,6 +1894,7 @@ pub async fn run_sandbox_instance( // TerminateBoundary or publish a main-process exit. Dropping the // access plane closes this supervisor's gateway session. instance_readiness.release(); + drop(process_activity); drop(running); drop(boundary_access); // The workload is frozen, so no new spans arrive. Export what the @@ -1972,6 +1981,9 @@ pub async fn run_sandbox_instance( if let Some(relay) = otlp_relay.take() { relay.shutdown(otlp_relay::FLUSH_TIMEOUT).await; } + if let Some(relay) = process_activity { + relay.finish(process_activity::FINISH_TIMEOUT).await; + } drop(instance_readiness); drop(running); drop(boundary_access); diff --git a/crates/openshell-supervisor/src/process_activity.rs b/crates/openshell-supervisor/src/process_activity.rs new file mode 100644 index 0000000000..8f78ead2e9 --- /dev/null +++ b/crates/openshell-supervisor/src/process_activity.rs @@ -0,0 +1,284 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! OCSF Process Activity for the processes the sandbox runtime starts +//! directly: the entrypoint and exec sessions. + +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use openshell_isolation_interface::contract::BackendError; +use openshell_ocsf::{ + ActionId, ActivityId, DispositionId, LaunchTypeId, OcsfEvent, Process, ProcessActivityBuilder, + SeverityId, StatusId, ocsf_emit, +}; +use openshell_sandbox_backend::ProcessEventSource; +use openshell_sandbox_backend::boundary_protocol::{ + ExitStatusWire, ProcessEventKindWire, ProcessEventWire, +}; + +const RETRY_DELAY: Duration = Duration::from_secs(1); +/// Bound on the final read when the relay finishes. +pub const FINISH_TIMEOUT: Duration = Duration::from_secs(2); + +/// Reads process events from `source` and emits them until finished or +/// dropped. +pub struct ProcessActivityRelay { + task: tokio::task::JoinHandle<()>, + source: ProcessEventSource, + cursor: Arc>, +} + +impl Drop for ProcessActivityRelay { + fn drop(&mut self) { + self.task.abort(); + } +} + +impl ProcessActivityRelay { + /// Stop reading, then emit the events already recorded, waiting at most + /// `timeout` for them. + pub async fn finish(mut self, timeout: Duration) { + self.task.abort(); + let _ = (&mut self.task).await; + let after = lock(&self.cursor).after; + match tokio::time::timeout(timeout, self.source.read(after, false)).await { + Ok(Ok((events, lost))) => { + let emitted = lock(&self.cursor).accept(events, lost); + for event in emitted { + ocsf_emit!(event); + } + } + Ok(Err(error)) => { + tracing::debug!(%error, "final read of sandbox process events failed"); + } + Err(_) => tracing::debug!("final read of sandbox process events timed out"), + } + } +} + +pub fn start(source: ProcessEventSource) -> ProcessActivityRelay { + let cursor = Arc::new(Mutex::new(Cursor::default())); + let task = tokio::spawn({ + let source = source.clone(); + let cursor = cursor.clone(); + async move { + let mut failing = false; + loop { + let after = lock(&cursor).after; + match source.read(after, true).await { + Ok((events, lost)) => { + failing = false; + let emitted = lock(&cursor).accept(events, lost); + for event in emitted { + ocsf_emit!(event); + } + } + Err(BackendError::Terminated(_)) => return, + Err(BackendError::Unavailable(error)) => { + tracing::warn!(%error, "sandbox process events unavailable; no longer reading them"); + return; + } + Err(error) => { + if failing { + tracing::debug!(%error, "reading sandbox process events failed; retrying"); + } else { + tracing::warn!(%error, "reading sandbox process events failed; retrying"); + } + failing = true; + tokio::time::sleep(RETRY_DELAY).await; + } + } + } + } + }); + ProcessActivityRelay { + task, + source, + cursor, + } +} + +fn lock(cursor: &Mutex) -> std::sync::MutexGuard<'_, Cursor> { + cursor + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) +} + +/// Sequence cursor over the runtime's process events. Unset until the first +/// event, so a replacement supervisor resumes after the events its +/// predecessor read. +#[derive(Default)] +struct Cursor { + after: Option, +} + +impl Cursor { + fn accept(&mut self, events: Vec, lost: u64) -> Vec { + if lost > 0 { + tracing::warn!( + lost, + "sandbox runtime dropped process events before they were read" + ); + } + events + .into_iter() + .map(|event| { + self.after = Some( + self.after + .map_or(event.sequence, |after| after.max(event.sequence)), + ); + process_activity(&event) + }) + .collect() + } +} + +fn process_activity(event: &ProcessEventWire) -> OcsfEvent { + let instance = event.process; + let launcher = || Process::new("openshell-sandbox", i64::from(instance.parent_pid)); + let name = if event.executable.is_empty() { + "-" + } else { + event.executable.as_str() + }; + let process = Process::new(name, i64::from(instance.pid)) + .with_parent(launcher()) + .with_instance(instance.parent_pid, instance.start_time_ms); + let kind = match event.kind { + ProcessEventKindWire::Launched => "launch", + ProcessEventKindWire::Exited(_) => "exit", + }; + let ctx = openshell_ocsf::ctx::ctx(); + // The process instance and transition identify the activity, so a + // replacement supervisor that reads it again reports the same uid. + let uid = format!( + "{}/{}/{}/{kind}", + ctx.sandbox_id, instance.pid, instance.start_time_ms + ); + let builder = ProcessActivityBuilder::new(ctx) + .action(ActionId::Allowed) + .disposition(DispositionId::Allowed) + .severity(SeverityId::Informational) + .process(process) + .time(event.time_ms) + .uid(uid) + .actor_process(launcher()); + match event.kind { + ProcessEventKindWire::Launched => builder + .status(StatusId::Success) + .activity(ActivityId::Open) + .launch_type(LaunchTypeId::Spawn) + .message(format!("Process started: pid={}", instance.pid)) + .build(), + ProcessEventKindWire::Exited(status) => { + let (code, detail) = match status { + ExitStatusWire::Exited(code) => (code, format!("exit={code}")), + ExitStatusWire::Signaled(signal) => { + (128_i32.saturating_add(signal), format!("signal={signal}")) + } + }; + builder + .status(if code == 0 { + StatusId::Success + } else { + StatusId::Failure + }) + .activity(ActivityId::Close) + .exit_code(code) + .message(format!("Process exited: pid={} {detail}", instance.pid)) + .build() + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use openshell_isolation_interface::contract::ProcessInstance; + use openshell_sandbox_backend::boundary_protocol::{ExitStatusWire, ProcessEventKindWire}; + + fn event(sequence: u64, kind: ProcessEventKindWire) -> ProcessEventWire { + ProcessEventWire { + sequence, + process: ProcessInstance { + pid: 57, + parent_pid: 1, + start_time_ms: 1_793_750_400_123, + }, + executable: "/usr/bin/sh".to_string(), + kind, + time_ms: 1_793_750_400_200 + i64::try_from(sequence).unwrap(), + } + } + + #[test] + fn launch_and_exit_become_process_activity() { + let mut cursor = Cursor::default(); + let emitted = cursor.accept( + vec![ + event(1, ProcessEventKindWire::Launched), + event(2, ProcessEventKindWire::Exited(ExitStatusWire::Exited(3))), + event(3, ProcessEventKindWire::Exited(ExitStatusWire::Signaled(9))), + ], + 0, + ); + assert_eq!(cursor.after, Some(3)); + + let launch = serde_json::to_value(&emitted[0]).unwrap(); + assert_eq!(launch["class_name"], "Process Activity"); + assert_eq!(launch["activity_name"], "Launch"); + assert_eq!(launch["process"]["name"], "/usr/bin/sh"); + assert_eq!(launch["process"]["pid"], 57); + assert_eq!(launch["process"]["created_time"], 1_793_750_400_123_i64); + assert_eq!(launch["process"]["parent_process"]["pid"], 1); + assert_eq!(launch["actor"]["process"]["name"], "openshell-sandbox"); + assert_eq!(launch["actor"]["process"]["pid"], 1); + + let exit = serde_json::to_value(&emitted[1]).unwrap(); + assert_eq!(exit["activity_name"], "Terminate"); + assert_eq!(exit["exit_code"], 3); + assert_eq!(exit["status"], "Failure"); + assert_eq!(exit["process"]["created_time"], 1_793_750_400_123_i64); + assert!( + emitted[1] + .format_shorthand() + .contains("PROC:TERMINATE [INFO] /usr/bin/sh(57) [exit:3]") + ); + + let killed = serde_json::to_value(&emitted[2]).unwrap(); + assert_eq!(killed["exit_code"], 137); + assert_eq!(killed["status"], "Failure"); + + let clean = event(4, ProcessEventKindWire::Exited(ExitStatusWire::Exited(0))); + let clean = serde_json::to_value(process_activity(&clean)).unwrap(); + assert_eq!(clean["exit_code"], 0); + assert_eq!(clean["status"], "Success"); + } + + #[test] + fn a_replayed_event_keeps_its_time_and_uid() { + let launch = event(1, ProcessEventKindWire::Launched); + let first = serde_json::to_value(process_activity(&launch)).unwrap(); + let replayed = serde_json::to_value(process_activity(&launch)).unwrap(); + assert_eq!(first["time"], 1_793_750_400_201_i64); + assert_eq!(replayed["time"], first["time"]); + assert_eq!(replayed["metadata"]["uid"], first["metadata"]["uid"]); + + let exit = event(2, ProcessEventKindWire::Exited(ExitStatusWire::Exited(0))); + let exit = serde_json::to_value(process_activity(&exit)).unwrap(); + assert_ne!(exit["metadata"]["uid"], first["metadata"]["uid"]); + } + + #[test] + fn the_cursor_advances_past_events_it_reads() { + let mut cursor = Cursor::default(); + assert_eq!(cursor.after, None); + assert!(cursor.accept(Vec::new(), 0).is_empty()); + assert_eq!(cursor.after, None); + cursor.accept(vec![event(7, ProcessEventKindWire::Launched)], 6); + assert_eq!(cursor.after, Some(7)); + assert!(cursor.accept(Vec::new(), 0).is_empty()); + assert_eq!(cursor.after, Some(7)); + } +} diff --git a/docs/observability/logging.mdx b/docs/observability/logging.mdx index a0b1065b95..3dfdc72635 100644 --- a/docs/observability/logging.mdx +++ b/docs/observability/logging.mdx @@ -195,7 +195,13 @@ OCSF SSH:OPEN [INFO] ALLOWED A process launched inside the sandbox: ```text -OCSF PROC:LAUNCH [INFO] sleep(49) +OCSF PROC:LAUNCH [INFO] /usr/bin/sleep(49) +``` + +The same process exiting with status 3: + +```text +OCSF PROC:TERMINATE [INFO] /usr/bin/sleep(49) [exit:3] ``` A policy reload after a settings change: diff --git a/docs/observability/ocsf-json-export.mdx b/docs/observability/ocsf-json-export.mdx index 26ef0fbff8..46f541ebd3 100644 --- a/docs/observability/ocsf-json-export.mdx +++ b/docs/observability/ocsf-json-export.mdx @@ -168,7 +168,7 @@ Sandbox identity has moved from top-level `container` to `device.container` for Some fields depend on the event class: - SSH Activity records name the supervisor's SSH server as `dst_endpoint`, with `svc_name: "ssh"` and the listen socket path in `name`, because the server listens on a Unix socket rather than a network address. -- Process Activity records from the sandbox name the `openshell-sandbox` launcher as `actor.process`. +- Process Activity records from the sandbox name the `openshell-sandbox` launcher as `actor.process`. The supervisor records a `Launch` and a `Terminate` for the sandbox entrypoint and for the process each exec or SSH session starts. `Terminate` carries `exit_code`, which is 128 plus the signal number when a signal ended the process, and `status` `Failure` when `exit_code` is not 0. `time` is when the sandbox observed the launch or exit. A replacement supervisor can report a launch or exit again with the same `metadata.uid`, so deduplicate Process Activity on that field. `process.pid` and `process.created_time` match the network events from the same process. - Network and HTTP Activity records for connections the sandbox runtime mediates name the process that opened the connection as `actor.process`, with its `pid` as the sandbox sees it and its start time in `created_time`. When the parent process is identified, `parent_process` carries its `pid`. A `pid` can be reused after its process exits; `pid` and `created_time` together identify one process. - `connection_info` carries `direction_id` and `direction`. OpenShell reports Unknown (`0`) where it does not track the direction. diff --git a/proto/sandbox_protocol.proto b/proto/sandbox_protocol.proto index 953885867e..2e66118d5b 100644 --- a/proto/sandbox_protocol.proto +++ b/proto/sandbox_protocol.proto @@ -85,6 +85,7 @@ message RequestEnvelope { LoopbackConnect loopback_connect = 24; OpenMediation open_mediation = 25; AcceptNetwork accept_network = 26; + ReadProcessEvents read_process_events = 27; } } message ResponseEnvelope { @@ -106,6 +107,7 @@ message ResponseEnvelope { MediationReady mediation_ready = 24; NetworkConnected network_connected = 25; Error error = 26; + ProcessEvents process_events = 27; } } // Read-only image-policy discovery, permitted before attachment. @@ -188,6 +190,16 @@ message LoopbackConnect { } message OpenMediation {} message AcceptNetwork {} +// Requires the openshell.sandbox.process-events capability. Returns the +// retained events after after_sequence; an empty response means none arrived. +// Reading after a sequence acknowledges the events up to it, and a read +// without after_sequence resumes after the last acknowledged one, so a +// replacement supervisor does not report events its predecessor read. With +// wait, a read with nothing to return waits briefly for an event. +message ReadProcessEvents { + optional uint64 after_sequence = 1; + bool wait = 2; +} // No image policy is yaml absent with invalid=false. invalid=true reports an // unreadable or invalid image policy; it must not be treated as missing. @@ -225,6 +237,27 @@ message ExecStarted { bool pty = 2; } message Resized {} +// lost counts events after the requested sequence that the runtime no longer +// retains. +message ProcessEvents { + repeated ProcessEvent events = 1; + uint64 lost = 2; +} +// A workload process the runtime started directly: the entrypoint or an exec +// session. `executable` is read just after spawn, so a process that execs +// at once can report its new program. +message ProcessEvent { + uint64 sequence = 1; + ProcessInstance process = 2; + string executable = 3; + oneof event { + ProcessLaunched launched = 4; + ExitStatus exited = 5; + } + // When the runtime observed the launch or exit. + google.protobuf.Timestamp time = 6; +} +message ProcessLaunched {} message LoopbackConnected {} message MediationReady {} message NetworkConnected {