diff --git a/crates/openshell-cli/tests/ensure_providers_integration.rs b/crates/openshell-cli/tests/ensure_providers_integration.rs index 3f17d22921..b742837b2f 100644 --- a/crates/openshell-cli/tests/ensure_providers_integration.rs +++ b/crates/openshell-cli/tests/ensure_providers_integration.rs @@ -77,6 +77,13 @@ impl TestOpenShell { #[tonic::async_trait] impl OpenShell for TestOpenShell { + async fn get_exec_sandbox_result( + &self, + _request: tonic::Request, + ) -> Result, Status> { + Err(Status::unimplemented("not used by this test server")) + } + async fn report_endpoint_status( &self, _request: tonic::Request, diff --git a/crates/openshell-cli/tests/grpc_default_stubs_integration.rs b/crates/openshell-cli/tests/grpc_default_stubs_integration.rs index 36ef9ec8b3..03a5455c47 100644 --- a/crates/openshell-cli/tests/grpc_default_stubs_integration.rs +++ b/crates/openshell-cli/tests/grpc_default_stubs_integration.rs @@ -13,7 +13,14 @@ use tonic::transport::{Endpoint, Server}; struct EmptyGateway; #[tonic::async_trait] -impl OpenShell for EmptyGateway {} +impl OpenShell for EmptyGateway { + async fn get_exec_sandbox_result( + &self, + _request: tonic::Request, + ) -> Result, tonic::Status> { + Err(tonic::Status::unimplemented("not used by this test server")) + } +} #[tokio::test] async fn production_client_gets_unimplemented_for_every_unused_rpc_shape() { diff --git a/crates/openshell-cli/tests/mtls_integration.rs b/crates/openshell-cli/tests/mtls_integration.rs index d5813cc017..d819703e87 100644 --- a/crates/openshell-cli/tests/mtls_integration.rs +++ b/crates/openshell-cli/tests/mtls_integration.rs @@ -29,6 +29,13 @@ struct TestOpenShell; #[tonic::async_trait] impl OpenShell for TestOpenShell { + async fn get_exec_sandbox_result( + &self, + _request: tonic::Request, + ) -> Result, Status> { + Err(Status::unimplemented("not used by this test server")) + } + async fn report_endpoint_status( &self, _request: tonic::Request, diff --git a/crates/openshell-cli/tests/provider_commands_integration.rs b/crates/openshell-cli/tests/provider_commands_integration.rs index f5563a7e77..c61d9205ad 100644 --- a/crates/openshell-cli/tests/provider_commands_integration.rs +++ b/crates/openshell-cli/tests/provider_commands_integration.rs @@ -235,6 +235,13 @@ impl TestOpenShell { #[tonic::async_trait] impl OpenShell for TestOpenShell { + async fn get_exec_sandbox_result( + &self, + _request: tonic::Request, + ) -> Result, Status> { + Err(Status::unimplemented("not used by this test server")) + } + async fn report_endpoint_status( &self, _request: tonic::Request, diff --git a/crates/openshell-cli/tests/sandbox_create_lifecycle_integration.rs b/crates/openshell-cli/tests/sandbox_create_lifecycle_integration.rs index e5072326b8..7d198e817d 100644 --- a/crates/openshell-cli/tests/sandbox_create_lifecycle_integration.rs +++ b/crates/openshell-cli/tests/sandbox_create_lifecycle_integration.rs @@ -100,6 +100,13 @@ struct TestOpenShell { #[tonic::async_trait] impl OpenShell for TestOpenShell { + async fn get_exec_sandbox_result( + &self, + _request: tonic::Request, + ) -> Result, Status> { + Err(Status::unimplemented("not used by this test server")) + } + // The rejected-suspend test checks that this error preserves active forwards. async fn suspend_sandbox( &self, diff --git a/crates/openshell-cli/tests/sandbox_exec_streaming_integration.rs b/crates/openshell-cli/tests/sandbox_exec_streaming_integration.rs index 657ee8e12c..00a6c09b39 100644 --- a/crates/openshell-cli/tests/sandbox_exec_streaming_integration.rs +++ b/crates/openshell-cli/tests/sandbox_exec_streaming_integration.rs @@ -154,6 +154,13 @@ async fn send_trailer_error(output: &mpsc::Sender, + ) -> Result, Status> { + Err(Status::unimplemented("not used by this test server")) + } + async fn get_sandbox( &self, _: Request, diff --git a/crates/openshell-cli/tests/sandbox_name_fallback_integration.rs b/crates/openshell-cli/tests/sandbox_name_fallback_integration.rs index 7e5a2c879f..1f0b953697 100644 --- a/crates/openshell-cli/tests/sandbox_name_fallback_integration.rs +++ b/crates/openshell-cli/tests/sandbox_name_fallback_integration.rs @@ -46,6 +46,13 @@ struct TestOpenShell { #[tonic::async_trait] impl OpenShell for TestOpenShell { + async fn get_exec_sandbox_result( + &self, + _request: tonic::Request, + ) -> Result, Status> { + Err(Status::unimplemented("not used by this test server")) + } + async fn report_endpoint_status( &self, _request: tonic::Request, diff --git a/crates/openshell-sdk/tests/client_mock.rs b/crates/openshell-sdk/tests/client_mock.rs index 39a11761e7..d94a83fb18 100644 --- a/crates/openshell-sdk/tests/client_mock.rs +++ b/crates/openshell-sdk/tests/client_mock.rs @@ -245,6 +245,13 @@ fn workload_template_proto(name: &str, workspace: &str) -> proto::SandboxWorkloa #[tonic::async_trait] impl OpenShell for TestOpenShell { + async fn get_exec_sandbox_result( + &self, + _request: tonic::Request, + ) -> Result, Status> { + Err(Status::unimplemented("not used by this test server")) + } + async fn get_sandbox_provider_access_token( &self, _request: tonic::Request, diff --git a/crates/openshell-server/src/grpc/mod.rs b/crates/openshell-server/src/grpc/mod.rs index ba6324f3a1..64e51a9f16 100644 --- a/crates/openshell-server/src/grpc/mod.rs +++ b/crates/openshell-server/src/grpc/mod.rs @@ -40,10 +40,11 @@ use openshell_core::proto::{ ExecSandboxInput, ExecSandboxRequest, ExposeServiceRequest, ExtensionKind, FinalizeMainProcessExitRequest, FinalizeMainProcessExitResponse, GatewayMessage, GetCurrentUserRequest, GetCurrentUserResponse, GetDraftHistoryRequest, GetDraftHistoryResponse, - GetDraftPolicyRequest, GetDraftPolicyResponse, GetGatewayConfigRequest, - GetGatewayConfigResponse, GetGatewayInfoRequest, GetGatewayInfoResponse, - GetProviderProfileRequest, GetProviderRefreshStatusRequest, GetProviderRefreshStatusResponse, - GetProviderRequest, GetSandboxConfigRequest, GetSandboxConfigResponse, GetSandboxLogsRequest, + GetDraftPolicyRequest, GetDraftPolicyResponse, GetExecSandboxResultRequest, + GetExecSandboxResultResponse, GetGatewayConfigRequest, GetGatewayConfigResponse, + GetGatewayInfoRequest, GetGatewayInfoResponse, GetProviderProfileRequest, + GetProviderRefreshStatusRequest, GetProviderRefreshStatusResponse, GetProviderRequest, + GetSandboxConfigRequest, GetSandboxConfigResponse, GetSandboxLogsRequest, GetSandboxLogsResponse, GetSandboxPolicyStatusRequest, GetSandboxPolicyStatusResponse, GetSandboxProviderEnvironmentRequest, GetSandboxProviderEnvironmentResponse, GetSandboxProviderStatusRequest, GetSandboxProviderStatusResponse, GetSandboxRequest, @@ -602,6 +603,13 @@ impl OpenShell for OpenShellService { mutation_replay::run(&self.state, request).await } + async fn get_exec_sandbox_result( + &self, + request: Request, + ) -> Result, Status> { + mutation_replay::get_exec_sandbox_result(&self.state, request).await + } + type ForwardTcpStream = Pin> + Send + 'static>>; diff --git a/crates/openshell-server/src/grpc/mutation_replay.rs b/crates/openshell-server/src/grpc/mutation_replay.rs index bdfa236885..208640609f 100644 --- a/crates/openshell-server/src/grpc/mutation_replay.rs +++ b/crates/openshell-server/src/grpc/mutation_replay.rs @@ -15,8 +15,8 @@ use openshell_core::proto::{ AddWorkspaceMemberRequest, AddWorkspaceMemberResponse, CreateSandboxTemplateRequest, CreateWorkspaceRequest, CreateWorkspaceResponse, DeleteSandboxTemplateRequest, DeleteSandboxTemplateResponse, DeleteWorkspaceRequest, DeleteWorkspaceResponse, - RemoveWorkspaceMemberRequest, RemoveWorkspaceMemberResponse, SandboxTemplateResponse, - Workspace, WorkspaceSelector, + GetExecSandboxResultRequest, GetExecSandboxResultResponse, RemoveWorkspaceMemberRequest, + RemoveWorkspaceMemberResponse, SandboxTemplateResponse, Workspace, WorkspaceSelector, }; use openshell_core::{GetResourceVersion, ObjectId, rpc_error}; use prost::Message; @@ -81,10 +81,19 @@ pub struct OriginalMutation(pub(crate) Vec); /// Deliberately no serialized requests, responses, tokens, or error messages. #[derive(Serialize, Deserialize)] pub(super) enum Success { - Resource { id: String, version: u64 }, - Deletion { outcome: i32 }, + Resource { + id: String, + version: u64, + }, + Deletion { + outcome: i32, + }, Ordinary(ordinary::Outcome), StreamTerminal, + /// A real SSH ExitStatus committed before the exit event is delivered. + StreamTerminalResult { + exit_code: i32, + }, } pub(super) struct Scope { @@ -410,8 +419,9 @@ impl Completion { Ok(()) } - pub(super) async fn stream_terminal(&self) -> Result<(), Status> { - self.complete(Success::StreamTerminal).await + pub(super) async fn stream_terminal(&self, exit_code: i32) -> Result<(), Status> { + self.complete(Success::StreamTerminalResult { exit_code }) + .await } async fn complete(&self, success: Success) -> Result<(), Status> { @@ -448,6 +458,114 @@ fn replay_window_ms(config: &openshell_core::Config) -> i64 { ) * 1000 } +/// Observe an existing exec admission without admitting, executing, sweeping, +/// repairing, or extending it. The caller must supply the exact original request. +pub(super) async fn get_exec_sandbox_result( + state: &Arc, + request: Request, +) -> Result, Status> { + let original = request + .get_ref() + .original_request + .as_ref() + .ok_or_else(|| Status::invalid_argument("original_request is required"))?; + if original.encoded_len() > 4 * 1024 * 1024 { + return Err(Status::resource_exhausted("exec request exceeds 4 MiB")); + } + let request_id = validate_request_id(&original.request_id)?; + let principal = super::extract_principal(&request)?; + let Some(identity) = principal.user_identity() else { + return Err(crate::auth::audit::deny( + &principal, + crate::auth::audit::AuthzDenial::MethodNotPermitted, + "exec result read requires a user principal", + )); + }; + let scope = original.authorize(state, &principal).await?; + // A read cannot infer a historical target from its name. Current immutable + // workspace and sandbox authorization must still resolve to the claim. + let fingerprint_key = fingerprint_key(state).await?; + let payload_hash = fingerprint_key.fingerprint(original)?; + let protection = Protection { + key_id: fingerprint_key.id(), + effective_payload_hash: payload_hash.clone(), + effective_workspace_id: scope.workspace_id.clone(), + effective_target_id: scope.target_id.clone(), + }; + let (provider, issuer) = match identity.provider { + IdentityProvider::Oidc => ( + "oidc", + state + .config + .oidc + .as_ref() + .map_or("", |config| config.issuer.as_str()), + ), + IdentityProvider::Mtls => ( + if matches!(principal, Principal::Operator(_)) { + "mtls-operator" + } else { + "mtls" + }, + "", + ), + IdentityProvider::CloudflareAccess => ("cloudflare_access", ""), + IdentityProvider::LocalDev => ("local_dev", ""), + }; + let caller = hash_json(&serde_json::json!([provider, issuer, identity.subject,]))?; + let bucket = format!("_mutation/{caller}"); + let key = hash_json(&serde_json::json!([ + caller, + ::REPLAY_METHOD, + scope.name, + request_id + ]))?; + let row = state + .store + .get_by_name(OBJECT_TYPE, &bucket, &key) + .await + .map_err(storage_error)? + .ok_or_else(replay_unavailable)?; + let admission: Admission = serde_json::from_slice(&row.payload) + .map_err(|_| Status::internal("invalid durable mutation admission"))?; + if admission.format_version != 1 + || admission.payload_hash != payload_hash + || admission.workspace_id != scope.workspace_id + || admission.target_id != scope.target_id + || admission.protection.as_ref() != Some(&protection) + { + return Err(replay_unavailable()); + } + let (Some(Success::StreamTerminalResult { exit_code }), Some(terminal_at_ms)) = + (admission.success, admission.completed_at_ms) + else { + return Err(uncertain()); + }; + let expires_at_ms = terminal_at_ms.saturating_add(replay_window_ms(&state.config)); + if current_time_ms() >= expires_at_ms { + return Err(replay_unavailable()); + } + Ok(Response::new(GetExecSandboxResultResponse { + request_id, + claim_id: row.id, + resource_version: row.resource_version, + format_version: admission.format_version, + method: ::REPLAY_METHOD.into(), + original_scope: scope.name, + original_workspace_id: admission.workspace_id.unwrap_or_default(), + original_target_id: admission.target_id.unwrap_or_default(), + effective_workspace_id: protection.effective_workspace_id.unwrap_or_default(), + effective_target_id: protection.effective_target_id.unwrap_or_default(), + original_payload_fingerprint: admission.payload_hash, + effective_payload_fingerprint: protection.effective_payload_hash, + fingerprint_key_id: protection.key_id, + admitted_at_ms: row.created_at_ms, + terminal_at_ms, + expires_at_ms, + exit_code, + })) +} + /// Delete expired successful admissions for one bucket, or all buckets, in /// bounded batches. Returns whether any admission was removed. async fn sweep_expired( diff --git a/crates/openshell-server/src/grpc/mutation_replay/streaming.rs b/crates/openshell-server/src/grpc/mutation_replay/streaming.rs index b6e797f726..dc60f09d7a 100644 --- a/crates/openshell-server/src/grpc/mutation_replay/streaming.rs +++ b/crates/openshell-server/src/grpc/mutation_replay/streaming.rs @@ -62,7 +62,10 @@ async fn authorize( } fn stream_unavailable(success: Success) -> Status { - if !matches!(success, Success::StreamTerminal) { + if !matches!( + success, + Success::StreamTerminal | Success::StreamTerminalResult { .. } + ) { return super::replay_unavailable(); } rpc_error::failed_precondition( diff --git a/crates/openshell-server/src/grpc/mutation_replay/streaming/tests.rs b/crates/openshell-server/src/grpc/mutation_replay/streaming/tests.rs index db3ef352fa..dea3c631ff 100644 --- a/crates/openshell-server/src/grpc/mutation_replay/streaming/tests.rs +++ b/crates/openshell-server/src/grpc/mutation_replay/streaming/tests.rs @@ -5,13 +5,14 @@ use super::*; use crate::grpc::mutation_replay::tests::{reason, state_for}; use crate::grpc::mutation_replay::{ Admission, AuthorizationBarrier, Completion, OBJECT_TYPE, OriginalMutation, fingerprint, - replay_window_ms, run, + get_exec_sandbox_result, replay_window_ms, run, }; use crate::grpc::test_support::authed_request; use crate::persistence::{ObjectType, WriteCondition, current_time_ms}; use openshell_core::proto::datamodel::v1::ObjectMeta; use openshell_core::proto::{ - GatewayMessage, Sandbox, SandboxPhase, SandboxStatus, gateway_message, + GatewayMessage, GetExecSandboxResultRequest, Sandbox, SandboxPhase, SandboxStatus, + gateway_message, }; use openshell_core::{ObjectId, ObjectName}; use prost::Message; @@ -269,20 +270,183 @@ async fn confirmed_exit_including_nonzero_and_124_finalizes_before_output_delive Some(code) ); assert_eq!( - reason(&run(&state, authed_request(req)).await.unwrap_err()), + reason(&run(&state, authed_request(req.clone())).await.unwrap_err()), "REQUEST_STREAM_UNAVAILABLE" ); + let observed = get_exec_sandbox_result( + &state, + authed_request(GetExecSandboxResultRequest { + original_request: Some(req.clone()), + }), + ) + .await + .unwrap() + .into_inner(); + assert_eq!(observed.request_id, req.request_id); + assert_eq!(observed.exit_code, code); + assert_eq!(observed.method, "ExecSandbox"); + assert!(!observed.claim_id.is_empty()); + assert_eq!(observed.resource_version, 2); + assert_eq!(observed.format_version, 1); + assert_eq!(observed.original_scope, "default"); + assert_eq!( + observed.original_workspace_id, + observed.effective_workspace_id + ); + assert_eq!(observed.original_target_id, observed.effective_target_id); + assert_eq!(observed.original_target_id, sandbox_id(&state, &req).await); + assert!(!observed.original_payload_fingerprint.is_empty()); + assert_eq!( + observed.original_payload_fingerprint, + observed.effective_payload_fingerprint + ); + assert!(!observed.fingerprint_key_id.is_empty()); + assert!(observed.admitted_at_ms <= observed.terminal_at_ms); + assert!(observed.terminal_at_ms < observed.expires_at_ms); + let (mut client, server) = wire_client(state.clone(), None, None).await; + let wire_result = client + .get_exec_sandbox_result(GetExecSandboxResultRequest { + original_request: Some(req.clone()), + }) + .await + .unwrap() + .into_inner(); + assert_eq!(wire_result.claim_id, observed.claim_id); + assert_eq!(wire_result.exit_code, code); + server.abort(); + let mut changed = req.clone(); + changed.command.push("foreign-command".into()); + assert!( + get_exec_sandbox_result( + &state, + authed_request(GetExecSandboxResultRequest { + original_request: Some(changed), + }), + ) + .await + .is_err(), + "a changed command cannot adopt the original result" + ); assert!( - owner.stream_terminal().await.is_err(), + owner.stream_terminal(code).await.is_err(), "CAS rejects a second finalization" ); let row = completion(&state).await; let admission: Admission = serde_json::from_slice(&row.admission).unwrap(); - assert!(matches!(admission.success, Some(Success::StreamTerminal))); + assert!(matches!( + admission.success, + Some(Success::StreamTerminalResult { exit_code }) if exit_code == code + )); assert!(admission.completed_at_ms.is_some()); } } +#[tokio::test] +async fn result_read_refuses_pending_legacy_and_foreign_claims_without_writes() { + let directory = tempfile::tempdir().unwrap(); + let state = setup("sqlite::memory:", &directory).await; + let req = request(&state).await; + let mut messages = register(&state, &sandbox_id(&state, &req).await); + drop(run(&state, authed_request(req.clone())).await.unwrap()); + receive_relay(&state, &mut messages).await; + let read = |original_request| { + authed_request(GetExecSandboxResultRequest { + original_request: Some(original_request), + }) + }; + assert!( + get_exec_sandbox_result(&state, read(req.clone())) + .await + .is_err(), + "a pending admission has no terminal result" + ); + let mut foreign = req.clone(); + foreign.request_id = uuid::Uuid::new_v4().to_string(); + assert!( + get_exec_sandbox_result(&state, read(foreign)) + .await + .is_err(), + "another request UUID cannot find this claim" + ); + let owner = completion(&state).await; + owner.complete(Success::StreamTerminal).await.unwrap(); + let before = state + .store + .get_by_name(OBJECT_TYPE, &owner.bucket, &owner.key) + .await + .unwrap() + .unwrap(); + assert!( + get_exec_sandbox_result(&state, read(req)).await.is_err(), + "a legacy terminal marker has no observed SSH exit code" + ); + let after = state + .store + .get_by_name(OBJECT_TYPE, &owner.bucket, &owner.key) + .await + .unwrap() + .unwrap(); + assert_eq!(before.resource_version, after.resource_version); + assert_eq!(before.payload, after.payload); +} + +#[tokio::test] +async fn result_read_refuses_rotated_key_and_expired_claim_without_relaunch() { + let directory = tempfile::tempdir().unwrap(); + let state = setup("sqlite::memory:", &directory).await; + let req = request(&state).await; + let mut messages = register(&state, &sandbox_id(&state, &req).await); + drop(run(&state, authed_request(req.clone())).await.unwrap()); + receive_relay(&state, &mut messages).await; + let owner = completion(&state).await; + owner.stream_terminal(7).await.unwrap(); + let read = || { + authed_request(GetExecSandboxResultRequest { + original_request: Some(req.clone()), + }) + }; + let key_path = directory.path().join("key"); + let original_key = std::fs::read(&key_path).unwrap(); + std::fs::write(&key_path, b"rotated-test-key").unwrap(); + assert!(get_exec_sandbox_result(&state, read()).await.is_err()); + std::fs::write(&key_path, original_key).unwrap(); + assert_eq!( + get_exec_sandbox_result(&state, read()) + .await + .unwrap() + .into_inner() + .exit_code, + 7 + ); + let row = state + .store + .get_by_name(OBJECT_TYPE, &owner.bucket, &owner.key) + .await + .unwrap() + .unwrap(); + let mut admission: Admission = serde_json::from_slice(&row.payload).unwrap(); + admission.completed_at_ms = Some(current_time_ms() - replay_window_ms(&state.config) - 1); + let payload = serde_json::to_vec(&admission).unwrap(); + state + .store + .put_if( + OBJECT_TYPE, + &row.id, + &row.name, + &row.workspace, + &payload, + None, + WriteCondition::MatchResourceVersion(row.resource_version), + ) + .await + .unwrap(); + assert!(get_exec_sandbox_result(&state, read()).await.is_err()); + assert!( + messages.try_recv().is_err(), + "a result read never opens a relay" + ); +} + #[tokio::test] async fn timeout_and_lost_exit_status_never_finalize_or_expire_pending_launches() { let directory = tempfile::tempdir().unwrap(); @@ -414,7 +578,7 @@ async fn exec_restart_preserves_pending_and_terminal_fences_and_reauthorizes() { reason(&run(&state, authed_request(req.clone())).await.unwrap_err()), "REQUEST_OUTCOME_UNCERTAIN" ); - completion(&state).await.stream_terminal().await.unwrap(); + completion(&state).await.stream_terminal(0).await.unwrap(); drop(state); let state = setup(&url, &directory).await; let mut sandbox: Sandbox = state @@ -429,6 +593,19 @@ async fn exec_restart_preserves_pending_and_terminal_fences_and_reauthorizes() { reason(&run(&state, authed_request(req.clone())).await.unwrap_err()), "REQUEST_STREAM_UNAVAILABLE" ); + assert_eq!( + get_exec_sandbox_result( + &state, + authed_request(GetExecSandboxResultRequest { + original_request: Some(req.clone()), + }), + ) + .await + .unwrap() + .into_inner() + .exit_code, + 0 + ); let mut unauthorized = authed_request(req.clone()); if let Principal::User(user) = unauthorized .extensions_mut() @@ -441,6 +618,23 @@ async fn exec_restart_preserves_pending_and_terminal_fences_and_reauthorizes() { run(&state, unauthorized).await.unwrap_err().code(), tonic::Code::NotFound ); + let mut unauthorized_read = authed_request(GetExecSandboxResultRequest { + original_request: Some(req.clone()), + }); + if let Principal::User(user) = unauthorized_read + .extensions_mut() + .get_mut::() + .unwrap() + { + user.identity.roles.clear(); + } + assert_eq!( + get_exec_sandbox_result(&state, unauthorized_read) + .await + .unwrap_err() + .code(), + tonic::Code::NotFound + ); state .store .delete(Sandbox::object_type(), sandbox.object_id()) @@ -584,7 +778,7 @@ async fn replacement_cannot_reuse_an_exec_claim_or_receive_its_admitted_launch() let owner = completion(&state).await; owner.ensure_target(&id).unwrap(); if terminal { - owner.stream_terminal().await.unwrap(); + owner.stream_terminal(0).await.unwrap(); } let mut replacement: Sandbox = state.store.get_message(&id).await.unwrap().unwrap(); state @@ -600,6 +794,17 @@ async fn replacement_cannot_reuse_an_exec_claim_or_receive_its_admitted_launch() reason(&run(&state, authed_request(req.clone())).await.unwrap_err()), "REQUEST_REPLAY_UNAVAILABLE" ); + assert!( + get_exec_sandbox_result( + &state, + authed_request(GetExecSandboxResultRequest { + original_request: Some(req.clone()), + }), + ) + .await + .is_err(), + "a replacement cannot inherit the old terminal result" + ); // Simulate replacement after admission, before the owner resolves its // public name again. The original claim must not launch on the new ID. let mut admitted = authed_request(req); @@ -669,7 +874,7 @@ async fn interactive_wire_start_is_admitted_under_its_own_method_namespace() { ), "REQUEST_OUTCOME_UNCERTAIN" ); - owner.stream_terminal().await.unwrap(); + owner.stream_terminal(0).await.unwrap(); assert_eq!( reason( &client diff --git a/crates/openshell-server/src/grpc/sandbox.rs b/crates/openshell-server/src/grpc/sandbox.rs index cdc701cbc1..d2ee030145 100644 --- a/crates/openshell-server/src/grpc/sandbox.rs +++ b/crates/openshell-server/src/grpc/sandbox.rs @@ -3929,7 +3929,7 @@ pub(super) async fn wait_for_exec_terminal( }; let exit_code = result?; if let Some(completion) = completion { - completion.stream_terminal().await?; + completion.stream_terminal(exit_code).await?; } Ok(Some(exit_code)) } diff --git a/crates/openshell-server/tests/common/mod.rs b/crates/openshell-server/tests/common/mod.rs index 71e3c6b0e6..5284674910 100644 --- a/crates/openshell-server/tests/common/mod.rs +++ b/crates/openshell-server/tests/common/mod.rs @@ -52,6 +52,13 @@ pub struct TestOpenShell; #[tonic::async_trait] impl OpenShell for TestOpenShell { + async fn get_exec_sandbox_result( + &self, + _request: tonic::Request, + ) -> Result, Status> { + Err(Status::unimplemented("not used by this test server")) + } + async fn get_sandbox_provider_access_token( &self, _request: tonic::Request, diff --git a/crates/openshell-server/tests/supervisor_relay_integration.rs b/crates/openshell-server/tests/supervisor_relay_integration.rs index bff7fe5c67..5b0f107641 100644 --- a/crates/openshell-server/tests/supervisor_relay_integration.rs +++ b/crates/openshell-server/tests/supervisor_relay_integration.rs @@ -50,6 +50,13 @@ struct RelayGateway { #[tonic::async_trait] impl OpenShell for RelayGateway { + async fn get_exec_sandbox_result( + &self, + _request: tonic::Request, + ) -> Result, Status> { + Err(Status::unimplemented("not used by this test server")) + } + async fn get_sandbox_provider_access_token( &self, _request: tonic::Request, diff --git a/docs/sdk/api-errors.mdx b/docs/sdk/api-errors.mdx index 153e271a37..2def6222fc 100644 --- a/docs/sdk/api-errors.mdx +++ b/docs/sdk/api-errors.mdx @@ -254,7 +254,23 @@ cannot be submitted through a duplicate stream. | Changed start payload | `REQUEST_ID_PAYLOAD_MISMATCH`. The changed command does not run. | | Sandbox replaced under the same name | `REQUEST_REPLAY_UNAVAILABLE`. The replacement does not receive the command. | -The terminal receipt contains only a marker and completion time, not commands, +For a noninteractive `ExecSandbox` request, `GetExecSandboxResult` can read a +newly recorded terminal result without launching or reattaching the command. +Supply the exact original `ExecSandboxRequest`, including its request ID. The +gateway rechecks the current caller, workspace, sandbox identity, protected +request fingerprint, and retention window. A confirmed result includes the +immutable claim ID, original and effective request commitments, admission and +terminal timestamps, and the observed SSH exit code. A nonzero code is a +terminal failure, not a successful application result. Admission time is not +the process start time. + +The read does not return stdout, stderr, or a replacement stream. It refuses +pending, expired, mismatched, or legacy terminal-marker records without +starting a new attempt. Interactive exec has no corresponding terminal-result +read in this API. Keep the original request ID and reconcile uncertain command +effects through the owning workflow. + +The terminal record stores the observed exit code and completion time, not commands, environment values, stdin, stdout, or stderr. Receiving a stream handle is not completion. A gateway-generated timeout exit code of `124` does not prove the remote process stopped, so it leaves the admission unresolved. A confirmed remote diff --git a/proto/openshell.proto b/proto/openshell.proto index 56a58e17f0..c355e308cc 100644 --- a/proto/openshell.proto +++ b/proto/openshell.proto @@ -278,6 +278,16 @@ service OpenShell { }; } + // Read a durably confirmed SSH exit result for the exact original exec + // request. This never starts, retries, or reattaches an execution. + rpc GetExecSandboxResult(GetExecSandboxResultRequest) returns (GetExecSandboxResultResponse) { + option (openshell.options.v1.authorization) = { + auth_mode: "bearer" + scope: "sandbox:read" + workspace_role: "user" + }; + } + // Forward one CLI-side TCP connection to a loopback TCP target in a sandbox. rpc ForwardTcp(stream TcpForwardFrame) returns (stream TcpForwardFrame) { option (openshell.options.v1.authorization) = { @@ -2145,6 +2155,31 @@ message ExecSandboxRequest { string request_id = 11; } +message GetExecSandboxResultRequest { + // The exact original request, including its caller-owned request_id. + ExecSandboxRequest original_request = 1; +} + +message GetExecSandboxResultResponse { + string request_id = 1; + string claim_id = 2; + uint64 resource_version = 3; + uint32 format_version = 4; + string method = 5; + string original_scope = 6; + string original_workspace_id = 7; + string original_target_id = 8; + string effective_workspace_id = 9; + string effective_target_id = 10; + string original_payload_fingerprint = 11; + string effective_payload_fingerprint = 12; + string fingerprint_key_id = 13; + int64 admitted_at_ms = 14; + int64 terminal_at_ms = 15; + int64 expires_at_ms = 16; + int32 exit_code = 17; +} + // One stdout chunk from a sandbox exec. message ExecSandboxStdout { bytes data = 1;