diff --git a/.agents/skills/tui-development/SKILL.md b/.agents/skills/tui-development/SKILL.md index cae3b3ef5e..d5ac70c1af 100644 --- a/.agents/skills/tui-development/SKILL.md +++ b/.agents/skills/tui-development/SKILL.md @@ -308,10 +308,16 @@ fn draw_detail_popup(frame: &mut Frame<'_>, data: &MyData, area: Rect, theme: &T Always show a y/n confirm dialog before delete, stop, or other irreversible operations. ``` -Delete sandbox 'my-sandbox'? [y] Confirm [Esc] Cancel +Delete sandbox 'my-sandbox'? +Workspace: team-a +Sandbox ID: my-sandbox-id + +[y] Confirm [Esc] Cancel ``` -The `confirm_delete` flag in `App` gates destructive key handling — while true, only `y`, `n`, and `Esc` are processed. +Pressing `d` captures the sandbox name, workspace, and ID shown in the dialog. +Background refreshes do not change what `y` confirms. Press `n` or `Esc` to +cancel. The TUI refuses to open confirmation when the sandbox ID is missing. ### CLI parity @@ -320,7 +326,7 @@ TUI actions should parallel `openshell` CLI commands so users have familiar ment | CLI Command | TUI Equivalent | | --- | --- | | `openshell sandbox list` | Sandbox table on Dashboard | -| `openshell sandbox delete ` | `[d]` on sandbox detail, then `[y]` to confirm | +| `openshell sandbox delete --id ` | `[d]` on sandbox detail, then `[y]` to confirm. A gateway that supports conditional deletion refuses to delete a same-name replacement; older gateways ignore the ID condition. | | `openshell sandbox create` | `[c]` on sandbox panel to open create form | | `openshell sandbox connect` | `[s]` on sandbox policy view to launch SSH shell | | `openshell logs ` | `[l]` on sandbox detail to open log viewer | @@ -488,6 +494,7 @@ use openshell_core::proto::{ name: sandbox_name, workspace_scope: Some(workspace_selector(workspace)), allow_missing: true, + expected_sandbox_id: Some(sandbox_id), ..Default::default() }; ``` diff --git a/crates/openshell-cli/src/main.rs b/crates/openshell-cli/src/main.rs index 5cca485033..722c08261c 100644 --- a/crates/openshell-cli/src/main.rs +++ b/crates/openshell-cli/src/main.rs @@ -1780,12 +1780,21 @@ enum SandboxCommands { #[command(help_template = LEAF_HELP_TEMPLATE, next_help_heading = "FLAGS")] Delete { /// Sandbox names. - #[arg(required_unless_present = "all", num_args = 1.., value_name = "NAME", add = ArgValueCompleter::new(completers::complete_sandbox_names))] + #[arg(required_unless_present_any = ["all", "id"], num_args = 1.., value_name = "NAME", add = ArgValueCompleter::new(completers::complete_sandbox_names))] names: Vec, /// Delete all sandboxes. #[arg(long, conflicts_with = "names")] all: bool, + + /// Delete only if the name still resolves to this sandbox ID. Fails + /// instead of deleting a same-name replacement. Requires one NAME. + #[arg(long = "expected-id", value_name = "ID", conflicts_with = "all")] + expected_id: Option, + + /// Delete the sandbox with this ID, never a same-name replacement. + #[arg(long, value_name = "ID", conflicts_with_all = ["names", "all", "expected_id"])] + id: Option, }, /// Stop a sandbox while preserving its workspace. @@ -3071,7 +3080,7 @@ async fn run_async() -> Result<()> { } } }; - if run::stop_forward(&workspace, &name, port)? { + if run::stop_forward(&workspace, &name, port, None)? { eprintln!( "{} Stopped forward of port {port} for sandbox {name}", "✓".green().bold(), @@ -3854,16 +3863,33 @@ async fn run_async() -> Result<()> { ) .await?; } - SandboxCommands::Delete { names, all } => { - run::sandbox_delete( - endpoint, - &names, - all, - &cli.workspace, - &tls, - &ctx.name, - ) - .await?; + SandboxCommands::Delete { + names, + all, + expected_id, + id, + } => { + if let Some(id) = id { + run::sandbox_delete_by_id( + endpoint, + &id, + &cli.workspace, + &tls, + &ctx.name, + ) + .await?; + } else { + run::sandbox_delete( + endpoint, + &names, + all, + expected_id.as_deref(), + &cli.workspace, + &tls, + &ctx.name, + ) + .await?; + } } SandboxCommands::Stop { name } => { let name = resolve_sandbox_name(name, &ctx.name, &cli.workspace)?; @@ -6017,6 +6043,73 @@ mod tests { )); } + #[test] + fn sandbox_delete_accepts_expected_id_but_not_with_all() { + let cli = Cli::try_parse_from([ + "openshell", + "sandbox", + "delete", + "my-box", + "--expected-id", + "sandbox-observed", + ]) + .expect("sandbox delete --expected-id should parse"); + assert!(matches!( + cli.command, + Some(Commands::Sandbox { + command: Some(SandboxCommands::Delete { + expected_id: Some(ref id), + .. + }) + }) if id == "sandbox-observed" + )); + + let result = Cli::try_parse_from([ + "openshell", + "sandbox", + "delete", + "--all", + "--expected-id", + "sandbox-observed", + ]); + assert!(result.is_err(), "--expected-id and --all should conflict"); + } + + #[test] + fn sandbox_delete_accepts_id_without_names() { + let cli = + Cli::try_parse_from(["openshell", "sandbox", "delete", "--id", "sandbox-observed"]) + .expect("sandbox delete --id should parse without a name"); + assert!(matches!( + cli.command, + Some(Commands::Sandbox { + command: Some(SandboxCommands::Delete { + id: Some(ref id), + .. + }) + }) if id == "sandbox-observed" + )); + + for conflicting in [ + vec!["openshell", "sandbox", "delete", "my-box", "--id", "x"], + vec!["openshell", "sandbox", "delete", "--all", "--id", "x"], + vec![ + "openshell", + "sandbox", + "delete", + "--id", + "x", + "--expected-id", + "y", + ], + ] { + assert!( + Cli::try_parse_from(&conflicting).is_err(), + "{conflicting:?} should conflict" + ); + } + } + #[test] fn sandbox_list_json_conflicts_with_ids() { let result = Cli::try_parse_from(["openshell", "sandbox", "list", "-o", "json", "--ids"]); diff --git a/crates/openshell-cli/src/run.rs b/crates/openshell-cli/src/run.rs index feb05f2f45..00edda5237 100644 --- a/crates/openshell-cli/src/run.rs +++ b/crates/openshell-cli/src/run.rs @@ -414,7 +414,7 @@ fn validate_memory_quantity(value: &str) -> Result { async fn finalize_sandbox_create_session( server: &str, - sandbox_name: &str, + sandbox: &Sandbox, persist: bool, session_result: Result, workspace: &str, @@ -425,8 +425,8 @@ async fn finalize_sandbox_create_session( return session_result; } - let names = [sandbox_name.to_string()]; - if let Err(err) = sandbox_delete(server, &names, false, workspace, tls, gateway).await { + let sandbox_name = sandbox.object_name(); + if let Err(err) = delete_ephemeral_sandbox(server, sandbox, workspace, tls, gateway).await { if let Ok(exit_code) = session_result.as_ref() { return Err(miette::miette!( "sandbox command exited with status {exit_code}, but ephemeral cleanup failed: {err}" @@ -438,6 +438,38 @@ async fn finalize_sandbox_create_session( session_result } +/// Delete the sandbox this command created, never a same-name replacement. +/// +/// A replacement means the created sandbox is already gone, so cleanup has +/// nothing left to do. +async fn delete_ephemeral_sandbox( + server: &str, + sandbox: &Sandbox, + workspace: &str, + tls: &TlsOptions, + gateway: &str, +) -> Result<()> { + let name = sandbox.object_name(); + let expected_sandbox_id = Some(sandbox.object_id()) + .filter(|id| !id.is_empty()) + .ok_or_else(|| { + miette::miette!("created sandbox is missing its ID; refusing unsafe cleanup") + })?; + let mut client = grpc_client(server, tls).await?; + match delete_sandbox_entry( + &mut client, + workspace, + gateway, + name, + Some(expected_sandbox_id), + ) + .await + { + SandboxDeleteEntry::Deleted | SandboxDeleteEntry::Replaced => Ok(()), + SandboxDeleteEntry::Failed => aggregate_delete_failures("sandbox", &[name.to_string()]), + } +} + /// Configuration for creating a sandbox via the CLI. /// /// Infrastructure parameters (`server`, `gateway_name`, `tls`) remain positional @@ -1711,7 +1743,7 @@ pub async fn sandbox_create( finalize_sandbox_create_session( &effective_server, - &sandbox_name, + &sandbox, persist, connect_result, workspace, @@ -1737,7 +1769,7 @@ pub async fn sandbox_create( .await; finalize_sandbox_create_session( &effective_server, - &sandbox_name, + &sandbox, persist, connect_result, workspace, @@ -1776,7 +1808,7 @@ pub async fn sandbox_create( ); finalize_sandbox_create_session( &effective_server, - &sandbox_name, + &sandbox, persist || last_sandbox .status @@ -4528,37 +4560,195 @@ fn labels_display(labels: &HashMap) -> String { pairs.join(", ") } +/// Result of deleting one named sandbox. +#[derive(Debug, PartialEq, Eq)] +enum SandboxDeleteEntry { + /// Deleted, deletion accepted, or already absent. + Deleted, + /// The name now identifies a different sandbox than the expected ID, so + /// nothing was deleted. + Replaced, + Failed, +} + +/// Delete one named sandbox and report the outcome on the terminal. +/// +/// Conditional deletion stops only forwards owned by the expected sandbox ID, +/// after the gateway accepts the deletion or reports the sandbox already gone. +async fn delete_sandbox_entry( + client: &mut GrpcClient, + workspace: &str, + gateway: &str, + name: &str, + expected_sandbox_id: Option<&str>, +) -> SandboxDeleteEntry { + let stop_forwards = || { + if let Ok(stopped) = stop_forwards_for_sandbox(workspace, name, expected_sandbox_id) { + for port in stopped { + eprintln!( + "{} Stopped forward of port {port} for sandbox {name}", + "✓".green().bold(), + ); + } + } + }; + // Stop any background port forwards for this sandbox before deleting. + if expected_sandbox_id.is_none() { + stop_forwards(); + } + + let response = match client + .delete_sandbox(DeleteSandboxRequest { + request_id: String::new(), + allow_missing: true, + expected_sandbox_id: expected_sandbox_id.map(str::to_string), + name: name.to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + workspace.to_string(), + )), + }) + .await + { + Ok(response) => response, + Err(status) if is_sandbox_identity_mismatch(&status) => { + eprintln!( + "{} Sandbox {name} now refers to a different sandbox; it was not deleted", + "!".red().bold() + ); + return SandboxDeleteEntry::Replaced; + } + Err(status) => { + eprintln!( + "{} Failed to delete sandbox {name}: {status}", + "!".red().bold() + ); + return SandboxDeleteEntry::Failed; + } + }; + + match response.into_inner().outcome() { + DeletionOutcome::Completed => println!("{} Deleted sandbox {name}", "✓".green().bold()), + DeletionOutcome::Accepted => println!( + "{} Sandbox {name} deletion accepted; cleanup is pending", + "✓".green().bold() + ), + DeletionOutcome::AlreadyAbsent => { + println!("{} Sandbox {name} already deleted", "✓".green().bold()); + } + DeletionOutcome::Unspecified => { + eprintln!( + "{} Unsupported deletion outcome for sandbox {name}", + "!".red().bold() + ); + return SandboxDeleteEntry::Failed; + } + } + if expected_sandbox_id.is_some() { + stop_forwards(); + } + clear_last_sandbox_if_matches(gateway, workspace, name); + SandboxDeleteEntry::Deleted +} + +fn is_sandbox_identity_mismatch(status: &Status) -> bool { + use openshell_core::rpc_error::StatusExt; + status.code() == Code::Aborted + && status + .get_error_details() + .error_info() + .is_some_and(|info| info.reason == "SANDBOX_IDENTITY_MISMATCH") +} + +/// List every sandbox in one workspace. +async fn list_workspace_sandboxes( + client: &mut GrpcClient, + workspace: &str, +) -> Result> { + let mut page_token = String::new(); + let mut sandboxes = Vec::new(); + loop { + let response = client + .list_sandboxes(ListSandboxesRequest { + page_size: 1000, + page_token, + label_selector: String::new(), + workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), + }) + .await + .into_diagnostic()? + .into_inner(); + sandboxes.extend(response.sandboxes); + if response.next_page_token.is_empty() { + return Ok(sandboxes); + } + page_token = response.next_page_token; + } +} + +/// Delete the sandbox with an immutable ID. +/// +/// The gateway addresses deletion by name, so this looks up the name that +/// currently has `sandbox_id` and sends a delete conditioned on that ID. If the +/// sandbox is deleted or replaced between the lookup and the delete, the +/// gateway refuses, and the sandbox with this ID is already gone. +pub async fn sandbox_delete_by_id( + server: &str, + sandbox_id: &str, + workspace: &str, + tls: &TlsOptions, + gateway: &str, +) -> Result<()> { + if sandbox_id.trim().is_empty() { + return Err(miette::miette!("--id must not be empty")); + } + let mut client = grpc_client(server, tls).await?; + let Some(sandbox) = list_workspace_sandboxes(&mut client, workspace) + .await? + .into_iter() + .find(|sandbox| sandbox.object_id() == sandbox_id) + else { + println!( + "{} Sandbox {sandbox_id} already deleted", + "✓".green().bold() + ); + return Ok(()); + }; + let name = sandbox.object_name(); + match delete_sandbox_entry(&mut client, workspace, gateway, name, Some(sandbox_id)).await { + SandboxDeleteEntry::Deleted => Ok(()), + SandboxDeleteEntry::Replaced => { + println!( + "{} Sandbox {sandbox_id} already deleted", + "✓".green().bold() + ); + Ok(()) + } + SandboxDeleteEntry::Failed => aggregate_delete_failures("sandbox", &[name.to_string()]), + } +} + /// Delete a sandbox by name, or all sandboxes when `all` is true. +/// +/// With `expected_sandbox_id`, the single named sandbox is deleted only if it +/// still has that ID, so a same-name replacement is never deleted. pub async fn sandbox_delete( server: &str, names: &[String], all: bool, + expected_sandbox_id: Option<&str>, workspace: &str, tls: &TlsOptions, gateway: &str, ) -> Result<()> { + if expected_sandbox_id.is_some() && (all || names.len() != 1) { + return Err(miette::miette!( + "--expected-id requires exactly one sandbox name" + )); + } let mut client = grpc_client(server, tls).await?; let names_to_delete: Vec = if all { - let mut page_token = String::new(); - let mut sandboxes = Vec::new(); - loop { - let response = client - .list_sandboxes(ListSandboxesRequest { - page_size: 1000, - page_token, - label_selector: String::new(), - workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), - }) - .await - .into_diagnostic()? - .into_inner(); - sandboxes.extend(response.sandboxes); - if response.next_page_token.is_empty() { - break; - } - page_token = response.next_page_token; - } + let sandboxes = list_workspace_sandboxes(&mut client, workspace).await?; if sandboxes.is_empty() { println!("No sandboxes to delete."); return Ok(()); @@ -4573,57 +4763,11 @@ pub async fn sandbox_delete( let mut failures = Vec::new(); for name in &names_to_delete { - // Stop any background port forwards for this sandbox before deleting. - if let Ok(stopped) = stop_forwards_for_sandbox(workspace, name) { - for port in stopped { - eprintln!( - "{} Stopped forward of port {port} for sandbox {name}", - "✓".green().bold(), - ); - } - } - - let response = match client - .delete_sandbox(DeleteSandboxRequest { - request_id: String::new(), - allow_missing: true, - name: name.clone(), - workspace_scope: Some(openshell_core::proto::workspace_selector( - workspace.to_string(), - )), - }) - .await + if delete_sandbox_entry(&mut client, workspace, gateway, name, expected_sandbox_id).await + != SandboxDeleteEntry::Deleted { - Ok(response) => response, - Err(status) => { - eprintln!( - "{} Failed to delete sandbox {name}: {status}", - "!".red().bold() - ); - failures.push(name.clone()); - continue; - } - }; - - match response.into_inner().outcome() { - DeletionOutcome::Completed => println!("{} Deleted sandbox {name}", "✓".green().bold()), - DeletionOutcome::Accepted => println!( - "{} Sandbox {name} deletion accepted; cleanup is pending", - "✓".green().bold() - ), - DeletionOutcome::AlreadyAbsent => { - println!("{} Sandbox {name} already deleted", "✓".green().bold()); - } - DeletionOutcome::Unspecified => { - eprintln!( - "{} Unsupported deletion outcome for sandbox {name}", - "!".red().bold() - ); - failures.push(name.clone()); - continue; - } + failures.push(name.clone()); } - clear_last_sandbox_if_matches(gateway, workspace, name); } aggregate_delete_failures("sandbox", &failures) @@ -4636,7 +4780,7 @@ pub async fn sandbox_stop( workspace: &str, tls: &TlsOptions, ) -> Result<()> { - if let Ok(stopped) = stop_forwards_for_sandbox(workspace, name) { + if let Ok(stopped) = stop_forwards_for_sandbox(workspace, name, None) { for port in stopped { eprintln!( "{} Stopped forward of port {port} for sandbox {name}", @@ -4719,7 +4863,7 @@ pub async fn sandbox_suspend( .sandbox .ok_or_else(|| miette!("gateway returned no sandbox after suspend"))?; wait_for_lifecycle_phase(&mut client, sandbox, SandboxPhase::Suspended).await?; - if let Ok(stopped) = stop_forwards_for_sandbox(workspace, name) { + if let Ok(stopped) = stop_forwards_for_sandbox(workspace, name, None) { for port in stopped { eprintln!( "{} Stopped forward of port {port} for sandbox {name}", diff --git a/crates/openshell-cli/tests/sandbox_create_lifecycle_integration.rs b/crates/openshell-cli/tests/sandbox_create_lifecycle_integration.rs index 8d616c69ba..d35272417d 100644 --- a/crates/openshell-cli/tests/sandbox_create_lifecycle_integration.rs +++ b/crates/openshell-cli/tests/sandbox_create_lifecycle_integration.rs @@ -68,6 +68,11 @@ struct SandboxState { reject_cedar_policy: Arc, health_requests: Arc, deleted_names: Arc>>>, + deleted_expected_ids: Arc>>>, + /// Make conditional `DeleteSandbox` calls report a same-name replacement. + delete_identity_mismatch: Arc, + /// Sandboxes returned by `ListSandboxes`. + listed_sandboxes: Arc>>, create_requests: Arc>>, policy_update_requests: Arc, /// The policy `GetSandboxConfig` returns. @@ -357,7 +362,10 @@ impl OpenShell for TestOpenShell { &self, _request: tonic::Request, ) -> Result, Status> { - Ok(Response::new(ListSandboxesResponse::default())) + Ok(Response::new(ListSandboxesResponse { + sandboxes: self.state.listed_sandboxes.lock().await.clone(), + ..Default::default() + })) } async fn create_sandbox_template( @@ -487,6 +495,19 @@ impl OpenShell for TestOpenShell { .lock() .await .push(vec![request.name.clone()]); + self.state + .deleted_expected_ids + .lock() + .await + .push(request.expected_sandbox_id.clone()); + if request.expected_sandbox_id.is_some() + && self.state.delete_identity_mismatch.load(Ordering::SeqCst) + { + return Err(openshell_core::rpc_error::aborted( + "SANDBOX_IDENTITY_MISMATCH", + "sandbox identity does not match expected_sandbox_id", + )); + } let delete_failure = self.state.fail_delete_sandbox_message.lock().await.take(); if let Some(message) = delete_failure { return Err(Status::internal(message)); @@ -1587,6 +1608,7 @@ async fn sandbox_delete_continues_after_entry_failure() { &server.endpoint, &["failing-sandbox".to_string(), "later-sandbox".to_string()], false, + None, "default", &tls, "openshell", @@ -1608,6 +1630,204 @@ async fn sandbox_delete_continues_after_entry_failure() { ); } +#[tokio::test] +async fn sandbox_delete_forwards_expected_id_for_one_name() { + let server = run_server().await; + let tls = test_tls(&server); + + run::sandbox_delete( + &server.endpoint, + &["observed".to_string()], + false, + Some("sandbox-observed"), + "default", + &tls, + "openshell", + ) + .await + .expect("conditional delete should succeed"); + + let err = run::sandbox_delete( + &server.endpoint, + &["first".to_string(), "second".to_string()], + false, + Some("sandbox-observed"), + "default", + &tls, + "openshell", + ) + .await + .expect_err("an expected ID cannot apply to several names"); + assert!(err.to_string().contains("exactly one sandbox name")); + + assert_eq!( + deleted_names(&server).await, + vec![vec!["observed".to_string()]] + ); + assert_eq!( + *server.openshell.state.deleted_expected_ids.lock().await, + vec![Some("sandbox-observed".to_string())] + ); +} + +fn listed_sandbox(id: &str, name: &str) -> Sandbox { + Sandbox { + metadata: Some(openshell_core::proto::datamodel::v1::ObjectMeta { + id: id.to_string(), + name: name.to_string(), + workspace: "default".to_string(), + ..Default::default() + }), + ..Default::default() + } +} + +#[tokio::test] +async fn sandbox_delete_by_id_deletes_the_named_sandbox_with_that_id() { + let server = run_server().await; + let tls = test_tls(&server); + *server.openshell.state.listed_sandboxes.lock().await = vec![ + listed_sandbox("sandbox-other", "other"), + listed_sandbox("sandbox-target", "target"), + ]; + + run::sandbox_delete_by_id( + &server.endpoint, + "sandbox-target", + "default", + &tls, + "openshell", + ) + .await + .expect("delete by ID should succeed"); + + assert_eq!( + deleted_names(&server).await, + vec![vec!["target".to_string()]] + ); + assert_eq!( + *server.openshell.state.deleted_expected_ids.lock().await, + vec![Some("sandbox-target".to_string())] + ); +} + +#[tokio::test] +async fn sandbox_delete_preserves_replacement_forward_after_success() { + use openshell_core::forward::{read_forward_pid, write_forward_pid}; + + let server = run_server().await; + let tls = test_tls(&server); + let config_dir = helpers::tempdir().unwrap(); + Environment::new() + .set("XDG_CONFIG_HOME", config_dir.path()) + .run_async(async { + // A completed receipt can refer to the original sandbox even + // after a replacement has opened a forward under the same name. + for (port, id) in [(31001, "original"), (31002, "replacement"), (31003, "")] { + write_forward_pid( + "default", + "reused", + port, + std::process::id(), + id, + "127.0.0.1", + ) + .unwrap(); + } + + run::sandbox_delete( + &server.endpoint, + &["reused".to_string()], + false, + Some("original"), + "default", + &tls, + "openshell", + ) + .await + .expect("the original sandbox deletion completed"); + + assert!(read_forward_pid("default", "reused", 31001).is_none()); + assert_eq!( + read_forward_pid("default", "reused", 31002) + .and_then(|record| record.sandbox_id) + .as_deref(), + Some("replacement") + ); + assert!(read_forward_pid("default", "reused", 31003).is_some()); + }) + .await; +} + +#[tokio::test] +async fn sandbox_delete_by_id_treats_missing_or_replaced_as_deleted() { + let server = run_server().await; + let tls = test_tls(&server); + + // No sandbox has the ID: nothing is sent. + run::sandbox_delete_by_id( + &server.endpoint, + "sandbox-gone", + "default", + &tls, + "openshell", + ) + .await + .expect("a missing ID is already deleted"); + assert!(deleted_names(&server).await.is_empty()); + + // The sandbox is replaced between lookup and delete. + *server.openshell.state.listed_sandboxes.lock().await = + vec![listed_sandbox("sandbox-target", "target")]; + server + .openshell + .state + .delete_identity_mismatch + .store(true, Ordering::SeqCst); + run::sandbox_delete_by_id( + &server.endpoint, + "sandbox-target", + "default", + &tls, + "openshell", + ) + .await + .expect("a replaced sandbox's ID is already deleted"); + assert_eq!( + *server.openshell.state.deleted_expected_ids.lock().await, + vec![Some("sandbox-target".to_string())] + ); +} + +#[tokio::test] +async fn sandbox_delete_with_stale_expected_id_fails() { + let server = run_server().await; + let tls = test_tls(&server); + server + .openshell + .state + .delete_identity_mismatch + .store(true, Ordering::SeqCst); + + let err = run::sandbox_delete( + &server.endpoint, + &["replaced".to_string()], + false, + Some("sandbox-original"), + "default", + &tls, + "openshell", + ) + .await + .expect_err("a stale expected ID must not report success"); + + assert!( + err.to_string() + .contains("failed to delete 1 sandbox: replaced"), + "unexpected error: {err}" + ); +} + #[tokio::test] async fn sandbox_create_tolerates_an_unreachable_profile_catalog() { // The catalog's only consumer is the advisory credential warning, so a @@ -2912,6 +3132,11 @@ async fn sandbox_create_deletes_shell_sessions_with_no_keep() { deleted_names(&server).await, vec![vec!["ephemeral-shell".to_string()]] ); + // Cleanup deletes only the sandbox this command created. + assert_eq!( + *server.openshell.state.deleted_expected_ids.lock().await, + vec![Some("id-ephemeral-shell".to_string())] + ); assert_eq!( load_last_sandbox("openshell", "default"), None, @@ -2921,6 +3146,45 @@ async fn sandbox_create_deletes_shell_sessions_with_no_keep() { .await; } +#[tokio::test] +async fn sandbox_create_no_keep_cleanup_treats_replacement_as_gone() { + let server = run_server().await; + let fake_ssh_dir = helpers::tempdir().unwrap(); + let xdg_dir = helpers::tempdir().unwrap(); + + test_env(&fake_ssh_dir, &xdg_dir) + .run_async(async { + let tls = test_tls(&server); + install_fake_ssh(&fake_ssh_dir); + server + .openshell + .state + .delete_identity_mismatch + .store(true, Ordering::SeqCst); + + run::sandbox_create( + &server.endpoint, + "openshell", + run::SandboxCreateConfig { + name: Some("replaced-shell"), + keep: false, + tty_override: Some(true), + ..test_config() + }, + "default", + &tls, + ) + .await + .expect("a replaced ephemeral sandbox needs no further cleanup"); + + assert_eq!( + *server.openshell.state.deleted_expected_ids.lock().await, + vec![Some("id-replaced-shell".to_string())] + ); + }) + .await; +} + #[tokio::test] async fn sandbox_create_keeps_sandbox_with_hidden_keep_flag() { let server = run_server().await; @@ -3396,8 +3660,13 @@ async fn sandbox_forward_background_tracks_owned_child_when_pid_discovery_fails( .expect("owned background forward should write a PID file"); assert!( - openshell_core::forward::stop_forward("default", "owned-forward", forward_port) - .expect("tracked fake forward should stop"), + openshell_core::forward::stop_forward( + "default", + "owned-forward", + forward_port, + None + ) + .expect("tracked fake forward should stop"), "tracked fake forward should be recognized as alive and stopped", ); assert!( diff --git a/crates/openshell-core/src/forward.rs b/crates/openshell-core/src/forward.rs index d65aa53321..18c6f6efdf 100644 --- a/crates/openshell-core/src/forward.rs +++ b/crates/openshell-core/src/forward.rs @@ -494,14 +494,23 @@ pub fn find_forward_by_port(port: u16) -> Result> { .map(|forward| (forward.workspace, forward.sandbox_name))) } -/// Stop a background port forward. -pub fn stop_forward(workspace: &str, name: &str, port: u16) -> Result { +/// Stop a background port forward, optionally requiring a specific sandbox ID. +pub fn stop_forward( + workspace: &str, + name: &str, + port: u16, + expected_sandbox_id: Option<&str>, +) -> Result { let pid_path = forward_pid_path(workspace, name, port)?; let Some(record) = read_forward_pid(workspace, name, port) else { return Ok(false); }; let pid = record.pid; - let Some(_) = expected_sandbox_id_from_record(&record) else { + let owner_sandbox_id = expected_sandbox_id_from_record(&record); + if expected_sandbox_id.is_some_and(|expected| owner_sandbox_id != Some(expected)) { + return Ok(false); + } + let Some(owner_sandbox_id) = owner_sandbox_id else { // Legacy PID records do not prove process ownership. let _ = std::fs::remove_file(&pid_path); return Ok(false); @@ -513,7 +522,7 @@ pub fn stop_forward(workspace: &str, name: &str, port: u16) -> Result { port, Some(workspace), Some(name), - expected_sandbox_id_from_record(&record), + Some(owner_sandbox_id), ) { let _ = std::fs::remove_file(&pid_path); return Ok(false); @@ -531,8 +540,12 @@ pub fn stop_forward(workspace: &str, name: &str, port: u16) -> Result { Ok(true) } -/// Stop all forwards for a workspace-scoped sandbox name. -pub fn stop_forwards_for_sandbox(workspace: &str, name: &str) -> Result> { +/// Stop forwards for a workspace-scoped sandbox name, optionally only for a specific ID. +pub fn stop_forwards_for_sandbox( + workspace: &str, + name: &str, + expected_sandbox_id: Option<&str>, +) -> Result> { safe_path_component(workspace, "workspace")?; safe_path_component(name, "sandbox")?; let Ok(dir) = forward_pid_dir().map(|path| path.join(workspace)) else { @@ -551,7 +564,7 @@ pub fn stop_forwards_for_sandbox(workspace: &str, name: &str) -> Result if let Some(rest) = file_name.strip_prefix(&prefix) && let Some(port_str) = rest.strip_suffix(".pid") && let Ok(port) = port_str.parse::() - && stop_forward(workspace, name, port)? + && stop_forward(workspace, name, port, expected_sandbox_id)? { stopped.push(port); } @@ -2031,7 +2044,7 @@ mod tests { std::fs::create_dir_all(pid_path.parent().unwrap()).unwrap(); std::fs::write(&pid_path, "12345").unwrap(); - assert!(!stop_forward("default", "sbx-1", 80).unwrap()); + assert!(!stop_forward("default", "sbx-1", 80, None).unwrap()); assert!(!pid_path.exists()); }); } diff --git a/crates/openshell-core/src/rpc_error.rs b/crates/openshell-core/src/rpc_error.rs index 5c4b2ab602..ccfcf65e04 100644 --- a/crates/openshell-core/src/rpc_error.rs +++ b/crates/openshell-core/src/rpc_error.rs @@ -114,6 +114,16 @@ pub fn failed_precondition(reason: &str, message: impl Into) -> Status { ) } +/// Return a concurrency conflict with a stable reason. Read fresh state before +/// deciding whether to try again. +pub fn aborted(reason: &str, message: impl Into) -> Status { + Status::with_error_details( + Code::Aborted, + message, + ErrorDetails::with_error_info(reason, ERROR_DOMAIN, HashMap::new()), + ) +} + /// A conditional write lost a race. Read fresh state before trying a new write. pub fn resource_version_conflict(message: impl Into, version: Option) -> Status { let mut metadata = HashMap::from([("recovery".into(), "REFRESH_STATE".into())]); diff --git a/crates/openshell-sdk/src/client.rs b/crates/openshell-sdk/src/client.rs index 7d11bf3e9c..3ec80e519d 100644 --- a/crates/openshell-sdk/src/client.rs +++ b/crates/openshell-sdk/src/client.rs @@ -435,6 +435,7 @@ impl OpenShellClient { let request = proto::DeleteSandboxRequest { request_id: String::new(), allow_missing: opts.allow_missing, + expected_sandbox_id: None, name: name.to_string(), workspace_scope: Some(proto::workspace_selector("default")), }; @@ -1554,6 +1555,7 @@ impl WorkspaceScopedClient { let request = proto::DeleteSandboxRequest { request_id: String::new(), allow_missing: opts.allow_missing, + expected_sandbox_id: None, name: name.to_string(), workspace_scope: Some(proto::workspace_selector(&self.workspace)), }; diff --git a/crates/openshell-sdk/tests/client_mock.rs b/crates/openshell-sdk/tests/client_mock.rs index 39d2f6b01e..50b41ea561 100644 --- a/crates/openshell-sdk/tests/client_mock.rs +++ b/crates/openshell-sdk/tests/client_mock.rs @@ -2425,7 +2425,7 @@ async fn delete_sandbox_returns_server_ack() { let client = connect(&endpoint).await; let deleted = client - .delete_sandbox("doomed", openshell_sdk::DeleteOptions::default()) + .delete_sandbox("doomed", Default::default()) .await .unwrap(); assert_eq!(deleted.outcome, openshell_sdk::DeletionOutcome::Completed); @@ -3146,7 +3146,7 @@ async fn workspace_scoped_delete_passes_workspace() { let ws = client.workspace("staging"); let deleted = ws - .delete_sandbox("doomed", openshell_sdk::DeleteOptions::default()) + .delete_sandbox("doomed", Default::default()) .await .unwrap(); assert_eq!(deleted.outcome, openshell_sdk::DeletionOutcome::Completed); diff --git a/crates/openshell-server/src/compute/mod.rs b/crates/openshell-server/src/compute/mod.rs index 8b2adb5570..09338573fe 100644 --- a/crates/openshell-server/src/compute/mod.rs +++ b/crates/openshell-server/src/compute/mod.rs @@ -3850,7 +3850,8 @@ impl ComputeRuntime { .as_deref() .is_some_and(|expected| expected != candidate.object_id()) { - return Err(Status::aborted( + return Err(openshell_core::rpc_error::aborted( + "SANDBOX_IDENTITY_MISMATCH", "sandbox identity does not match expected_sandbox_id", )); } @@ -3943,7 +3944,8 @@ impl ComputeRuntime { .as_deref() .is_some_and(|expected| expected != current.object_id()) { - return Err(Status::aborted( + return Err(openshell_core::rpc_error::aborted( + "SANDBOX_IDENTITY_MISMATCH", "sandbox identity changed before delete mutation", )); } diff --git a/crates/openshell-server/src/grpc/mutation_replay.rs b/crates/openshell-server/src/grpc/mutation_replay.rs index bdfa236885..3ca0e62a3c 100644 --- a/crates/openshell-server/src/grpc/mutation_replay.rs +++ b/crates/openshell-server/src/grpc/mutation_replay.rs @@ -111,6 +111,10 @@ pub(super) trait Mutation: Message + Default + Send + Sync + 'static { // Streaming producers, not returned stream handles, confirm completion. const DEFERRED: bool = false; fn request_id(&self) -> &str; + /// Validate caller-owned fields before dispatch or replay. + fn validate_intercepted(&self, _effective: &Self) -> Result<(), Status> { + Ok(()) + } /// Name-addressed targets must keep their identity unless an interceptor /// actually changes the selector, not merely another request field. fn target_selector(&self) -> Option<(&str, &WorkspaceSelector)> { @@ -146,6 +150,9 @@ pub(super) async fn run( .map(|original| M::decode(original.0.as_slice())) .transpose() .map_err(|_| Status::internal("decode original mutation request"))?; + if let Some(original) = original.as_ref() { + original.validate_intercepted(request.get_ref())?; + } let original = original.as_ref().unwrap_or_else(|| request.get_ref()); if original.request_id() != request.get_ref().request_id() { return Err(rpc_error::invalid_argument( diff --git a/crates/openshell-server/src/grpc/mutation_replay/ordinary.rs b/crates/openshell-server/src/grpc/mutation_replay/ordinary.rs index 6765171975..25ebe6f045 100644 --- a/crates/openshell-server/src/grpc/mutation_replay/ordinary.rs +++ b/crates/openshell-server/src/grpc/mutation_replay/ordinary.rs @@ -350,7 +350,8 @@ async fn profile_scope( } macro_rules! mutation { - ($req:ty, $resp:ty, $method:literal, $handler:path, $auth:expr, $capture:expr, $restore:expr $(, replay_method = $replay_method:literal)?) => { + ($req:ty, $resp:ty, $method:literal, $handler:path, $auth:expr, $capture:expr, $restore:expr + $(, replay_method = $replay_method:literal)? $(, validate_intercepted = $validate:expr)?) => { impl Mutation for $req { type Output = $resp; const METHOD: &'static str = $method; @@ -359,6 +360,11 @@ macro_rules! mutation { fn request_id(&self) -> &str { &self.request_id } + $( + fn validate_intercepted(&self, effective: &Self) -> Result<(), Status> { + ($validate)(self, effective) + } + )? async fn authorize( &self, state: &ServerState, @@ -405,7 +411,8 @@ macro_rules! scoped_mutation { } macro_rules! sandbox_scoped_mutation { - ($req:ty, $resp:ty, $method:literal, $handler:path, $role:ident, $capture:expr, $restore:expr $(, replay_method = $replay_method:literal)?) => { + ($req:ty, $resp:ty, $method:literal, $handler:path, $role:ident, $capture:expr, $restore:expr + $(, replay_method = $replay_method:literal)? $(, validate_intercepted = $validate:expr)?) => { mutation!( $req, $resp, @@ -423,6 +430,7 @@ macro_rules! sandbox_scoped_mutation { $capture, $restore $(, replay_method = $replay_method)? + $(, validate_intercepted = $validate)? ); }; } @@ -587,6 +595,17 @@ sandbox_scoped_mutation!( sandbox_id: id, outcome, }) + }, + validate_intercepted = |original: &DeleteSandboxRequest, effective: &DeleteSandboxRequest| { + if original.expected_sandbox_id.is_some() + && original.expected_sandbox_id != effective.expected_sandbox_id + { + return Err(openshell_core::rpc_error::invalid_argument( + "expected_sandbox_id", + "interceptors must preserve the caller-supplied expected_sandbox_id", + )); + } + Ok(()) } ); diff --git a/crates/openshell-server/src/grpc/mutation_replay/ordinary/tests.rs b/crates/openshell-server/src/grpc/mutation_replay/ordinary/tests.rs index 1e0c37cb01..d16530a6aa 100644 --- a/crates/openshell-server/src/grpc/mutation_replay/ordinary/tests.rs +++ b/crates/openshell-server/src/grpc/mutation_replay/ordinary/tests.rs @@ -12,8 +12,9 @@ use openshell_core::proto::{ DeletionOutcome, DraftChunkApproval, GetDraftPolicyRequest, NetworkBinary, NetworkEndpoint, NetworkPolicyRule, PolicyChunk, ProviderCredentialRefresh, ProviderCredentialRefreshMaterial, ProviderCredentialRefreshStrategy, ProviderProfileCategory, ProviderProfileCredential, - ProviderProfileImportItem, SandboxPhase, SandboxPolicy, SandboxSpec, ServiceEndpoint, - SettingValue, SubmitPolicyAnalysisRequest, WorkspaceMember, WorkspaceRole, setting_value, + ProviderProfileImportItem, SandboxPhase, SandboxPolicy, SandboxSpec, SandboxStatus, + ServiceEndpoint, SettingValue, SubmitPolicyAnalysisRequest, WorkspaceMember, WorkspaceRole, + setting_value, }; use tonic::Code; @@ -106,6 +107,7 @@ pub(in crate::grpc::mutation_replay) async fn exercise_protected_backend(url: &s "default".to_string(), )), allow_missing: true, + expected_sandbox_id: None, request_id: id(), }; let mut tasks = Vec::new(); @@ -278,6 +280,7 @@ async fn durable_sandbox_mutations_hide_unauthorized_workspaces() { name: "hidden".into(), workspace_scope: Some(openshell_core::proto::workspace_selector("default")), allow_missing: false, + expected_sandbox_id: None, request_id, }), ) @@ -378,6 +381,152 @@ async fn sandbox_replay_survives_status_churn_but_never_selects_replacement() { ); } +#[tokio::test] +async fn conditional_sandbox_delete_replays_original_receipt_without_touching_replacement() { + let (_directory, state) = protected_state().await; + let name = "reused-conditional-delete"; + let original = Sandbox { + metadata: Some(meta(name)), + status: Some(SandboxStatus { + phase: SandboxPhase::Ready.into(), + ..Default::default() + }), + ..Default::default() + }; + state.store.put_message(&original).await.unwrap(); + let request = DeleteSandboxRequest { + name: name.into(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), + expected_sandbox_id: Some(original.object_id().into()), + request_id: id(), + allow_missing: false, + }; + let deleted = run(&state, authed_request(request.clone())) + .await + .unwrap() + .into_inner(); + assert_eq!(deleted.sandbox_id, original.object_id()); + + // Simulate the driver watcher completing cleanup before name reuse. + state + .store + .delete(Sandbox::object_type(), original.object_id()) + .await + .unwrap(); + let replacement = Sandbox { + metadata: Some(meta(name)), + ..original + }; + state.store.put_message(&replacement).await.unwrap(); + + assert_eq!(replay(&state, request.clone()).await, deleted); + for expected_sandbox_id in [None, Some(replacement.object_id().into())] { + let changed = DeleteSandboxRequest { + expected_sandbox_id, + ..request.clone() + }; + let error = run(&state, authed_request(changed)).await.unwrap_err(); + assert_eq!(error.code(), Code::FailedPrecondition); + assert_eq!(reason(&error), "REQUEST_ID_PAYLOAD_MISMATCH"); + } + + let current = state + .store + .get_message_by_name::("default", name) + .await + .unwrap() + .unwrap(); + assert_eq!(current.object_id(), replacement.object_id()); + assert_eq!(current.status.unwrap().phase(), SandboxPhase::Ready); +} + +#[tokio::test] +async fn intercepted_sandbox_delete_preserves_caller_condition() { + use bytes::{BufMut, BytesMut}; + use http_body_util::{BodyExt, Full}; + use openshell_core::proto::open_shell_server::OpenShellServer; + use tower::ServiceExt; + + let (_directory, state) = protected_state().await; + let service = OpenShellServer::new(crate::grpc::OpenShellService::new(state.clone())); + + for (name, request_id) in [ + ("conditional-unkeyed", String::new()), + ("conditional-keyed", id()), + ] { + let sandbox = Sandbox { + metadata: Some(meta(name)), + status: Some(SandboxStatus { + phase: SandboxPhase::Ready.into(), + ..Default::default() + }), + ..Default::default() + }; + state.store.put_message(&sandbox).await.unwrap(); + let original = DeleteSandboxRequest { + name: name.into(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), + expected_sandbox_id: Some(sandbox.object_id().into()), + request_id, + allow_missing: false, + }; + let dispatch = |expected_sandbox_id| { + let effective = DeleteSandboxRequest { + expected_sandbox_id, + allow_missing: true, + ..original.clone() + }; + let mut frame = BytesMut::with_capacity(5 + effective.encoded_len()); + frame.put_u8(0); + frame.put_u32(u32::try_from(effective.encoded_len()).unwrap()); + effective.encode(&mut frame).unwrap(); + let principal = authed_request(()) + .extensions() + .get::() + .unwrap() + .clone(); + let request = http::Request::builder() + .method(http::Method::POST) + .uri("/openshell.v1.OpenShell/DeleteSandbox") + .header("content-type", "application/grpc") + .extension(principal) + .extension(OriginalMutation(original.encode_to_vec())) + .body(tonic::body::Body::new(Full::new(frame.freeze()))) + .unwrap(); + service.clone().oneshot(request) + }; + + for condition in [None, Some("different-sandbox".into())] { + let response = dispatch(condition).await.unwrap(); + let status = Status::from_header_map(response.headers()).unwrap(); + assert_eq!(status.code(), Code::InvalidArgument); + assert!(status.message().contains("expected_sandbox_id")); + let current = state + .store + .get_message::(sandbox.object_id()) + .await + .unwrap() + .unwrap(); + assert_eq!(current.status.unwrap().phase(), SandboxPhase::Ready); + } + + let response = dispatch(original.expected_sandbox_id.clone()) + .await + .unwrap(); + let body = response.into_body().collect().await.unwrap(); + assert_eq!(body.trailers().unwrap().get("grpc-status").unwrap(), "0"); + let deleted = DeleteSandboxResponse::decode(&body.to_bytes()[5..]).unwrap(); + assert_eq!(deleted.sandbox_id, sandbox.object_id()); + + if !original.request_id.is_empty() { + let response = dispatch(None).await.unwrap(); + let status = Status::from_header_map(response.headers()).unwrap(); + assert_eq!(status.code(), Code::InvalidArgument); + assert!(status.message().contains("expected_sandbox_id")); + } + } +} + #[tokio::test] async fn keyed_fingerprints_fail_closed_on_missing_or_rotated_keys() { let missing = test_server_state().await; @@ -387,6 +536,7 @@ async fn keyed_fingerprints_fail_closed_on_missing_or_rotated_keys() { "default".to_string(), )), allow_missing: true, + expected_sandbox_id: None, request_id: id(), }; assert_eq!( @@ -436,6 +586,7 @@ async fn original_payload_is_identity_and_current_transformation_is_a_replay_gua "default".to_string(), )), allow_missing: true, + expected_sandbox_id: None, request_id: id(), }; let mut effective = original.clone(); diff --git a/crates/openshell-server/src/grpc/sandbox.rs b/crates/openshell-server/src/grpc/sandbox.rs index 8e5762a33b..adeaf5656f 100644 --- a/crates/openshell-server/src/grpc/sandbox.rs +++ b/crates/openshell-server/src/grpc/sandbox.rs @@ -1856,6 +1856,14 @@ async fn handle_delete_sandbox_inner( if name.is_empty() { return Err(Status::invalid_argument("sandbox is required")); } + // An explicitly empty condition must not silently become an + // unconditional delete of whatever sandbox now has this name. + if req.expected_sandbox_id.as_deref() == Some("") { + return Err(openshell_core::rpc_error::invalid_argument( + "expected_sandbox_id", + "must not be empty when present", + )); + } let authz = authorize_workspace( &state.store, &state.admin_role, @@ -1874,10 +1882,13 @@ async fn handle_delete_sandbox_inner( let workspace = super::workspace::resolve_workspace(state.store.as_ref(), &authz.workspace) .await? .name; - // Main's canonical public delete request contains no caller-provided - // identity/version fields. The compute layer still binds the resolved - // object ID and lifecycle guards before committing deletion. - let preconditions = SandboxDeletePreconditions::default(); + // The compute layer checks the expected ID when resolving the name and + // again under the lifecycle lock, so a same-name replacement created + // before or after resolution is never deleted by this request. + let preconditions = SandboxDeletePreconditions { + expected_sandbox_id: req.expected_sandbox_id, + ..SandboxDeletePreconditions::default() + }; let result = state .compute .delete_sandbox_allow_missing_with_preconditions( @@ -6754,6 +6765,12 @@ mod tests { #[tokio::test] async fn delete_handler_ends_telemetry_for_the_resolved_sandbox_id() { + for expected_sandbox_id in [None, Some("sandbox-original")] { + assert_delete_pins_resolved_sandbox(expected_sandbox_id).await; + } + } + + async fn assert_delete_pins_resolved_sandbox(expected_sandbox_id: Option<&'static str>) { let state = test_server_state().await; let mut original = test_sandbox("reused-name", Vec::new()); original.metadata.as_mut().unwrap().id = "sandbox-original".to_string(); @@ -6771,14 +6788,7 @@ mod tests { let delete = tokio::spawn(async move { handle_delete_sandbox_inner( &delete_state, - authed_request(DeleteSandboxRequest { - request_id: String::new(), - allow_missing: false, - name: "reused-name".to_string(), - workspace_scope: Some(openshell_core::proto::workspace_selector( - "default".to_string(), - )), - }), + conditional_delete("reused-name", expected_sandbox_id, false), ) .await }); @@ -6801,6 +6811,7 @@ mod tests { drop(global_guard); let response = delete.await.unwrap().unwrap().into_inner(); + assert_eq!(response.sandbox_id, original.object_id()); assert_eq!( response.outcome(), openshell_core::proto::DeletionOutcome::Completed @@ -6819,6 +6830,130 @@ mod tests { ); } + fn conditional_delete( + name: &str, + expected_sandbox_id: Option<&str>, + allow_missing: bool, + ) -> Request { + authed_request(DeleteSandboxRequest { + request_id: String::new(), + allow_missing, + name: name.to_string(), + expected_sandbox_id: expected_sandbox_id.map(str::to_string), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), + }) + } + + #[tokio::test] + async fn delete_with_stale_expected_id_preserves_same_name_replacement() { + use openshell_core::rpc_error::StatusExt; + + let state = test_server_state().await; + // A client observed `sandbox-original`; another client then deleted it + // and created a replacement with the same name. + let mut replacement = test_sandbox("reused-name", Vec::new()); + replacement.metadata.as_mut().unwrap().id = "sandbox-replacement".to_string(); + state.store.put_message(&replacement).await.unwrap(); + + for allow_missing in [false, true] { + let status = handle_delete_sandbox_inner( + &state, + conditional_delete("reused-name", Some("sandbox-original"), allow_missing), + ) + .await + .unwrap_err(); + assert_eq!(status.code(), tonic::Code::Aborted); + assert_eq!( + status.get_error_details().error_info().unwrap().reason, + "SANDBOX_IDENTITY_MISMATCH" + ); + } + + let current = state + .store + .get_message::(replacement.object_id()) + .await + .unwrap() + .expect("replacement must survive a stale conditional delete"); + assert_eq!(current.status.unwrap().phase(), SandboxPhase::Ready); + assert!(state.telemetry.ended_sandbox_sessions().is_empty()); + } + + #[tokio::test] + async fn delete_with_matching_expected_id_deletes_that_sandbox() { + let state = test_server_state().await; + let mut sandbox = test_sandbox("conditional", Vec::new()); + sandbox.metadata.as_mut().unwrap().id = "sandbox-expected".to_string(); + state.store.put_message(&sandbox).await.unwrap(); + + let response = handle_delete_sandbox_inner( + &state, + conditional_delete("conditional", Some("sandbox-expected"), false), + ) + .await + .unwrap() + .into_inner(); + + assert_eq!(response.sandbox_id, "sandbox-expected"); + assert_eq!( + response.outcome(), + openshell_core::proto::DeletionOutcome::Accepted + ); + let deleting = state + .store + .get_message::("sandbox-expected") + .await + .unwrap() + .expect("accepted deletion keeps the record until the watcher removes it"); + assert_eq!(deleting.status.unwrap().phase(), SandboxPhase::Deleting); + } + + #[tokio::test] + async fn delete_rejects_present_but_empty_expected_id() { + let state = test_server_state().await; + let sandbox = test_sandbox("conditional", Vec::new()); + state.store.put_message(&sandbox).await.unwrap(); + + let status = + handle_delete_sandbox_inner(&state, conditional_delete("conditional", Some(""), true)) + .await + .unwrap_err(); + + assert_eq!(status.code(), tonic::Code::InvalidArgument); + assert!( + state + .store + .get_message::(sandbox.object_id()) + .await + .unwrap() + .is_some() + ); + } + + #[tokio::test] + async fn delete_with_expected_id_follows_missing_target_contract() { + let state = test_server_state().await; + + let status = + handle_delete_sandbox_inner(&state, conditional_delete("gone", Some("old-id"), false)) + .await + .unwrap_err(); + assert_eq!(status.code(), tonic::Code::NotFound); + + let response = + handle_delete_sandbox_inner(&state, conditional_delete("gone", Some("old-id"), true)) + .await + .unwrap() + .into_inner(); + assert_eq!( + response.outcome(), + openshell_core::proto::DeletionOutcome::AlreadyAbsent + ); + assert!(response.sandbox_id.is_empty()); + } + #[tokio::test] async fn internal_delete_rejects_expected_identity_drift_before_mutation() { let state = test_server_state().await; @@ -11003,6 +11138,7 @@ mod tests { non_member_request(DeleteSandboxRequest { request_id: String::new(), allow_missing: false, + expected_sandbox_id: None, name: ("any").to_string(), workspace_scope: Some(openshell_core::proto::workspace_selector( "no-such-ws".to_string(), diff --git a/crates/openshell-server/src/storage_proto.rs b/crates/openshell-server/src/storage_proto.rs index 4c452c7cf3..ae4d331fed 100644 --- a/crates/openshell-server/src/storage_proto.rs +++ b/crates/openshell-server/src/storage_proto.rs @@ -251,8 +251,11 @@ mod tests { // and the public/durable overlap remain unchanged. // The service backend HTTP version is part of both schemas. Legacy // endpoint records omit it and continue to use HTTP/1.1. + // DeleteSandboxRequest field 5 adds a public-only expected_sandbox_id + // precondition. Older requests decode it absent; durable schemas remain + // unchanged. const PUBLIC_RPC_SCHEMA_SHA256: &str = - "edfc80ad192e77e1a9d1e1d6e3342280e4438f8bf7cb49969f580060df9a056a"; + "9b395c4a3314fa26032f1cf3bd6f3e257768131e8a288fa4098c9b6707718c61"; // The storage.v2 refresh root adds retired handles and the first mint's // provider revision. All fields from the prior root retain their wire tags. const DURABLE_SCHEMA_SHA256: &str = diff --git a/crates/openshell-tui/src/app.rs b/crates/openshell-tui/src/app.rs index 8c18c8ccb4..bfdfeb205e 100644 --- a/crates/openshell-tui/src/app.rs +++ b/crates/openshell-tui/src/app.rs @@ -9,7 +9,7 @@ use indexmap::IndexMap; use openshell_bootstrap::GatewayMetadataSource; use openshell_core::auth::EdgeAuthInterceptor; use openshell_core::proto::open_shell_client::OpenShellClient; -use openshell_core::proto::setting_value; +use openshell_core::proto::{DeleteSandboxRequest, setting_value, workspace_selector}; use openshell_core::settings::{self, SettingValueKind}; use openshell_providers::{ DiscoveredProvider, ProviderTypeProfile, RealDiscoveryContext, discover_from_profile, @@ -691,9 +691,9 @@ pub struct App { pub sandbox_count: usize, // Sandbox detail / actions - pub confirm_delete: bool, + pub(super) sandbox_delete_confirmation: Option, pub pending_log_fetch: bool, - pub pending_sandbox_delete: bool, + pub(super) pending_sandbox_delete: Option, pub pending_sandbox_detail: bool, pub pending_shell_connect: bool, @@ -1058,9 +1058,9 @@ impl App { sandbox_policy_versions: Vec::new(), sandbox_selected: 0, sandbox_count: 0, - confirm_delete: false, + sandbox_delete_confirmation: None, pending_log_fetch: false, - pending_sandbox_delete: false, + pending_sandbox_delete: None, pending_sandbox_detail: false, pending_shell_connect: false, sandbox_policy_tab: SandboxPolicyTab::Policy, @@ -1689,7 +1689,6 @@ impl App { KeyCode::Enter if self.sandbox_count > 0 => { self.screen = Screen::Sandbox; self.focus = Focus::SandboxPolicy; - self.confirm_delete = false; self.pending_sandbox_detail = true; } KeyCode::Esc => { @@ -1700,14 +1699,13 @@ impl App { } fn handle_policy_key(&mut self, key: KeyEvent) { - if self.confirm_delete { + if self.sandbox_delete_confirmation.is_some() { match key.code { KeyCode::Char('y') => { - self.confirm_delete = false; - self.pending_sandbox_delete = true; + self.pending_sandbox_delete = self.sandbox_delete_confirmation.take(); } KeyCode::Esc | KeyCode::Char('n') => { - self.confirm_delete = false; + self.sandbox_delete_confirmation = None; } _ => {} } @@ -1746,7 +1744,10 @@ impl App { self.pending_shell_connect = true; } KeyCode::Char('d') => { - self.confirm_delete = true; + self.sandbox_delete_confirmation = self.selected_sandbox_delete_request(); + if self.sandbox_delete_confirmation.is_none() { + self.status_text = "Missing sandbox ID; cannot delete".into(); + } } KeyCode::Char('j') | KeyCode::Down => { self.scroll_policy(1); @@ -3266,6 +3267,23 @@ impl App { // Helpers // ------------------------------------------------------------------ + /// Capture the selected row's identity before asking for confirmation. + fn selected_sandbox_delete_request(&self) -> Option { + let name = self.selected_sandbox_name()?; + let expected_sandbox_id = self + .sandbox_ids + .get(self.sandbox_selected) + .filter(|id| !id.is_empty()) + .cloned()?; + Some(DeleteSandboxRequest { + workspace_scope: Some(workspace_selector(self.selected_sandbox_workspace())), + request_id: String::new(), + allow_missing: true, + expected_sandbox_id: Some(expected_sandbox_id), + name: name.to_owned(), + }) + } + /// Get the name of the currently selected sandbox. pub fn selected_sandbox_name(&self) -> Option<&str> { self.sandbox_names @@ -3580,7 +3598,8 @@ impl App { self.log_autoscroll = true; self.log_detail_index = None; self.log_selection_anchor = None; - self.confirm_delete = false; + self.sandbox_delete_confirmation = None; + self.pending_sandbox_delete = None; self.sandbox_policy = None; self.sandbox_providers_list.clear(); self.policy_lines.clear(); @@ -3661,6 +3680,61 @@ mod tests { ) } + #[tokio::test] + async fn sandbox_delete_cancellation_discards_the_target() { + for cancel in [KeyCode::Esc, KeyCode::Char('n')] { + let mut app = test_app(); + app.screen = Screen::Sandbox; + app.focus = Focus::SandboxPolicy; + app.sandbox_names = vec!["alpha".into()]; + app.sandbox_ids = vec!["sandbox-a".into()]; + + app.handle_key(KeyEvent::new(KeyCode::Char('d'), KeyModifiers::NONE)); + app.handle_key(KeyEvent::new(cancel, KeyModifiers::NONE)); + app.handle_key(KeyEvent::new(KeyCode::Char('y'), KeyModifiers::NONE)); + + assert!(app.pending_sandbox_delete.is_none()); + assert_eq!(app.screen, Screen::Sandbox); + } + } + + #[tokio::test] + async fn sandbox_delete_reset_discards_confirmation_and_queued_request() { + for confirmed in [false, true] { + let mut app = test_app(); + app.screen = Screen::Sandbox; + app.focus = Focus::SandboxPolicy; + app.sandbox_names = vec!["alpha".into()]; + app.sandbox_ids = vec!["sandbox-a".into()]; + + app.handle_key(KeyEvent::new(KeyCode::Char('d'), KeyModifiers::NONE)); + if confirmed { + app.handle_key(KeyEvent::new(KeyCode::Char('y'), KeyModifiers::NONE)); + } + app.reset_sandbox_state(); + app.handle_key(KeyEvent::new(KeyCode::Char('y'), KeyModifiers::NONE)); + + assert!(app.pending_sandbox_delete.is_none()); + } + } + + #[tokio::test] + async fn sandbox_delete_requires_an_id() { + for ids in [vec![], vec![String::new()]] { + let mut app = test_app(); + app.screen = Screen::Sandbox; + app.focus = Focus::SandboxPolicy; + app.sandbox_names = vec!["alpha".into()]; + app.sandbox_ids = ids; + + app.handle_key(KeyEvent::new(KeyCode::Char('d'), KeyModifiers::NONE)); + app.handle_key(KeyEvent::new(KeyCode::Char('y'), KeyModifiers::NONE)); + + assert!(app.pending_sandbox_delete.is_none()); + assert!(app.status_text.contains("Missing sandbox ID")); + } + } + #[tokio::test] async fn create_command_preserves_quoted_and_escaped_arguments() { let cases: &[(&str, &[&str])] = &[ diff --git a/crates/openshell-tui/src/lib.rs b/crates/openshell-tui/src/lib.rs index c6464157a9..6ef09f03fb 100644 --- a/crates/openshell-tui/src/lib.rs +++ b/crates/openshell-tui/src/lib.rs @@ -24,7 +24,7 @@ use openshell_bootstrap::list_gateways_with_source; use openshell_core::auth::EdgeAuthInterceptor; use openshell_core::metadata::{ObjectId, ObjectLabels, ObjectName, ObjectWorkspace}; use openshell_core::proto::open_shell_client::OpenShellClient; -use openshell_core::proto::{SandboxPhase, SandboxRestartPolicy}; +use openshell_core::proto::{DeleteSandboxRequest, SandboxPhase, SandboxRestartPolicy}; use openshell_core::ssh_handoff::{SshCleanup, SshTarget}; use ratatui::Terminal; use ratatui::backend::CrosstermBackend; @@ -170,9 +170,8 @@ pub async fn run_with_gateway_insecure( app.pending_log_fetch = false; spawn_log_stream(&mut app, events.sender()); } - if app.pending_sandbox_delete { - app.pending_sandbox_delete = false; - handle_sandbox_delete(&mut app, events.sender()).await; + if let Some(request) = app.pending_sandbox_delete.take() { + handle_sandbox_delete(&mut app, request, events.sender()).await; } if app.pending_create_sandbox { app.pending_create_sandbox = false; @@ -831,36 +830,38 @@ fn proto_to_log_line(log: openshell_core::proto::SandboxLogLine) -> LogLine { } } -/// Delete the currently selected sandbox. -async fn handle_sandbox_delete(app: &mut App, tx: mpsc::UnboundedSender) { - let sandbox_name = match app.selected_sandbox_name() { - Some(n) => n.to_string(), - None => return, +fn sandbox_delete_workspace(request: &DeleteSandboxRequest) -> &str { + use openshell_core::proto::{WorkspaceSelector, workspace_selector::Selection}; + + let Some(WorkspaceSelector { + selection: Some(Selection::Workspace(workspace)), + }) = &request.workspace_scope + else { + unreachable!("sandbox delete confirmation always names a workspace"); }; + workspace +} - // Stop any active port forwards before deleting (mirrors CLI behavior). - let workspace = app.selected_sandbox_workspace(); - if let Ok(stopped) = - openshell_core::forward::stop_forwards_for_sandbox(&workspace, &sandbox_name) - && !stopped.is_empty() - { - let ports: Vec = stopped.iter().map(ToString::to_string).collect(); - app.status_text = format!( - "stopped port forwards [{}] for sandbox {sandbox_name}", - ports.join(", ") - ); - } +/// Delete the sandbox captured when the confirmation opened. +async fn handle_sandbox_delete( + app: &mut App, + request: DeleteSandboxRequest, + tx: mpsc::UnboundedSender, +) { + let sandbox_name = &request.name; - let req = openshell_core::proto::DeleteSandboxRequest { - workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), - request_id: String::new(), - allow_missing: true, - name: sandbox_name, - }; - match app.client.delete_sandbox(req).await { + match app.client.delete_sandbox(request.clone()).await { Ok(response) => { use openshell_core::proto::DeletionOutcome; - app.status_text = match response.into_inner().outcome() { + let outcome = response.into_inner().outcome(); + if outcome != DeletionOutcome::Unspecified { + let _ = openshell_core::forward::stop_forwards_for_sandbox( + sandbox_delete_workspace(&request), + sandbox_name, + request.expected_sandbox_id.as_deref(), + ); + } + app.status_text = match outcome { DeletionOutcome::Completed => "sandbox deleted".into(), DeletionOutcome::Accepted => "sandbox deletion accepted; cleanup is pending".into(), DeletionOutcome::AlreadyAbsent => "sandbox already deleted".into(), @@ -874,6 +875,15 @@ async fn handle_sandbox_delete(app: &mut App, tx: mpsc::UnboundedSender) app.cancel_list_refresh(); spawn_list_refresh(app, tx); } + Err(e) if is_sandbox_identity_mismatch(&e) => { + app.status_text = format!( + "delete refused: {sandbox_name} now refers to a different sandbox; list refreshed" + ); + app.screen = Screen::Dashboard; + app.focus = Focus::Sandboxes; + app.cancel_list_refresh(); + spawn_list_refresh(app, tx); + } Err(e) => { app.status_text = format!("delete failed: {}", e.message()); app.screen = Screen::Dashboard; @@ -882,6 +892,15 @@ async fn handle_sandbox_delete(app: &mut App, tx: mpsc::UnboundedSender) } } +fn is_sandbox_identity_mismatch(status: &tonic::Status) -> bool { + use openshell_core::rpc_error::StatusExt; + status.code() == Code::Aborted + && status + .get_error_details() + .error_info() + .is_some_and(|info| info.reason == "SANDBOX_IDENTITY_MISMATCH") +} + // --------------------------------------------------------------------------- // Sandbox detail + policy rendering // --------------------------------------------------------------------------- diff --git a/crates/openshell-tui/src/ui/mod.rs b/crates/openshell-tui/src/ui/mod.rs index 749fddc1a5..3de6c4b610 100644 --- a/crates/openshell-tui/src/ui/mod.rs +++ b/crates/openshell-tui/src/ui/mod.rs @@ -122,6 +122,55 @@ fn draw_sandbox_screen(frame: &mut Frame<'_>, app: &mut App, area: Rect) { &app.theme, ); } + if let Some(request) = &app.sandbox_delete_confirmation { + draw_sandbox_delete_confirmation(frame, request, frame.area(), &app.theme); + } +} + +fn draw_sandbox_delete_confirmation( + frame: &mut Frame<'_>, + request: &openshell_core::proto::DeleteSandboxRequest, + area: Rect, + theme: &Theme, +) { + let width = area.width.min(76); + let content_width = usize::from(width.saturating_sub(4).max(1)); + let workspace = crate::sandbox_delete_workspace(request); + let sandbox_id = request + .expected_sandbox_id + .as_deref() + .expect("sandbox delete confirmation always has an ID"); + let mut lines: Vec> = [ + ( + format!("Delete sandbox '{}'?", request.name), + theme.status_err, + ), + (format!("Workspace: {workspace}"), theme.text), + (format!("Sandbox ID: {sandbox_id}"), theme.text), + ] + .into_iter() + .flat_map(|(text, style)| { + sandbox_draft::wrap_value(&text, content_width) + .into_iter() + .map(move |row| Line::from(Span::styled(row, style))) + }) + .collect(); + lines.push(Line::default()); + lines.push(Line::from(vec![ + Span::styled("[y]", theme.key_hint), + Span::styled(" Confirm ", theme.text), + Span::styled("[Esc]", theme.key_hint), + Span::styled(" Cancel", theme.text), + ])); + + let height = u16::try_from(lines.len() + 2).unwrap_or(u16::MAX); + let popup = centered_rect(width, height.min(area.height), area); + frame.render_widget(Clear, popup); + let block = Block::bordered() + .title(" Confirm sandbox deletion ") + .border_style(theme.border_focused) + .padding(Padding::horizontal(1)); + frame.render_widget(Paragraph::new(lines).block(block), popup); } // --------------------------------------------------------------------------- @@ -675,6 +724,7 @@ pub fn centered_popup(percent_x: u16, height: u16, area: Rect) -> Rect { #[cfg(test)] mod tests { use super::*; + use crossterm::event::{KeyCode, KeyEvent, KeyModifiers}; use openshell_core::auth::EdgeAuthInterceptor; use openshell_core::proto::open_shell_client::OpenShellClient; use ratatui::Terminal; @@ -788,15 +838,25 @@ mod tests { } #[tokio::test] - async fn sandbox_delete_confirmation_is_visible_in_standard_terminal() { + async fn sandbox_delete_confirmation_retains_identity_across_refresh() { let mut app = test_app(); app.screen = Screen::Sandbox; app.focus = Focus::SandboxPolicy; - app.sandbox_names = vec!["test-sandbox".to_string()]; + app.all_workspaces = true; + app.sandbox_names = vec!["neighbor".into(), "test-sandbox".into()]; + app.sandbox_workspaces = vec!["default".into(), "staging".into()]; + app.sandbox_ids = vec!["neighbor-id".into(), "original-id".into()]; + app.sandbox_count = 2; + app.sandbox_selected = 1; + app.handle_key(KeyEvent::new(KeyCode::Char('d'), KeyModifiers::NONE)); + + // A background refresh drops the original row and clamps the cursor. + app.sandbox_names.truncate(1); + app.sandbox_workspaces.truncate(1); + app.sandbox_ids.truncate(1); app.sandbox_count = 1; - app.confirm_delete = true; - let mut terminal = Terminal::new(TestBackend::new(100, 24)).unwrap(); - + app.sandbox_selected = 0; + let mut terminal = Terminal::new(TestBackend::new(80, 24)).unwrap(); terminal.draw(|frame| draw(frame, &mut app)).unwrap(); let text: String = terminal @@ -810,5 +870,19 @@ mod tests { text.contains("Delete sandbox 'test-sandbox'?"), "sandbox screen was: {text:?}" ); + assert!(text.contains("Workspace: staging")); + assert!(text.contains("Sandbox ID: original-id")); + + // A later refresh shows a different sandbox with the original name. + app.sandbox_names[0] = "test-sandbox".into(); + app.sandbox_workspaces[0] = "staging".into(); + app.sandbox_ids[0] = "replacement-id".into(); + app.handle_key(KeyEvent::new(KeyCode::Char('y'), KeyModifiers::NONE)); + + let request = app.pending_sandbox_delete.take().unwrap(); + assert_eq!(request.name, "test-sandbox"); + assert_eq!(crate::sandbox_delete_workspace(&request), "staging"); + assert_eq!(request.expected_sandbox_id.as_deref(), Some("original-id")); + assert!(request.allow_missing); } } diff --git a/crates/openshell-tui/src/ui/sandbox_detail.rs b/crates/openshell-tui/src/ui/sandbox_detail.rs index 726e6d8124..03adbcd6f1 100644 --- a/crates/openshell-tui/src/ui/sandbox_detail.rs +++ b/crates/openshell-tui/src/ui/sandbox_detail.rs @@ -42,11 +42,7 @@ fn note_lines(app: &App, width: u16) -> Vec { /// Return the rows needed to render every metadata line without clipping. pub(super) fn required_height(app: &App, width: u16) -> u16 { let policy_rows = u16::from(app.sandbox_policy_is_global); - let action_rows = if app.confirm_delete { - 2 // spacer plus confirmation - } else { - u16::from(pending_draft_count(app) > 0) - }; + let action_rows = u16::from(pending_draft_count(app) > 0); BASE_CONTENT_ROWS + policy_rows @@ -193,9 +189,7 @@ pub fn draw(frame: &mut Frame<'_>, app: &App, area: Rect) { ])); } - // Show pending network rules prompt — but not when delete confirmation is - // active, since it would push the confirmation off the bottom of the pane. - if pending_count > 0 && !app.confirm_delete { + if pending_count > 0 { lines.push(Line::from(vec![ Span::styled(" ", t.text), Span::styled( @@ -211,22 +205,6 @@ pub fn draw(frame: &mut Frame<'_>, app: &App, area: Rect) { ])); } - // Delete confirmation in title area (same pattern as provider delete). - // Takes priority over the pending-policy prompt so it isn't pushed off-screen. - if app.confirm_delete { - lines.push(Line::from("")); - lines.push(Line::from(vec![ - Span::styled(" ", t.text), - Span::styled("Delete sandbox '", t.status_err), - Span::styled(name, t.status_err), - Span::styled("'? ", t.status_err), - Span::styled("[y]", t.key_hint), - Span::styled(" Confirm ", t.text), - Span::styled("[Esc]", t.key_hint), - Span::styled(" Cancel", t.text), - ])); - } - let mut title_spans: Vec> = vec![Span::styled(format!(" Sandbox: {name} "), t.heading)]; if pending_count > 0 { diff --git a/docs/how-it-works/sandboxes/overview.mdx b/docs/how-it-works/sandboxes/overview.mdx index 123678e9fe..640bfc3476 100644 --- a/docs/how-it-works/sandboxes/overview.mdx +++ b/docs/how-it-works/sandboxes/overview.mdx @@ -1221,6 +1221,27 @@ When a multi-sandbox delete fails for one entry, the CLI reports that sandbox's failure and continues with the remaining names. The command exits with an error after it attempts every requested deletion if any entry failed. +To delete a specific sandbox rather than whichever sandbox currently has a +name, pass the ID that `openshell sandbox get` prints: + +```shell +openshell sandbox delete --id +``` + +On gateways that support conditional deletion, a same-name replacement created +after you looked up the ID is not deleted. Gateways that predate +`expected_sandbox_id` ignore the condition and may delete the replacement, so +upgrade the gateway before relying on this behavior. If no sandbox has that ID, +the command reports it as already deleted. + +To also require that a name still refers to that ID, use `--expected-id` with +exactly one sandbox name. If the name now belongs to a different sandbox, the +command fails and deletes nothing: + +```shell +openshell sandbox delete my-sandbox --expected-id +``` + ## Sandbox Lifecycle Every sandbox moves through a defined set of phases: diff --git a/docs/sdk/api-errors.mdx b/docs/sdk/api-errors.mdx index 661c52d66b..19976763ea 100644 --- a/docs/sdk/api-errors.mdx +++ b/docs/sdk/api-errors.mdx @@ -30,6 +30,7 @@ Recognized gateway reasons include the following. |---|---|---| | `INVALID_ARGUMENT` | `INVALID_ARGUMENT` | Correct the fields listed in `BadRequest`. | | `RESOURCE_VERSION_CONFLICT` | `ABORTED` | Read the resource again and construct a new conditional write. `metadata.recovery` is `REFRESH_STATE`; `current_resource_version` is included when known. | +| `SANDBOX_IDENTITY_MISMATCH` | `ABORTED` | The sandbox name resolves to a different sandbox than `expected_sandbox_id`. The expected sandbox is no longer at that name. Do not retry the deletion without the condition. | | `PROFILE_SOURCE_UNAVAILABLE` | `UNAVAILABLE` | Retry a profile snapshot read after at least the supplied delay. | | `DATABASE_UNAVAILABLE` | `UNAVAILABLE` | The gateway could not get a database connection within 5 seconds. Retry after at least the supplied delay. | | `MUTATION_LOCK_TIMEOUT` | `UNAVAILABLE` | The request waited more than 10 seconds for a concurrent mutation to release a sandbox, workspace, or gateway-wide lock. Retry after at least the supplied delay. The Rust SDK's retrying sandbox-create methods and the CLI retry this reason automatically; see [Sandbox create retry](#sandbox-create-retry). A request that carried a `request_id` leaves its admission unresolved, like any other error, so a retry with that ID returns `REQUEST_OUTCOME_UNCERTAIN`. Observe resource state and reconcile effects before you start a new request with a new ID. | @@ -374,6 +375,23 @@ the third argument; use `None` to retain name-only behavior. a newly created resource with that name. Do not blindly repeat a timed-out deletion when names might be reused. +### Conditional sandbox deletion + +Set `expected_sandbox_id` on `DeleteSandbox` to the sandbox ID you previously +observed, such as `metadata.id` from `GetSandbox` or `CreateSandbox`. The gateway +deletes the sandbox only if the name still resolves to that ID. If another +client deleted it and created a same-name replacement, the request fails with +`SANDBOX_IDENTITY_MISMATCH` and the replacement is not deleted. A missing name +follows `allow_missing` as usual. An explicitly empty `expected_sandbox_id` +returns `INVALID_ARGUMENT`. Gateways that predate this field ignore it and +delete by name. + +| Client | Conditional deletion | +|---|---| +| CLI | `openshell sandbox delete --id ID`, or `openshell sandbox delete NAME --expected-id ID`. Cleanup after `sandbox create --no-keep` supplies the created sandbox's ID automatically. | +| TUI | Deleting a sandbox supplies the selected row's ID automatically. | +| Rust | Use the [raw gRPC client](/sdk/rust) from `client.raw_grpc_fresh().await?`. Call `grpc.delete_sandbox(request).await?` with an `openshell_sdk::raw::proto::DeleteSandboxRequest` that sets `name`, `workspace_scope`, and `expected_sandbox_id: Some(id)`. The curated `delete_sandbox` method remains name-only. | + ### SDK migration for deletion Upgrade gateways and clients together. This pre-1.0 change removes the boolean diff --git a/proto/openshell.proto b/proto/openshell.proto index 4212445623..7d3428c48b 100644 --- a/proto/openshell.proto +++ b/proto/openshell.proto @@ -1677,6 +1677,13 @@ message DeleteSandboxRequest { openshell.datamodel.v1.WorkspaceSelector workspace_scope = 2; // Canonical sandbox name. string name = 1; + // Optional immutable sandbox ID (`metadata.id`) the caller expects `name` to + // resolve to. When present, the gateway deletes only that sandbox and + // returns ABORTED with reason SANDBOX_IDENTITY_MISMATCH if the name + // resolves to a different sandbox, such as a same-name replacement. + // An explicitly empty value is rejected. When absent, deletion targets + // whichever sandbox currently has the name. + optional string expected_sandbox_id = 5; // Succeed with ALREADY_ABSENT if the target is missing. Does not wait for // asynchronous cleanup and does not suppress authorization or parent errors. bool allow_missing = 3; diff --git a/skills/openshell-cli/SKILL.md b/skills/openshell-cli/SKILL.md index c89ba151ea..6bf306ff80 100644 --- a/skills/openshell-cli/SKILL.md +++ b/skills/openshell-cli/SKILL.md @@ -559,12 +559,16 @@ openshell logs my-sandbox --since 5m openshell sandbox delete my-sandbox openshell sandbox delete sandbox-1 sandbox-2 sandbox-3 # Multiple at once openshell sandbox delete --all +openshell sandbox delete --id # Requires conditional-delete gateway support ``` `deletion accepted` means cleanup is still pending. Inspect the sandbox until it disappears before assuming completion. An already-absent sandbox succeeds; missing workspaces and authorization failures remain errors. Do not blindly -retry by name if another process might have recreated that name. +retry by name if another process might have recreated that name. On a gateway +that supports conditional deletion, use `openshell sandbox delete --id ` +with the `Id` from `openshell sandbox get` to leave a same-name replacement +untouched. Older gateways ignore the condition and delete by name. ### Stop and start sandboxes diff --git a/tests/suites/conformance/src/lifecycle.rs b/tests/suites/conformance/src/lifecycle.rs index 1e66e1e3fb..e7c95f5fc2 100644 --- a/tests/suites/conformance/src/lifecycle.rs +++ b/tests/suites/conformance/src/lifecycle.rs @@ -9,8 +9,9 @@ use std::time::Duration; -use testkit::sdk::{SandboxPhase, SandboxRestartPolicy}; -use testkit::{Context, Poll, ResultExt as _, Sandbox, poll_until, with_deadline}; +use testkit::sdk::raw::proto::{DeleteSandboxRequest, workspace_selector}; +use testkit::sdk::{SandboxPhase, SandboxRestartPolicy, SdkError}; +use testkit::{Context, GrpcCode, Poll, ResultExt as _, Sandbox, poll_until, with_deadline}; /// A long-running sandbox becomes ready, runs a command with exec, and is gone /// from get and list after delete. @@ -32,6 +33,74 @@ async fn long_running_exec_delete(cx: &mut Context) -> testkit::Result { sandbox.expect_absent().await } +/// A conditional delete must not remove a sandbox that replaced the observed one. +#[testkit::test] +async fn conditional_delete_preserves_same_name_replacement(cx: &mut Context) -> testkit::Result { + let original = cx + .sandbox("cd") + .command(["sleep", "infinity"]) + .create_ready() + .await?; + original.delete().await?; + let replacement = cx + .sandbox("cd") + .command(["sleep", "infinity"]) + .create_ready() + .await?; + testkit::ensure!(replacement.id() != original.id(), "sandbox IDs were reused"); + + let mut grpc = cx + .cli_handle() + .gateway() + .connect() + .await? + .raw_grpc_fresh() + .await?; + let workspace = cx.client().workspace_name(); + + for allow_missing in [false, true] { + let status = grpc + .delete_sandbox(DeleteSandboxRequest { + name: original.name().to_owned(), + request_id: String::new(), + workspace_scope: Some(workspace_selector(workspace)), + allow_missing, + expected_sandbox_id: Some(original.id().to_owned()), + }) + .await + .expect_err("conditional delete of the original ID must fail"); + let code = status.code(); + let error = SdkError::from_status(status); + testkit::ensure!( + code == GrpcCode::Aborted + && error.error_details().is_some_and(|details| details + .error_info() + .is_some_and(|info| info.reason == "SANDBOX_IDENTITY_MISMATCH")), + "unexpected conditional deletion error: {error}" + ); + } + testkit::ensure!( + replacement.get().await?.id == replacement.id(), + "conditional deletion removed the replacement" + ); + + let result = grpc + .delete_sandbox(DeleteSandboxRequest { + name: replacement.name().to_owned(), + request_id: String::new(), + workspace_scope: Some(workspace_selector(workspace)), + allow_missing: false, + expected_sandbox_id: Some(replacement.id().to_owned()), + }) + .await? + .into_inner(); + testkit::ensure!( + result.sandbox_id == replacement.id(), + "conditional deletion did not return the replacement ID" + ); + replacement.wait_absent(Duration::from_mins(2)).await +} + /// Longer than the supervisor's 30s startup recovery deadline. const PAST_RECOVERY_DEADLINE: Duration = Duration::from_secs(31); /// The exec's own timeout is the runner's two-minute kill, so fail sooner,