diff --git a/.github/workflows/e2e-docker-test.yml b/.github/workflows/e2e-docker-test.yml index 4b747ff3c4..45f8097cdb 100644 --- a/.github/workflows/e2e-docker-test.yml +++ b/.github/workflows/e2e-docker-test.yml @@ -33,7 +33,7 @@ on: required: false type: string default: >- - [{"suite":"oidc-pkce-docker","cmd":"mise run --no-deps --skip-deps e2e:oidc-pkce:docker","apt_packages":"openssh-client","mcp":false},{"suite":"rust-docker","cmd":"mise run --no-deps --skip-deps e2e:rust","apt_packages":"openssh-client","mcp":false},{"suite":"oci-image","cmd":"mise run --no-deps --skip-deps e2e:oci-image","apt_packages":"openssh-client","mcp":false},{"suite":"additional-ca","cmd":"OPENSHELL_E2E_DOCKER_TEST=additional_ca mise run --no-deps --skip-deps e2e:docker","apt_packages":"openssh-client","mcp":false},{"suite":"middleware-http-hooks","cmd":"mise run --no-deps --skip-deps e2e:middleware-http-hooks","apt_packages":"","mcp":false},{"suite":"mcp","cmd":"mise run --no-deps --skip-deps e2e:mcp","apt_packages":"","mcp":true}] + [{"suite":"oidc-pkce-docker","cmd":"mise run --no-deps --skip-deps e2e:oidc-pkce:docker","apt_packages":"openssh-client","mcp":false},{"suite":"rust-docker","cmd":"mise run --no-deps --skip-deps e2e:rust","apt_packages":"openssh-client","mcp":false},{"suite":"rust-docker-child-sandboxes","cmd":"mise run --no-deps --skip-deps e2e:rust:child-sandboxes","apt_packages":"openssh-client","mcp":false},{"suite":"oci-image","cmd":"mise run --no-deps --skip-deps e2e:oci-image","apt_packages":"openssh-client","mcp":false},{"suite":"additional-ca","cmd":"OPENSHELL_E2E_DOCKER_TEST=additional_ca mise run --no-deps --skip-deps e2e:docker","apt_packages":"openssh-client","mcp":false},{"suite":"middleware-http-hooks","cmd":"mise run --no-deps --skip-deps e2e:middleware-http-hooks","apt_packages":"","mcp":false},{"suite":"mcp","cmd":"mise run --no-deps --skip-deps e2e:mcp","apt_packages":"","mcp":true}] permissions: actions: read diff --git a/Cargo.lock b/Cargo.lock index 988793659d..0f0c491510 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4776,6 +4776,7 @@ name = "openshell-cli" version = "0.0.0" dependencies = [ "anyhow", + "async-trait", "base64 0.22.1", "bytes", "clap", @@ -5660,6 +5661,8 @@ dependencies = [ "async-stream", "async-trait", "futures", + "http 1.4.0", + "http-body-util", "hyper", "hyper-util", "miette", @@ -5706,6 +5709,7 @@ dependencies = [ "hyper-util", "ipnet", "jiff 1.0.2", + "jsonschema", "jsonwebtoken", "k8s-openapi", "kube", @@ -5939,6 +5943,9 @@ dependencies = [ "hex", "hickory-proto", "http 1.4.0", + "http-body-util", + "hyper", + "hyper-util", "ipnet", "libc", "miette", @@ -5983,6 +5990,7 @@ dependencies = [ "tokio-stream", "tokio-tungstenite 0.26.2", "tonic", + "tower", "tower-mcp-types", "tracing", "tracing-opentelemetry", diff --git a/crates/openshell-cli/Cargo.toml b/crates/openshell-cli/Cargo.toml index 882b7c35d7..79f188ac8a 100644 --- a/crates/openshell-cli/Cargo.toml +++ b/crates/openshell-cli/Cargo.toml @@ -32,6 +32,7 @@ prost = { workspace = true } prost-types = { workspace = true } # Async runtime +async-trait = "0.1" tokio = { workspace = true } # gRPC client diff --git a/crates/openshell-cli/src/completers.rs b/crates/openshell-cli/src/completers.rs index 36c9aa08f2..821a6273ca 100644 --- a/crates/openshell-cli/src/completers.rs +++ b/crates/openshell-cli/src/completers.rs @@ -35,6 +35,7 @@ pub fn complete_sandbox_names(_prefix: &OsStr) -> Vec { page_size: 200, page_token: String::new(), label_selector: String::new(), + parent: String::new(), workspace_scope: Some(openshell_core::proto::workspace_selector( workspace_from_args(), )), diff --git a/crates/openshell-cli/src/lib.rs b/crates/openshell-cli/src/lib.rs index d1a4b3be89..453a0a7b54 100644 --- a/crates/openshell-cli/src/lib.rs +++ b/crates/openshell-cli/src/lib.rs @@ -17,6 +17,7 @@ pub mod callback; pub mod color; pub(crate) mod commands; pub mod completers; +pub mod mcp_bridge; pub mod oidc_auth; pub mod output; pub(crate) mod policy_update; diff --git a/crates/openshell-cli/src/main.rs b/crates/openshell-cli/src/main.rs index 5cca485033..56f44b15e9 100644 --- a/crates/openshell-cli/src/main.rs +++ b/crates/openshell-cli/src/main.rs @@ -256,6 +256,74 @@ fn apply_auth_with_status(tls: &mut TlsOptions, gateway_name: &str) -> Option, + gateway_endpoint: &Option, + allow_endpoint_override: bool, + tls: TlsOptions, +) -> std::result::Result { + let ctx = resolve_gateway(gateway, gateway_endpoint, allow_endpoint_override) + .map_err(|error| error.to_string())?; + let mut tls = tls.with_gateway_name(&ctx.name); + if let Some(error) = apply_auth_with_status(&mut tls, &ctx.name) { + return Err(error); + } + let refresher = get_gateway_metadata(&ctx.name) + .filter(|meta| meta.auth_mode.as_deref() == Some("oidc")) + .map(|meta| { + let refresher: std::sync::Arc = + std::sync::Arc::new(openshell_cli::mcp_bridge::StoredOidcRefresher { + gateway_name: ctx.name.clone(), + audience: meta.oidc_audience, + scopes: meta.oidc_scopes, + insecure: tls.gateway_insecure, + }); + refresher + }); + openshell_cli::tls::sdk_client(&ctx.endpoint, &tls, refresher) + .await + .map_err(|error| format!("cannot reach the gateway: {error}")) +} + +/// Run the MCP bridge. Missing or unusable credentials do not stop it: each +/// call then answers with what to run, so the MCP client shows the reason, +/// and nothing ever starts an interactive login. The client is built on the +/// first call that can build it, so a login made after the bridge started +/// takes effect without restarting it. +async fn mcp_serve( + gateway: &Option, + gateway_endpoint: &Option, + allow_endpoint_override: bool, + tls: TlsOptions, + workspace: String, +) -> Result<()> { + let (gateway, gateway_endpoint) = (gateway.clone(), gateway_endpoint.clone()); + let client = std::sync::Arc::new(openshell_cli::mcp_bridge::LazyClient::new(move || { + let (gateway, gateway_endpoint, tls) = + (gateway.clone(), gateway_endpoint.clone(), tls.clone()); + async move { mcp_client(&gateway, &gateway_endpoint, allow_endpoint_override, tls).await } + })); + // Try once at start so a missing login shows on stderr straight away. + if let Err(error) = client.get().await { + eprintln!("openshell mcp serve: {error}"); + } + let workspace = std::sync::Arc::new(workspace); + let send = move |body: Vec| { + let client = std::sync::Arc::clone(&client); + let workspace = std::sync::Arc::clone(&workspace); + async move { openshell_cli::mcp_bridge::send_with(client.get().await, &body, &workspace).await } + }; + openshell_cli::mcp_bridge::serve( + tokio::io::BufReader::new(tokio::io::stdin()), + tokio::io::stdout(), + send, + ) + .await + .map_err(|error| miette::miette!("MCP stdio failed: {error}")) +} + /// Resolve a sandbox name, falling back to the last-used sandbox for the /// gateway and workspace. /// @@ -660,6 +728,13 @@ enum Commands { output: OutputFormat, }, + /// Serve the gateway's sandbox tools to a local MCP client (experimental). + #[command(help_template = SUBCOMMAND_HELP_TEMPLATE)] + Mcp { + #[command(subcommand)] + command: Option, + }, + /// Show the identity validated by the gateway. #[command(help_template = LEAF_HELP_TEMPLATE, next_help_heading = "FLAGS")] Whoami { @@ -1494,6 +1569,18 @@ enum GatewayCommands { // Doctor (diagnostic) commands // ----------------------------------------------------------------------- +#[derive(Subcommand, Debug)] +enum McpCommands { + /// Run a local MCP server over stdio for an MCP client. + /// + /// Add it to the client's configuration as the command + /// `openshell mcp serve`. Each tool call goes to the active gateway with + /// this CLI's login, acting in `--workspace`. The gateway serves the tools + /// only when `experimental_enable_child_sandboxes` is on. + #[command(help_template = LEAF_HELP_TEMPLATE, next_help_heading = "FLAGS")] + Serve, +} + #[derive(Subcommand, Debug)] enum DoctorCommands { /// Validate system prerequisites for running a gateway. @@ -1525,6 +1612,12 @@ enum SandboxCommands { #[arg(long, conflicts_with_all = ["from", "gpu", "cpu", "memory", "driver_config_json", "envs", "env_from"])] template: Option, + /// Experimental: create the sandbox as a child of this root sandbox. + /// The child uses the parent's policy, and `--provider` picks from + /// the parent's providers (all of them when omitted). + #[arg(long, add = ArgValueCompleter::new(completers::complete_sandbox_names))] + parent: Option, + /// Sandbox source: a rootfs tar archive (`.tar`, `.tar.gz`, or `.tgz`) /// or a container image reference (e.g., `myregistry.com/img:tag`). /// @@ -1767,6 +1860,10 @@ enum SandboxCommands { #[arg(long)] selector: Option, + /// Experimental: list only the child sandboxes of this root sandbox. + #[arg(long, conflicts_with = "all_workspaces", add = ArgValueCompleter::new(completers::complete_sandbox_names))] + parent: Option, + /// Output format. #[arg(short = 'o', long = "output", value_enum, default_value_t = OutputFormat::Table, conflicts_with_all = ["ids", "names"])] output: OutputFormat, @@ -2885,9 +2982,17 @@ async fn run_async() -> Result<()> { // The fmt formatter defaults to ANSI on with no terminal detection, and it // writes to stdout, so without this `openshell -v ... | ...` pipes escapes - // to the caller. + // to the caller. The MCP bridge's stdout carries MCP messages only, so it + // logs to stderr. + let mcp = matches!(cli.command, Some(Commands::Mcp { .. })); + let writer = if mcp { + tracing_subscriber::fmt::writer::BoxMakeWriter::new(std::io::stderr) + } else { + tracing_subscriber::fmt::writer::BoxMakeWriter::new(std::io::stdout) + }; tracing_subscriber::fmt() - .with_ansi(color::stdout_enabled()) + .with_ansi(!mcp && color::stdout_enabled()) + .with_writer(writer) .with_env_filter( tracing_subscriber::EnvFilter::try_from_default_env() .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new(log_level)), @@ -3040,6 +3145,29 @@ async fn run_async() -> Result<()> { } } + // ----------------------------------------------------------- + // MCP bridge + // ----------------------------------------------------------- + Some(Commands::Mcp { + command: Some(McpCommands::Serve), + }) => { + mcp_serve( + &cli.gateway, + &cli.gateway_endpoint, + explicit_gateway == explicit_endpoint, + tls, + cli.workspace, + ) + .await?; + } + Some(Commands::Mcp { command: None }) => { + Cli::command() + .find_subcommand_mut("mcp") + .expect("mcp subcommand exists") + .print_help() + .expect("Failed to print help"); + } + // ----------------------------------------------------------- // Top-level current identity // ----------------------------------------------------------- @@ -3625,6 +3753,7 @@ async fn run_async() -> Result<()> { SandboxCommands::Create { name, template, + parent, from, upload, no_git_ignore, @@ -3727,6 +3856,7 @@ async fn run_async() -> Result<()> { run::SandboxCreateConfig { name: name.as_deref(), template: template.as_deref(), + parent: parent.as_deref(), from: from.as_deref(), uploads: &upload_specs, keep, @@ -3837,6 +3967,7 @@ async fn run_async() -> Result<()> { ids, names, selector, + parent, output, all_workspaces, } => { @@ -3847,6 +3978,7 @@ async fn run_async() -> Result<()> { ids, names, selector.as_deref(), + parent.as_deref(), output.as_str(), &cli.workspace, all_workspaces, @@ -7105,6 +7237,57 @@ mod tests { } } + #[test] + fn sandbox_list_parent_flag_parses_and_needs_one_workspace() { + let cli = Cli::try_parse_from(["openshell", "sandbox", "list", "--parent", "lead"]) + .expect("sandbox list parent flag should parse"); + assert!(matches!( + cli.command, + Some(Commands::Sandbox { + command: Some(SandboxCommands::List { parent: Some(ref parent), .. }), + }) if parent == "lead" + )); + + let err = Cli::try_parse_from([ + "openshell", + "sandbox", + "list", + "--parent", + "lead", + "--all-workspaces", + ]) + .expect_err("--parent needs a single workspace"); + assert_eq!(err.kind(), clap::error::ErrorKind::ArgumentConflict); + } + + #[test] + fn sandbox_create_parent_flag_parses() { + let cli = Cli::try_parse_from([ + "openshell", + "sandbox", + "create", + "--parent", + "lead", + "--provider", + "github", + ]) + .expect("sandbox create parent flag should parse"); + + match cli.command { + Some(Commands::Sandbox { + command: + Some(SandboxCommands::Create { + parent, providers, .. + }), + .. + }) => { + assert_eq!(parent.as_deref(), Some("lead")); + assert_eq!(providers, vec!["github".to_string()]); + } + other => panic!("expected SandboxCommands::Create, got: {other:?}"), + } + } + #[test] fn sandbox_create_template_conflicts_with_inline_workload_flags() { for (label, extra_args) in [ diff --git a/crates/openshell-cli/src/mcp_bridge.rs b/crates/openshell-cli/src/mcp_bridge.rs new file mode 100644 index 0000000000..53873a606a --- /dev/null +++ b/crates/openshell-cli/src/mcp_bridge.rs @@ -0,0 +1,404 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! `openshell mcp serve`: a local MCP server over stdio that forwards each +//! message to the gateway's `/mcp` with the CLI's login (RFC 0021). +//! +//! Stdout carries MCP messages only, one JSON-RPC message per line; the +//! client reads every line as one. Everything else goes to stderr. + +use openshell_bootstrap::oidc_token::{load_oidc_token, store_oidc_token}; +use openshell_sdk::{OpenShellClient, Refresh, RefreshError, RefreshedToken}; +use serde_json::{Value, json}; +use std::future::Future; +use std::sync::Arc; +use tokio::io::{AsyncBufRead, AsyncBufReadExt, AsyncWrite, AsyncWriteExt}; + +/// What the gateway answered to one forwarded message. +pub struct Sent { + pub status: u16, + pub body: Vec, +} + +/// Read MCP messages from `input` and answer each on `output`, one per line. +/// +/// Each message is sent on its own task, so a long `exec` never holds up a +/// `ping`; a whole reply line is written under one lock. Returns when `input` +/// closes and every call in flight has answered. +pub async fn serve(input: R, output: W, send: S) -> std::io::Result<()> +where + R: AsyncBufRead + Unpin, + W: AsyncWrite + Unpin + Send + 'static, + S: Fn(Vec) -> F + Clone + Send + 'static, + F: Future> + Send, +{ + let output = Arc::new(tokio::sync::Mutex::new(output)); + let mut input = input; + let mut raw = Vec::new(); + let mut calls = tokio::task::JoinSet::new(); + loop { + raw.clear(); + if input.read_until(b'\n', &mut raw).await? == 0 { + break; + } + // A line that is not UTF-8 cannot be JSON: answer it as a parse + // error, as for any other bad line, and keep reading. + let line = String::from_utf8(raw.clone()).map_or_else( + |_| "\u{fffd}".to_string(), + |line| line.trim_end_matches(['\r', '\n']).to_string(), + ); + if line.trim().is_empty() { + continue; + } + let output = Arc::clone(&output); + let send = send.clone(); + calls.spawn(async move { + let Some(reply) = reply_to(&line, send).await else { + return; + }; + let mut output = output.lock().await; + // A client that went away cannot be told anything. + let _ = output.write_all(format!("{reply}\n").as_bytes()).await; + let _ = output.flush().await; + }); + } + while calls.join_next().await.is_some() {} + Ok(()) +} + +/// The reply line for one message, or none for a notification the gateway +/// accepted. +async fn reply_to(line: &str, send: S) -> Option +where + S: Fn(Vec) -> F, + F: Future>, +{ + let Ok(message) = serde_json::from_str::(line) else { + return Some(rpc_error(&Value::Null, -32700, "parse error")); + }; + let id = message.get("id").cloned(); + let error = |message: String| id.as_ref().map(|id| rpc_error(id, -32000, &message)); + match send(line.as_bytes().to_vec()).await { + // Re-encode the reply so it is one line whatever the gateway sent. + Ok(Sent { status: 200, body }) => serde_json::from_slice::(&body).map_or_else( + |_| error("the gateway sent a reply that is not JSON".to_string()), + |reply| Some(reply.to_string()), + ), + Ok(Sent { status: 202, .. }) => None, + Ok(Sent { status, body }) => { + let text = String::from_utf8_lossy(&body); + let hint = match status { + 401 => "; run `openshell gateway login`", + _ => "", + }; + error(format!( + "the gateway refused the call (HTTP {status}): {}{hint}", + text.trim() + )) + } + Err(message) => error(message), + } +} + +fn rpc_error(id: &Value, code: i64, message: &str) -> String { + json!({"jsonrpc": "2.0", "id": id, "error": {"code": code, "message": message}}).to_string() +} + +/// The gateway client, built on first use. +/// +/// A built client is kept, and its login is refreshed by the client itself. +/// A failed build is not kept: that call answers with the fresh error and the +/// next call tries again, so a bridge started before `openshell gateway login` +/// works once the user logs in. Concurrent first calls share one attempt. +pub struct LazyClient { + client: tokio::sync::OnceCell, + build: M, +} + +impl LazyClient +where + C: Send + Sync, + M: Fn() -> F + Sync, + F: Future> + Send, +{ + pub fn new(build: M) -> Self { + Self { + client: tokio::sync::OnceCell::new(), + build, + } + } + + pub async fn get(&self) -> Result<&C, String> { + self.client.get_or_try_init(|| (self.build)()).await + } +} + +/// Forward one message with `client`, or explain why there is no client. +pub async fn send_with( + client: Result<&OpenShellClient, String>, + body: &[u8], + workspace: &str, +) -> Result { + let client = client?; + let reply = client + .post_mcp(body, workspace) + .await + .map_err(|error| format!("gateway unreachable: {error}"))?; + Ok(Sent { + status: reply.status.as_u16(), + body: reply.body, + }) +} + +/// Refreshes the gateway's stored OIDC login, as the CLI does at start-up, +/// for a bridge that outlives one access token. +pub struct StoredOidcRefresher { + pub gateway_name: String, + pub audience: Option, + pub scopes: Option, + pub insecure: bool, +} + +#[async_trait::async_trait] +impl Refresh for StoredOidcRefresher { + async fn refresh(&self) -> Result { + let bundle = load_oidc_token(&self.gateway_name).ok_or_else(|| { + RefreshError::Terminal(format!( + "no stored login; run `openshell gateway login {}`", + self.gateway_name + )) + })?; + let refreshed = crate::oidc_auth::oidc_renew_token( + &bundle, + self.audience.as_deref(), + self.scopes.as_deref(), + self.insecure, + ) + .await + .map_err(|error| RefreshError::Transient(error.to_string()))?; + if let Err(error) = store_oidc_token(&self.gateway_name, &refreshed) { + tracing::warn!("could not store the refreshed login: {error}"); + } + let token = RefreshedToken::new(refreshed.access_token); + Ok(match refreshed.expires_at { + Some(expires_at) => token.with_expires_at(expires_at), + None => token, + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Run the bridge over `input` with a gateway that answers by `answer`, + /// and return its stdout lines. + async fn bridge_lines(input: &str, answer: fn(&Value) -> Result) -> Vec { + let (writer, mut reader) = tokio::io::duplex(1 << 20); + let send = + move |body: Vec| async move { answer(&serde_json::from_slice(&body).unwrap()) }; + serve(input.as_bytes(), writer, send).await.unwrap(); + let mut out = String::new(); + tokio::io::AsyncReadExt::read_to_string(&mut reader, &mut out) + .await + .unwrap(); + out.lines().map(str::to_string).collect() + } + + fn gateway(message: &Value) -> Result { + let reply = |status, body: Value| { + Ok(Sent { + status, + body: body.to_string().into_bytes(), + }) + }; + match message["method"].as_str().unwrap_or_default() { + // Pretty-printed, to check the bridge sends it as one line. + "ping" => Ok(Sent { + status: 200, + body: serde_json::to_vec_pretty( + &json!({"jsonrpc": "2.0", "id": message["id"], "result": {}}), + ) + .unwrap(), + }), + "notifications/initialized" => reply(202, Value::Null), + "forbidden" => Ok(Sent { + status: 403, + body: b"requests with an Origin header are refused".to_vec(), + }), + "expired" => Ok(Sent { + status: 401, + body: Vec::new(), + }), + _ => Err("gateway unreachable: connection refused".to_string()), + } + } + + #[tokio::test] + async fn stdout_carries_one_json_rpc_message_per_line_and_nothing_else() { + let input = [ + r#"{"jsonrpc":"2.0","id":1,"method":"ping"}"#, + r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#, + "", + r#"{"jsonrpc":"2.0","id":2,"method":"forbidden"}"#, + r#"{"jsonrpc":"2.0","id":"three","method":"expired"}"#, + r#"{"jsonrpc":"2.0","id":4,"method":"down"}"#, + "not json", + ] + .join("\n"); + let lines = bridge_lines(&input, gateway).await; + + // Five replies: the notification and the blank line get none. + assert_eq!(lines.len(), 5, "{lines:?}"); + let mut by_id = std::collections::HashMap::new(); + for line in &lines { + let message: Value = serde_json::from_str(line).unwrap_or_else(|_| panic!("{line}")); + assert_eq!(message["jsonrpc"], "2.0", "{line}"); + by_id.insert(message["id"].to_string(), message); + } + assert_eq!(by_id["1"]["result"], json!({})); + assert!( + by_id["2"]["error"]["message"] + .as_str() + .unwrap() + .contains("HTTP 403") + ); + assert!( + by_id["\"three\""]["error"]["message"] + .as_str() + .unwrap() + .contains("openshell gateway login") + ); + assert!( + by_id["4"]["error"]["message"] + .as_str() + .unwrap() + .contains("unreachable") + ); + assert_eq!(by_id["null"]["error"]["code"], -32700); + } + + #[tokio::test] + async fn a_login_after_the_bridge_started_works_without_a_restart() { + use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; + + let logged_in = Arc::new(AtomicBool::new(false)); + let builds = Arc::new(AtomicUsize::new(0)); + let client = Arc::new(LazyClient::new({ + let (logged_in, builds) = (Arc::clone(&logged_in), Arc::clone(&builds)); + move || { + let (logged_in, builds) = (Arc::clone(&logged_in), Arc::clone(&builds)); + async move { + let attempt = builds.fetch_add(1, Ordering::SeqCst) + 1; + // A slow connect, so concurrent first calls overlap. + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + if logged_in.load(Ordering::SeqCst) { + Ok("client") + } else { + Err(format!("attempt {attempt}: run `openshell gateway login`")) + } + } + } + })); + let send = move |body: Vec| { + let client = Arc::clone(&client); + async move { + client.get().await?; + let message: Value = serde_json::from_slice(&body).unwrap(); + Ok(Sent { + status: 200, + body: json!({"jsonrpc": "2.0", "id": message["id"], "result": {}}) + .to_string() + .into_bytes(), + }) + } + }; + let (mut stdin, input) = tokio::io::duplex(1 << 16); + let (output, stdout) = tokio::io::duplex(1 << 16); + let bridge = tokio::spawn(serve(tokio::io::BufReader::new(input), output, send)); + let mut stdout = tokio::io::BufReader::new(stdout).lines(); + let ping = |id: usize| format!("{{\"jsonrpc\":\"2.0\",\"id\":{id},\"method\":\"ping\"}}\n"); + + stdin.write_all(ping(1).as_bytes()).await.unwrap(); + let first: Value = + serde_json::from_str(&stdout.next_line().await.unwrap().unwrap()).unwrap(); + assert_eq!( + first["error"]["message"], "attempt 1: run `openshell gateway login`", + "the call gets the error from its own attempt" + ); + + logged_in.store(true, Ordering::SeqCst); + for id in 2..=6 { + stdin.write_all(ping(id).as_bytes()).await.unwrap(); + } + for _ in 2..=6 { + let reply: Value = + serde_json::from_str(&stdout.next_line().await.unwrap().unwrap()).unwrap(); + assert_eq!(reply["result"], json!({}), "{reply}"); + } + assert_eq!( + builds.load(Ordering::SeqCst), + 2, + "one failed build, then one build shared by every later call" + ); + + drop(stdin); + bridge.await.unwrap().unwrap(); + } + + #[tokio::test] + async fn a_line_that_is_not_utf8_is_a_parse_error_and_the_bridge_keeps_reading() { + let (writer, mut reader) = tokio::io::duplex(1 << 20); + let mut input = b"\xff\xfe not utf-8\n".to_vec(); + input.extend_from_slice(b"{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"ping\"}\r\n"); + let send = |body: Vec| async move { gateway(&serde_json::from_slice(&body).unwrap()) }; + + serve(&input[..], writer, send).await.unwrap(); + + let mut out = String::new(); + tokio::io::AsyncReadExt::read_to_string(&mut reader, &mut out) + .await + .unwrap(); + let replies: Vec = out + .lines() + .map(|line| serde_json::from_str(line).unwrap()) + .collect(); + assert_eq!(replies.len(), 2, "{out}"); + let parse_error = replies.iter().find(|reply| reply["id"].is_null()).unwrap(); + assert_eq!(parse_error["error"]["code"], -32700); + assert_eq!(parse_error["error"]["message"], "parse error"); + let ping = replies.iter().find(|reply| reply["id"] == 1).unwrap(); + assert_eq!(ping["result"], json!({})); + } + + #[tokio::test] + async fn a_slow_call_does_not_hold_up_the_others() { + let (writer, mut reader) = tokio::io::duplex(1 << 20); + let send = |body: Vec| async move { + let message: Value = serde_json::from_slice(&body).unwrap(); + if message["method"] == "slow" { + tokio::time::sleep(std::time::Duration::from_secs(5)).await; + } + Ok(Sent { + status: 200, + body: json!({"jsonrpc": "2.0", "id": message["id"], "result": {}}) + .to_string() + .into_bytes(), + }) + }; + let input = "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"slow\"}\n\ + {\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"ping\"}\n"; + tokio::spawn(serve(input.as_bytes(), writer, send)); + + let mut first = String::new(); + let mut reader = tokio::io::BufReader::new(&mut reader); + tokio::time::timeout( + std::time::Duration::from_secs(2), + reader.read_line(&mut first), + ) + .await + .expect("the ping is answered before the slow call ends") + .unwrap(); + assert_eq!(serde_json::from_str::(&first).unwrap()["id"], 2); + } +} diff --git a/crates/openshell-cli/src/run.rs b/crates/openshell-cli/src/run.rs index feb05f2f45..0fed34f95e 100644 --- a/crates/openshell-cli/src/run.rs +++ b/crates/openshell-cli/src/run.rs @@ -78,7 +78,7 @@ use openshell_core::settings; use openshell_core::{ObjectId, ObjectName, ObjectWorkspace}; use prost::Message; use std::borrow::Cow; -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use std::io::{ErrorKind, IsTerminal, Read, Write}; use std::path::{Path, PathBuf}; use std::process::Command; @@ -447,6 +447,7 @@ async fn finalize_sandbox_create_session( pub struct SandboxCreateConfig<'a> { pub name: Option<&'a str>, pub template: Option<&'a str>, + pub parent: Option<&'a str>, pub from: Option<&'a str>, pub uploads: &'a [(String, Option, bool)], pub keep: bool, @@ -483,6 +484,7 @@ impl Default for SandboxCreateConfig<'_> { Self { name: None, template: None, + parent: None, from: None, uploads: &[], keep: false, @@ -1025,10 +1027,29 @@ pub async fn sandbox_create( config: SandboxCreateConfig<'_>, workspace: &str, tls: &TlsOptions, +) -> Result { + // Boxed so callers do not hold the whole create flow inline. + Box::pin(sandbox_create_boxed( + server, + gateway_name, + config, + workspace, + tls, + )) + .await +} + +async fn sandbox_create_boxed( + server: &str, + gateway_name: &str, + config: SandboxCreateConfig<'_>, + workspace: &str, + tls: &TlsOptions, ) -> Result { let SandboxCreateConfig { name, template, + parent, from, uploads, keep, @@ -1075,6 +1096,11 @@ pub async fn sandbox_create( if expose == Some(0) { return Err(miette::miette!("--expose port must be in 1..=65535")); } + if parent.is_some() && policy.is_some() { + return Err(miette::miette!( + "child sandboxes use their parent's policy; omit --policy" + )); + } // Plan every upload before provisioning so a rejected one leaves no sandbox. let upload_plans = uploads @@ -1141,11 +1167,23 @@ pub async fn sandbox_create( None => (None, None), } }; - let configured_providers = + // A child's providers must already be on its parent, which the gateway + // checks, so `--parent` never creates one from local credentials. + let configured_providers = if parent.is_some() { + child_provider_names(providers) + } else { ensure_required_providers(&mut client, providers, auto_providers_override, workspace) - .await?; + .await? + }; - let policy = load_sandbox_policy(policy)?; + let (policy, policy_note) = create_request_policy( + parent, + policy, + std::env::var("OPENSHELL_SANDBOX_POLICY").ok().as_deref(), + )?; + if let Some(note) = policy_note { + eprintln!("{note}"); + } let resource_limits = if template.is_none() { build_sandbox_resource_limits(cpu, memory)? } else { @@ -1200,6 +1238,7 @@ pub async fn sandbox_create( ); } let request = CreateSandboxRequest { + parent: parent.unwrap_or_default().to_string(), request_id: String::new(), spec: Some(SandboxSpec { resource_requirements, @@ -2072,6 +2111,43 @@ fn load_sandbox_policy(cli_path: Option<&str>) -> Result> openshell_policy::load_sandbox_policy(cli_path) } +/// A child's `--provider` names as given, each once, like a root's. +fn child_provider_names(providers: &[String]) -> Vec { + let mut names = Vec::with_capacity(providers.len()); + for name in providers { + if !names.contains(name) { + names.push(name.clone()); + } + } + names +} + +const IGNORED_POLICY_ENV_NOTE: &str = + "note: OPENSHELL_SANDBOX_POLICY is ignored; child sandboxes use their parent's policy"; + +/// The policy a create request sends, from `--policy` or else the +/// `OPENSHELL_SANDBOX_POLICY` value. A child uses its parent's policy, so with +/// `--parent` no source is read; the note says so when the variable is set. +/// A Cedar file is carried as-is; the gateway validates it. +fn create_request_policy( + parent: Option<&str>, + cli_path: Option<&str>, + env_path: Option<&str>, +) -> Result<(Option, Option<&'static str>)> { + if parent.is_some() { + return Ok((None, env_path.map(|_| IGNORED_POLICY_ENV_NOTE))); + } + let Some(path) = cli_path.or(env_path) else { + return Ok((None, None)); + }; + Ok(( + Some(openshell_policy::parse_sandbox_policy_file_auto( + Path::new(path), + )?), + None, + )) +} + /// Sync files to or from a sandbox. /// /// Dispatches to `sandbox_sync_up` or `sandbox_sync_down` based on the @@ -3402,6 +3478,7 @@ pub async fn sandbox_list( ids_only: bool, names_only: bool, label_selector: Option<&str>, + parent: Option<&str>, output: &str, workspace: &str, all_workspaces: bool, @@ -3414,6 +3491,7 @@ pub async fn sandbox_list( page_size, page_token: page_token.to_string(), label_selector: label_selector.unwrap_or("").to_string(), + parent: parent.unwrap_or_default().to_string(), workspace_scope: Some(if all_workspaces { openshell_core::proto::all_workspaces_selector() } else { @@ -3482,26 +3560,53 @@ pub async fn sandbox_list( 0 }; + // A PARENT column only when the page holds a child, so lists without + // children look as before. + let parent_labels = if sandboxes.iter().any(|s| s.parent.is_some()) { + Some(parent_column_labels(&mut client, &sandboxes).await) + } else { + None + }; + let parent_cell = |sandbox: &Sandbox| -> String { + sandbox.parent.as_ref().map_or_else( + || "-".to_string(), + |parent| { + parent_labels + .as_ref() + .and_then(|labels| labels.get(&parent.id).cloned()) + .unwrap_or_else(|| parent.name.clone()) + }, + ) + }; + let parent_width = parent_labels.as_ref().map_or(0, |_| { + sandboxes + .iter() + .map(|s| parent_cell(s).len()) + .max() + .unwrap_or(6) + .max(6) + }); + // Print header - if all_workspaces { - println!( - "{: phase.green().to_string(), @@ -3524,22 +3629,22 @@ pub async fn sandbox_list( .as_ref() .map_or(0, |m| proto_timestamp_ms(m.created_time.as_ref())), ); - if all_workspaces { - println!( - "{: serde_json::Value { "configuration_admission": admission, "provisioning": provisioning, "created_from_workload_template": created_from_workload_template, + "parent": sandbox.parent.as_ref().map(|parent| serde_json::json!({ + "name": parent.name, + "id": parent.id, + })), }) } +/// The PARENT column for one parent id, given the sandbox currently holding +/// the parent's name, or the error from looking it up. Only "not found" or a +/// different id means the parent was deleted; any other error keeps the +/// recorded name. +fn parent_column_label( + parent: &openshell_core::proto::SandboxParent, + lookup: Result, Code>, +) -> String { + match lookup { + Ok(Some(id)) if id == parent.id => parent.name.clone(), + Ok(_) | Err(Code::NotFound) => format!("deleted ({})", parent.id), + Err(_) => parent.name.clone(), + } +} + +/// PARENT column labels by parent id. A parent listed in the same response +/// needs no lookup; any other is looked up once by name. +async fn parent_column_labels( + client: &mut GrpcClient, + sandboxes: &[Sandbox], +) -> HashMap { + let mut labels = HashMap::new(); + for sandbox in sandboxes { + let Some(parent) = sandbox.parent.as_ref() else { + continue; + }; + if labels.contains_key(&parent.id) { + continue; + } + let label = if sandboxes.iter().any(|s| s.object_id() == parent.id) { + parent.name.clone() + } else { + let lookup = client + .get_sandbox(GetSandboxRequest { + name: parent.name.clone(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + sandbox.object_workspace(), + )), + }) + .await; + match lookup { + Ok(response) => { + let current = response.into_inner().sandbox; + parent_column_label(parent, Ok(current.as_ref().map(ObjectId::object_id))) + } + Err(status) => parent_column_label(parent, Err(status.code())), + } + }; + labels.insert(parent.id.clone(), label); + } + labels +} + fn sandbox_condition_to_json(condition: &SandboxCondition) -> serde_json::Value { let transition_time = condition .transition_time @@ -4539,6 +4701,9 @@ pub async fn sandbox_delete( ) -> Result<()> { let mut client = grpc_client(server, tls).await?; + // Roots that had a child in the `--all` listing. Their children are + // deleted first, and the gateway refuses a root until those deletes finish. + let mut roots_with_children = HashSet::new(); let names_to_delete: Vec = if all { let mut page_token = String::new(); let mut sandboxes = Vec::new(); @@ -4548,6 +4713,7 @@ pub async fn sandbox_delete( page_size: 1000, page_token, label_selector: String::new(), + parent: String::new(), workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), }) .await @@ -4563,6 +4729,14 @@ pub async fn sandbox_delete( println!("No sandboxes to delete."); return Ok(()); } + // A root cannot be deleted while it has children. + sandboxes.sort_by_key(|sandbox| sandbox.parent.is_none()); + roots_with_children.extend( + sandboxes + .iter() + .filter_map(|sandbox| sandbox.parent.as_ref()) + .map(|parent| parent.name.clone()), + ); sandboxes .into_iter() .map(|s| s.object_name().to_string()) @@ -4583,6 +4757,9 @@ pub async fn sandbox_delete( } } + if roots_with_children.contains(name) { + wait_for_child_deletes(&mut client, workspace, name).await; + } let response = match client .delete_sandbox(DeleteSandboxRequest { request_id: String::new(), @@ -4629,6 +4806,54 @@ pub async fn sandbox_delete( aggregate_delete_failures("sandbox", &failures) } +/// How long `sandbox delete --all` waits for a root's children to finish +/// deleting. +const CHILD_DELETE_WAIT: Duration = Duration::from_mins(2); + +/// Wait until a root has no children left whose delete has started, since the +/// gateway refuses to delete a root while any child remains. Only `--all` +/// waits, and only on a root whose children it just deleted. Returns at once +/// when a child is not being deleted or the children cannot be listed, and +/// after [`CHILD_DELETE_WAIT`]; the delete then reports why it is refused. +async fn wait_for_child_deletes(client: &mut GrpcClient, workspace: &str, name: &str) { + let deadline = Instant::now() + CHILD_DELETE_WAIT; + let mut announced = false; + loop { + let Ok(response) = client + .list_sandboxes(ListSandboxesRequest { + page_size: 1000, + page_token: String::new(), + label_selector: String::new(), + parent: name.to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), + }) + .await + else { + return; + }; + let children = response.into_inner().sandboxes; + let all_deleting = children + .iter() + .all(|child| child.phase() == SandboxPhase::Deleting as i32); + if children.is_empty() || !all_deleting || Instant::now() >= deadline { + return; + } + if !announced { + let noun = if children.len() == 1 { + "child sandbox" + } else { + "child sandboxes" + }; + eprintln!( + "Waiting for {} {noun} of {name} to finish deleting", + children.len() + ); + announced = true; + } + tokio::time::sleep(Duration::from_secs(1)).await; + } +} + /// Stop a sandbox while retaining its persistent workspace. pub async fn sandbox_stop( server: &str, @@ -7925,6 +8150,78 @@ mod tests { assert_eq!(update, expected); } + #[test] + fn the_parent_column_shows_deleted_only_when_the_parent_is_gone() { + use super::parent_column_label; + use tonic::Code; + + let parent = openshell_core::proto::SandboxParent { + name: "lead".to_string(), + id: "lead-id".to_string(), + }; + assert_eq!(parent_column_label(&parent, Ok(Some("lead-id"))), "lead"); + // A new root under the old name is not this child's parent. + assert_eq!( + parent_column_label(&parent, Ok(Some("new-id"))), + "deleted (lead-id)" + ); + assert_eq!( + parent_column_label(&parent, Err(Code::NotFound)), + "deleted (lead-id)" + ); + assert_eq!(parent_column_label(&parent, Err(Code::Unavailable)), "lead"); + assert_eq!( + parent_column_label(&parent, Err(Code::PermissionDenied)), + "lead" + ); + } + + #[test] + fn sandbox_json_includes_the_parent() { + use openshell_core::proto::{Sandbox, SandboxParent}; + + let root = Sandbox::default(); + assert!(super::sandbox_to_json(&root)["parent"].is_null()); + + let child = Sandbox { + parent: Some(SandboxParent { + name: "lead".to_string(), + id: "lead-id".to_string(), + }), + ..Default::default() + }; + let json = super::sandbox_to_json(&child); + assert_eq!(json["parent"]["name"], "lead"); + assert_eq!(json["parent"]["id"], "lead-id"); + } + + #[test] + fn a_child_create_ignores_the_policy_env_var_with_a_note() { + use super::{IGNORED_POLICY_ENV_NOTE, create_request_policy}; + + // The path does not exist, so any attempt to read it fails. + let missing = "/nonexistent/openshell-policy.yaml"; + let (policy, note) = create_request_policy(Some("lead"), None, Some(missing)) + .expect("a child create never reads the env policy"); + assert!(policy.is_none()); + assert_eq!(note, Some(IGNORED_POLICY_ENV_NOTE)); + + assert!(create_request_policy(None, None, Some(missing)).is_err()); + assert_eq!( + create_request_policy(Some("lead"), None, None).unwrap().1, + None + ); + } + + #[test] + fn a_child_create_sends_each_provider_once() { + let names = |list: &[&str]| list.iter().map(ToString::to_string).collect::>(); + assert_eq!( + super::child_provider_names(&names(&["github", "slack", "github"])), + names(&["github", "slack"]) + ); + } + #[test] fn lifecycle_wait_fails_fast_on_phases_that_block_the_target() { use super::lifecycle_phase_blocks_target; diff --git a/crates/openshell-cli/src/tls.rs b/crates/openshell-cli/src/tls.rs index fd138aae5b..d004dc11a9 100644 --- a/crates/openshell-cli/src/tls.rs +++ b/crates/openshell-cli/src/tls.rs @@ -337,6 +337,22 @@ pub async fn build_channel(server: &str, tls: &TlsOptions) -> Result { .into_diagnostic() } +/// Build the SDK client itself. With `refresh`, an OIDC login is refreshed +/// for as long as the client lives, not only when the command starts. +pub async fn sdk_client( + server: &str, + tls: &TlsOptions, + refresh: Option>, +) -> Result { + let mut config = sdk_client_config(server, tls)?; + if let (Some(refresher), Some(AuthConfig::Oidc { refresh, .. })) = (refresh, &mut config.auth) { + *refresh = Some(refresher); + } + Box::pin(OpenShellClient::connect(config)) + .await + .into_diagnostic() +} + /// Build the SDK client and return its raw gRPC escape hatch. /// /// The returned client carries a [`GatewayInterceptor`] that injects diff --git a/crates/openshell-cli/tests/mcp_serve_integration.rs b/crates/openshell-cli/tests/mcp_serve_integration.rs new file mode 100644 index 0000000000..12108b2fda --- /dev/null +++ b/crates/openshell-cli/tests/mcp_serve_integration.rs @@ -0,0 +1,75 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! `openshell mcp serve` writes nothing but JSON-RPC messages to stdout, even +//! with verbose logging and no usable gateway. + +use std::io::Write; +use std::process::{Command, Stdio}; + +fn serve(extra_args: &[&str], envs: &[(&str, &str)]) -> (Vec, String) { + let config_dir = tempfile::tempdir().unwrap(); + let system_dir = tempfile::tempdir().unwrap(); + let mut command = Command::new(env!("CARGO_BIN_EXE_openshell")); + command + .args(extra_args) + .args(["mcp", "serve"]) + .env("XDG_CONFIG_HOME", config_dir.path()) + .env("HOME", config_dir.path()) + .env("OPENSHELL_SYSTEM_GATEWAY_DIR", system_dir.path()) + .env("OPENSHELL_NO_BROWSER", "1") + .env_remove("OPENSHELL_GATEWAY") + .env_remove("OPENSHELL_GATEWAY_ENDPOINT") + .env_remove("RUST_LOG") + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + for (name, value) in envs { + command.env(name, value); + } + let mut child = command.spawn().expect("run openshell mcp serve"); + child + .stdin + .take() + .unwrap() + .write_all( + concat!( + r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18"}}"#, + "\n", + r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#, + "\n", + r#"{"jsonrpc":"2.0","id":2,"method":"tools/list"}"#, + "\n", + ) + .as_bytes(), + ) + .unwrap(); + let output = child.wait_with_output().unwrap(); + assert!(output.status.success(), "{output:?}"); + let stdout = String::from_utf8(output.stdout).unwrap(); + let stderr = String::from_utf8(output.stderr).unwrap(); + (stdout.lines().map(str::to_string).collect(), stderr) +} + +fn assert_only_json_rpc(lines: &[String], stderr: &str) { + assert_eq!(lines.len(), 2, "stdout: {lines:?}\nstderr: {stderr}"); + for line in lines { + let message: serde_json::Value = + serde_json::from_str(line).unwrap_or_else(|_| panic!("not JSON-RPC: {line}")); + assert_eq!(message["jsonrpc"], "2.0", "{line}"); + } +} + +#[test] +fn without_a_gateway_every_call_gets_a_json_rpc_error() { + let (lines, stderr) = serve(&["-vvv"], &[]); + assert_only_json_rpc(&lines, &stderr); + assert!(lines[0].contains("No active gateway"), "{lines:?}"); +} + +#[test] +fn with_an_unreachable_gateway_logs_stay_on_stderr() { + let (lines, stderr) = serve(&["-vvv", "--gateway-endpoint", "http://127.0.0.1:9"], &[]); + assert_only_json_rpc(&lines, &stderr); + assert!(lines[0].contains("cannot reach the gateway"), "{lines:?}"); +} diff --git a/crates/openshell-cli/tests/sandbox_create_lifecycle_integration.rs b/crates/openshell-cli/tests/sandbox_create_lifecycle_integration.rs index 8d616c69ba..3827e4b33f 100644 --- a/crates/openshell-cli/tests/sandbox_create_lifecycle_integration.rs +++ b/crates/openshell-cli/tests/sandbox_create_lifecycle_integration.rs @@ -120,6 +120,9 @@ struct SandboxState { global_settings: Arc>>, gateway_config_requests: Arc, providers: Arc>>, + provider_create_requests: Arc, + list_requests: Arc>>, + list_response: Arc>>, template_create_requests: Arc>>, template_get_requests: Arc>>, template_list_requests: Arc>>, @@ -355,9 +358,29 @@ impl OpenShell for TestOpenShell { async fn list_sandboxes( &self, - _request: tonic::Request, + request: tonic::Request, ) -> Result, Status> { - Ok(Response::new(ListSandboxesResponse::default())) + let request = request.into_inner(); + let sandboxes = self + .state + .list_response + .lock() + .await + .iter() + .filter(|sandbox| { + request.parent.is_empty() + || sandbox + .parent + .as_ref() + .is_some_and(|parent| parent.name == request.parent) + }) + .cloned() + .collect(); + self.state.list_requests.lock().await.push(request); + Ok(Response::new(ListSandboxesResponse { + sandboxes, + next_page_token: String::new(), + })) } async fn create_sandbox_template( @@ -629,6 +652,9 @@ impl OpenShell for TestOpenShell { &self, _request: tonic::Request, ) -> Result, Status> { + self.state + .provider_create_requests + .fetch_add(1, Ordering::SeqCst); Ok(Response::new(ProviderResponse::default())) } @@ -1608,6 +1634,123 @@ async fn sandbox_delete_continues_after_entry_failure() { ); } +fn child_of_lead(name: &str, deleting: bool) -> Sandbox { + let mut child = Sandbox { + metadata: Some(openshell_core::proto::datamodel::v1::ObjectMeta { + id: format!("id-{name}"), + name: name.to_string(), + workspace: "default".to_string(), + ..Default::default() + }), + parent: Some(openshell_core::proto::SandboxParent { + name: "lead".to_string(), + id: "id-lead".to_string(), + }), + ..Sandbox::default() + }; + let phase = if deleting { + SandboxPhase::Deleting + } else { + SandboxPhase::Ready + }; + child.set_phase(phase as i32); + child +} + +fn root(name: &str) -> Sandbox { + Sandbox { + metadata: Some(openshell_core::proto::datamodel::v1::ObjectMeta { + id: format!("id-{name}"), + name: name.to_string(), + workspace: "default".to_string(), + ..Default::default() + }), + ..Sandbox::default() + } +} + +async fn delete_all(server: &TestServer) -> miette::Result<()> { + let tls = test_tls(server); + tokio::time::timeout( + Duration::from_secs(10), + run::sandbox_delete(&server.endpoint, &[], true, "default", &tls, "openshell"), + ) + .await + .expect("sandbox delete --all finishes") +} + +#[tokio::test] +async fn sandbox_delete_all_waits_for_the_children_it_deleted() { + let server = run_server().await; + let state = server.openshell.state.clone(); + *state.list_response.lock().await = vec![root("lead"), child_of_lead("worker1", true)]; + // The child's delete finishes once the CLI has asked for the root's children. + let finisher = { + let state = state.clone(); + tokio::spawn(async move { + while !state + .list_requests + .lock() + .await + .iter() + .any(|request| request.parent == "lead") + { + tokio::time::sleep(Duration::from_millis(10)).await; + } + *state.list_response.lock().await = vec![root("lead")]; + }) + }; + + delete_all(&server).await.expect("everything is deleted"); + finisher.await.unwrap(); + + let lists = state.list_requests.lock().await; + assert!(lists[0].parent.is_empty(), "the listing of every sandbox"); + assert!(lists.len() >= 3, "listed again after the child was seen"); + assert!(lists[1..].iter().all(|request| request.parent == "lead")); + assert_eq!( + deleted_names(&server).await, + vec![vec!["worker1".to_string()], vec!["lead".to_string()]] + ); +} + +#[tokio::test] +async fn sandbox_delete_all_lists_once_when_no_root_has_children() { + let server = run_server().await; + let state = server.openshell.state.clone(); + *state.list_response.lock().await = vec![root("one"), root("two")]; + + delete_all(&server).await.expect("everything is deleted"); + + assert_eq!(state.list_requests.lock().await.len(), 1); + assert_eq!( + deleted_names(&server).await, + vec![vec!["one".to_string()], vec!["two".to_string()]] + ); +} + +#[tokio::test] +async fn sandbox_delete_by_name_lists_nothing() { + let server = run_server().await; + let tls = test_tls(&server); + let state = server.openshell.state.clone(); + *state.list_response.lock().await = vec![root("lead"), child_of_lead("worker1", true)]; + + run::sandbox_delete( + &server.endpoint, + &["lead".to_string()], + false, + "default", + &tls, + "openshell", + ) + .await + .expect("the gateway, not the CLI, decides whether the root can go"); + + assert!(state.list_requests.lock().await.is_empty()); + assert_eq!(deleted_names(&server).await, vec![vec!["lead".to_string()]]); +} + #[tokio::test] async fn sandbox_create_tolerates_an_unreachable_profile_catalog() { // The catalog's only consumer is the advisory credential warning, so a @@ -1800,6 +1943,89 @@ async fn sandbox_create_sends_cpu_and_memory_limits_only() { .await; } +#[tokio::test] +async fn child_create_sends_provider_names_without_creating_providers() { + let server = run_server().await; + let fake_ssh_dir = helpers::tempdir().unwrap(); + let xdg_dir = helpers::tempdir().unwrap(); + + // Local credentials a root create would turn into a new provider. + test_env_with( + &fake_ssh_dir, + &xdg_dir, + &[("ANTHROPIC_API_KEY", "sk-test".to_string())], + ) + .run_async(async { + let tls = test_tls(&server); + install_fake_ssh(&fake_ssh_dir); + + run::sandbox_create( + &server.endpoint, + "openshell", + run::SandboxCreateConfig { + name: Some("worker"), + parent: Some("lead"), + providers: &["anthropic".into()], + auto_providers_override: Some(true), + command: &["echo".into(), "OK".into()], + ..test_config() + }, + "default", + &tls, + ) + .await + .expect("sandbox create should succeed"); + + assert_eq!( + server + .openshell + .state + .provider_create_requests + .load(Ordering::SeqCst), + 0 + ); + let requests = create_requests(&server).await; + assert_eq!(requests[0].parent, "lead"); + let spec = requests[0].spec.as_ref().unwrap(); + assert_eq!(spec.providers, vec!["anthropic".to_string()]); + assert!(spec.policy.is_none()); + }) + .await; +} + +#[tokio::test] +async fn child_create_refuses_a_policy_before_sending() { + 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); + let error = run::sandbox_create( + &server.endpoint, + "openshell", + run::SandboxCreateConfig { + name: Some("worker"), + parent: Some("lead"), + policy: Some("policy.yaml"), + ..test_config() + }, + "default", + &tls, + ) + .await + .expect_err("a child create with a policy should be refused"); + + assert_eq!( + error.to_string(), + "child sandboxes use their parent's policy; omit --policy" + ); + assert!(create_requests(&server).await.is_empty()); + }) + .await; +} + #[tokio::test] async fn sandbox_create_persists_exact_trailing_argv_as_main_process() { let server = run_server().await; @@ -6156,3 +6382,51 @@ async fn sandbox_create_stops_a_missing_holder_retry_when_the_budget_is_spent() }) .await; } + +fn listed_child(name: &str, parent: &str, parent_id: &str) -> Sandbox { + Sandbox { + metadata: Some(openshell_core::proto::datamodel::v1::ObjectMeta { + id: format!("id-{name}"), + name: name.to_string(), + workspace: "default".to_string(), + ..Default::default() + }), + parent: Some(openshell_core::proto::SandboxParent { + name: parent.to_string(), + id: parent_id.to_string(), + }), + ..Default::default() + } +} + +#[tokio::test] +async fn sandbox_list_sends_the_parent_filter_and_labels_children() { + let server = run_server().await; + // The mock answers GetSandbox("lead") with id "id-lead", so worker1's + // parent is live and worker2's ("gone-id") was deleted. + *server.openshell.state.list_response.lock().await = vec![ + listed_child("worker1", "lead", "id-lead"), + listed_child("worker2", "lead", "gone-id"), + ]; + let tls = test_tls(&server); + + run::sandbox_list( + &server.endpoint, + 100, + "", + false, + false, + None, + Some("lead"), + "table", + "default", + false, + &tls, + ) + .await + .expect("sandbox list should succeed"); + + let requests = server.openshell.state.list_requests.lock().await; + assert_eq!(requests.len(), 1); + assert_eq!(requests[0].parent, "lead"); +} diff --git a/crates/openshell-core/src/config.rs b/crates/openshell-core/src/config.rs index 2d3f37c7eb..70a15e58cf 100644 --- a/crates/openshell-core/src/config.rs +++ b/crates/openshell-core/src/config.rs @@ -491,6 +491,14 @@ pub struct Config { /// [`MUTATION_REPLAY_WINDOW_SECONDS_RANGE`]. pub mutation_replay_window_seconds: u32, + /// Allow creating child sandboxes under a root sandbox. Disabled by + /// default; turning it off blocks only new children. + pub enable_child_sandboxes: bool, + + /// Maximum number of children one parent may have at once. Must be + /// between 0 and 1000, inclusive; 0 allows none. + pub max_concurrent_children: u32, + /// Maximum gRPC requests allowed per rate-limit window. /// /// When paired with [`Self::grpc_rate_limit_window_secs`], positive values @@ -1355,6 +1363,8 @@ impl Config { provisioning_repair_window_seconds: 300, mutation_admission_limit_per_caller: DEFAULT_MUTATION_ADMISSION_LIMIT_PER_CALLER, mutation_replay_window_seconds: DEFAULT_MUTATION_REPLAY_WINDOW_SECONDS, + enable_child_sandboxes: false, + max_concurrent_children: 10, grpc_rate_limit_requests: None, grpc_rate_limit_window_secs: None, service_routing: ServiceRoutingConfig::default(), diff --git a/crates/openshell-gateway-interceptors/src/proto_json.rs b/crates/openshell-gateway-interceptors/src/proto_json.rs index f34c791adc..8a395e5778 100644 --- a/crates/openshell-gateway-interceptors/src/proto_json.rs +++ b/crates/openshell-gateway-interceptors/src/proto_json.rs @@ -308,6 +308,7 @@ mod tests { let codec = ProtoJsonCodec::from_descriptor_set(openshell_core::FILE_DESCRIPTOR_SET).unwrap(); let request = CreateSandboxRequest { + parent: String::new(), request_id: String::new(), spec: Some(SandboxSpec { providers: vec!["github".to_string()], diff --git a/crates/openshell-gateway-interceptors/src/runtime.rs b/crates/openshell-gateway-interceptors/src/runtime.rs index a92391e9e6..e9a1f06a09 100644 --- a/crates/openshell-gateway-interceptors/src/runtime.rs +++ b/crates/openshell-gateway-interceptors/src/runtime.rs @@ -1097,6 +1097,7 @@ mod tests { let codec = ProtoJsonCodec::from_descriptor_set(openshell_core::FILE_DESCRIPTOR_SET).unwrap(); let request = CreateSandboxRequest { + parent: String::new(), request_id: String::new(), spec: Some(SandboxSpec { template: Some(SandboxTemplate { diff --git a/crates/openshell-sdk/Cargo.toml b/crates/openshell-sdk/Cargo.toml index 6c4d0523b4..1d7c5d4f22 100644 --- a/crates/openshell-sdk/Cargo.toml +++ b/crates/openshell-sdk/Cargo.toml @@ -15,6 +15,8 @@ openshell-crypto = { workspace = true } openshell-core = { path = "../openshell-core" } async-trait = "0.1" futures = { workspace = true } +http = { workspace = true } +http-body-util = { workspace = true } hyper = { workspace = true } hyper-util = { workspace = true } miette = { workspace = true } diff --git a/crates/openshell-sdk/src/client.rs b/crates/openshell-sdk/src/client.rs index 7d11bf3e9c..59b377ae8c 100644 --- a/crates/openshell-sdk/src/client.rs +++ b/crates/openshell-sdk/src/client.rs @@ -35,6 +35,25 @@ use std::time::{Duration, Instant}; use tonic::metadata::AsciiMetadataValue; use tonic::transport::Channel; +const MCP_PATH: &str = "/mcp"; +/// The workspace a user acts in over MCP, read by the gateway's `/mcp`. +const MCP_WORKSPACE_HEADER: &str = "x-openshell-workspace"; +/// A `/mcp` call's own limit, longer than the SDK's RPCs: an `exec` can take +/// about 50 s. +const MCP_CALL_TIMEOUT: Duration = Duration::from_secs(90); +/// Largest `/mcp` reply read. +const MAX_MCP_REPLY_BYTES: usize = 8 * 1024 * 1024; + +/// The gateway's HTTP answer to one `/mcp` message. +#[derive(Debug)] +pub struct McpReply { + /// HTTP status: 200 with a JSON-RPC reply, 202 for a notification, or an + /// error such as 401 or 403 with a short text body. + pub status: http::StatusCode, + /// The response body. + pub body: Vec, +} + /// Async client for a single `OpenShell` gateway. /// /// Cheap to clone — the underlying tonic [`Channel`] multiplexes RPCs over a @@ -178,6 +197,80 @@ impl OpenShellClient { self.refresh_on_unauthorized().await } + /// Experimental: the gateway's MCP tools, and this method, may change or be + /// removed between releases. + /// + /// Send one MCP message to the gateway's `/mcp`, acting in `workspace`, + /// with this client's credentials and over its own connection (TLS, mTLS + /// and the edge tunnel included). + /// + /// A token near expiry is refreshed first. Only an HTTP 401 is retried, + /// once, after a forced refresh: the request reached no handler, so + /// sending it again is safe. Timeouts, resets and server errors are not + /// retried, since a tool call such as `exec` may already have run. + pub async fn post_mcp(&self, body: &[u8], workspace: &str) -> Result { + self.post_mcp_within(body, workspace, MCP_CALL_TIMEOUT) + .await + } + + async fn post_mcp_within( + &self, + body: &[u8], + workspace: &str, + timeout: Duration, + ) -> Result { + self.ensure_fresh().await?; + let reply = self.send_mcp(body, workspace, timeout).await?; + if reply.status == http::StatusCode::UNAUTHORIZED && self.refresh_on_unauthorized().await? { + return self.send_mcp(body, workspace, timeout).await; + } + Ok(reply) + } + + async fn send_mcp(&self, body: &[u8], workspace: &str, timeout: Duration) -> Result { + use http_body_util::BodyExt; + use tonic::service::Interceptor; + use tower::ServiceExt; + + let credentials = self + .interceptor + .clone() + .call(tonic::Request::new(())) + .map_err(|status| SdkError::auth(status.message()))?; + let mut request = http::Request::builder() + .method(http::Method::POST) + .uri(MCP_PATH) + .header(http::header::CONTENT_TYPE, "application/json") + .header(MCP_WORKSPACE_HEADER, workspace) + .body(tonic::body::Body::new(http_body_util::Full::new( + hyper::body::Bytes::copy_from_slice(body), + ))) + .map_err(|e| SdkError::invalid_config(format!("invalid /mcp request: {e}")))?; + request + .headers_mut() + .extend(credentials.metadata().clone().into_headers()); + + let call = async { + let response = self + .channel + .clone() + .oneshot(request) + .await + .map_err(|e| SdkError::connect(format!("/mcp request failed: {e}")))?; + let status = response.status(); + let body = http_body_util::Limited::new(response.into_body(), MAX_MCP_REPLY_BYTES) + .collect() + .await + .map_err(|e| SdkError::connect(format!("/mcp reply failed: {e}")))? + .to_bytes() + .to_vec(); + Ok(McpReply { status, body }) + }; + tokio::time::timeout(timeout, call) + .await + .map_err(|_| SdkError::connect("the gateway did not answer /mcp in time"))? + } + /// Gateway health snapshot. pub async fn health(&self) -> Result { let resp = self @@ -230,7 +323,7 @@ impl OpenShellClient { options: CreateRetryOptions, ) -> Result { let request = create_sandbox_request(spec); - self.create_with_retry(request, "default", options).await + Box::pin(self.create_with_retry(request, "default", options)).await } /// Create a new sandbox from a workload template, retrying while the @@ -245,7 +338,7 @@ impl OpenShellClient { options: CreateRetryOptions, ) -> Result { let request = create_sandbox_from_template_request(spec); - self.create_with_retry(request, "default", options).await + Box::pin(self.create_with_retry(request, "default", options)).await } /// Create a reusable sandbox template in the default workspace. @@ -403,6 +496,7 @@ impl OpenShellClient { page_size: opts.page_size, page_token, label_selector: opts.label_selector.clone().unwrap_or_default(), + parent: String::new(), workspace_scope: Some(proto::workspace_selector("default")), }; async move { grpc.list_sandboxes(request).await } @@ -593,6 +687,7 @@ impl OpenShellClient { page_size: opts.page_size, page_token, label_selector: opts.label_selector.clone().unwrap_or_default(), + parent: String::new(), workspace_scope: Some(proto::all_workspaces_selector()), }; async move { grpc.list_sandboxes(request).await } @@ -1384,9 +1479,11 @@ impl WorkspaceScopedClient { ) -> Result { let mut request = create_sandbox_request(spec); request.workspace_scope = Some(proto::workspace_selector(&self.workspace)); - self.client - .create_with_retry(request, &self.workspace, options) - .await + Box::pin( + self.client + .create_with_retry(request, &self.workspace, options), + ) + .await } /// Create a new sandbox from a template in this workspace, retrying while @@ -1398,9 +1495,11 @@ impl WorkspaceScopedClient { ) -> Result { let mut request = create_sandbox_from_template_request(spec); request.workspace_scope = Some(proto::workspace_selector(&self.workspace)); - self.client - .create_with_retry(request, &self.workspace, options) - .await + Box::pin( + self.client + .create_with_retry(request, &self.workspace, options), + ) + .await } /// Create a reusable sandbox template in this workspace. @@ -1524,6 +1623,7 @@ impl WorkspaceScopedClient { page_size: opts.page_size, page_token, label_selector: opts.label_selector.clone().unwrap_or_default(), + parent: String::new(), workspace_scope: Some(proto::workspace_selector(&workspace)), }; async move { grpc.list_sandboxes(request).await } @@ -1850,6 +1950,7 @@ fn create_sandbox_request(spec: SandboxSpec) -> proto::CreateSandboxRequest { gpu: Some(proto::GpuResourceRequirements { count: None }), }); proto::CreateSandboxRequest { + parent: String::new(), request_id: String::new(), spec: Some(proto::SandboxSpec { environment, @@ -1894,6 +1995,7 @@ fn create_sandbox_from_template_request( service_exposures, } = spec; proto::CreateSandboxRequest { + parent: String::new(), request_id: String::new(), spec: Some(proto::SandboxSpec { providers, @@ -2183,6 +2285,45 @@ mod tests { } } + /// A request the gateway never answers ends at the call's own limit and + /// is not sent again: `exec` may already be running. + #[tokio::test] + async fn a_mcp_call_that_times_out_is_not_retried() { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let endpoint = format!("http://{}", listener.local_addr().unwrap()); + let requests = Arc::new(AtomicUsize::new(0)); + let seen = Arc::clone(&requests); + tokio::spawn(async move { + let (stream, _) = listener.accept().await.unwrap(); + let service = hyper::service::service_fn(move |_request| { + seen.fetch_add(1, Ordering::SeqCst); + std::future::pending::< + std::result::Result< + http::Response>, + std::convert::Infallible, + >, + >() + }); + let _ = hyper::server::conn::http2::Builder::new(hyper_util::rt::TokioExecutor::new()) + .serve_connection(hyper_util::rt::TokioIo::new(stream), service) + .await; + }); + let client = OpenShellClient::connect(ClientConfig::new(endpoint)) + .await + .unwrap(); + + let error = client + .post_mcp_within(b"{}", "default", Duration::from_millis(200)) + .await + .unwrap_err(); + + assert!( + error.to_string().contains("did not answer /mcp in time"), + "{error}" + ); + assert_eq!(requests.load(Ordering::SeqCst), 1); + } + struct FailingRefresher; #[async_trait::async_trait] diff --git a/crates/openshell-sdk/src/lib.rs b/crates/openshell-sdk/src/lib.rs index 2ca6fa6ec8..d7d3b03255 100644 --- a/crates/openshell-sdk/src/lib.rs +++ b/crates/openshell-sdk/src/lib.rs @@ -45,7 +45,7 @@ pub mod transport; pub mod types; pub use auth::EdgeAuthInterceptor; -pub use client::{OpenShellClient, WorkspaceScopedClient}; +pub use client::{McpReply, OpenShellClient, WorkspaceScopedClient}; pub use config::{AuthConfig, ClientConfig, ClientIdentity}; pub use error::SdkError; pub use pagination::{Page, Pager}; diff --git a/crates/openshell-sdk/tests/client_mock.rs b/crates/openshell-sdk/tests/client_mock.rs index 39d2f6b01e..e54cdbea30 100644 --- a/crates/openshell-sdk/tests/client_mock.rs +++ b/crates/openshell-sdk/tests/client_mock.rs @@ -147,6 +147,8 @@ fn sandbox_with_phase_ws( resource_version: "7".to_string(), }); proto::Sandbox { + created_on_behalf_of: None, + parent: None, metadata: Some(proto::datamodel::v1::ObjectMeta { id: format!("id-{name}"), name: name.to_string(), diff --git a/crates/openshell-sdk/tests/post_mcp.rs b/crates/openshell-sdk/tests/post_mcp.rs new file mode 100644 index 0000000000..9375845680 --- /dev/null +++ b/crates/openshell-sdk/tests/post_mcp.rs @@ -0,0 +1,170 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! `OpenShellClient::post_mcp` against a local HTTP/2 server standing in for +//! the gateway's `/mcp`. + +use http_body_util::Full; +use hyper::body::{Bytes, Incoming}; +use hyper::{Request, Response, StatusCode}; +use hyper_util::rt::{TokioExecutor, TokioIo}; +use openshell_sdk::{ + AuthConfig, ClientConfig, OpenShellClient, Refresh, RefreshError, RefreshedToken, +}; +use std::convert::Infallible; +use std::sync::Arc; +use std::sync::Mutex; +use std::sync::atomic::{AtomicU32, Ordering}; +use tokio::net::TcpListener; + +/// How the stand-in gateway answers. +#[derive(Clone, Copy)] +enum Answer { + /// 200 for `Bearer fresh-token`, 401 for anything else. + FreshTokenOnly, + Always(StatusCode), +} + +#[derive(Default)] +struct Seen { + requests: AtomicU32, + authorization: Mutex>, + workspace: Mutex>, +} + +async fn start(answer: Answer) -> (String, Arc) { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let endpoint = format!("http://{}", listener.local_addr().unwrap()); + let seen = Arc::new(Seen::default()); + let server_seen = Arc::clone(&seen); + tokio::spawn(async move { + loop { + let Ok((stream, _)) = listener.accept().await else { + return; + }; + let seen = Arc::clone(&server_seen); + tokio::spawn(async move { + let service = hyper::service::service_fn(move |request: Request| { + let seen = Arc::clone(&seen); + async move { + let header = |name: &str| { + request + .headers() + .get(name) + .and_then(|value| value.to_str().ok()) + .unwrap_or_default() + .to_string() + }; + if request.uri().path() == "/mcp" { + seen.requests.fetch_add(1, Ordering::SeqCst); + seen.authorization + .lock() + .unwrap() + .push(header("authorization")); + seen.workspace + .lock() + .unwrap() + .push(header("x-openshell-workspace")); + } + let status = match answer { + Answer::FreshTokenOnly + if header("authorization") == "Bearer fresh-token" => + { + StatusCode::OK + } + Answer::FreshTokenOnly => StatusCode::UNAUTHORIZED, + Answer::Always(status) => status, + }; + let mut response = Response::new(Full::new(Bytes::from_static(b"{}"))); + *response.status_mut() = status; + Ok::<_, Infallible>(response) + } + }); + let _ = hyper::server::conn::http2::Builder::new(TokioExecutor::new()) + .serve_connection(TokioIo::new(stream), service) + .await; + }); + } + }); + (endpoint, seen) +} + +/// Hands out `fresh-token` and counts how often it is asked. +struct CountingRefresher { + calls: Arc, +} + +#[async_trait::async_trait] +impl Refresh for CountingRefresher { + async fn refresh(&self) -> Result { + self.calls.fetch_add(1, Ordering::SeqCst); + Ok(RefreshedToken::new("fresh-token").with_expires_at(now() + 3600)) + } +} + +fn now() -> u64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_secs() +} + +async fn client(endpoint: &str, token_expires_at: u64) -> (OpenShellClient, Arc) { + let calls = Arc::new(AtomicU32::new(0)); + let mut config = ClientConfig::new(endpoint); + config.auth = Some(AuthConfig::Oidc { + token: "stale-token".to_string(), + expires_at: Some(token_expires_at), + refresh: Some(Arc::new(CountingRefresher { + calls: Arc::clone(&calls), + })), + }); + (OpenShellClient::connect(config).await.unwrap(), calls) +} + +#[tokio::test] +async fn a_401_is_retried_once_after_a_refresh() { + let (endpoint, seen) = start(Answer::FreshTokenOnly).await; + let (client, refreshes) = client(&endpoint, now() + 3600).await; + + let reply = client.post_mcp(b"{}", "team").await.unwrap(); + + assert_eq!(reply.status, StatusCode::OK); + assert_eq!(seen.requests.load(Ordering::SeqCst), 2); + assert_eq!(refreshes.load(Ordering::SeqCst), 1); + assert_eq!( + *seen.authorization.lock().unwrap(), + ["Bearer stale-token", "Bearer fresh-token"] + ); + assert_eq!(*seen.workspace.lock().unwrap(), ["team", "team"]); +} + +#[tokio::test] +async fn a_token_near_expiry_is_refreshed_before_sending() { + let (endpoint, seen) = start(Answer::FreshTokenOnly).await; + let (client, refreshes) = client(&endpoint, now()).await; + + let reply = client.post_mcp(b"{}", "default").await.unwrap(); + + assert_eq!(reply.status, StatusCode::OK); + assert_eq!(seen.requests.load(Ordering::SeqCst), 1); + assert_eq!(refreshes.load(Ordering::SeqCst), 1); +} + +#[tokio::test] +async fn only_one_retry_and_only_after_a_401() { + for (answer, requests) in [ + (StatusCode::UNAUTHORIZED, 2), + (StatusCode::INTERNAL_SERVER_ERROR, 1), + (StatusCode::BAD_GATEWAY, 1), + (StatusCode::FORBIDDEN, 1), + ] { + let (endpoint, seen) = start(Answer::Always(answer)).await; + let (client, _) = client(&endpoint, now() + 3600).await; + + let reply = client.post_mcp(b"{}", "default").await.unwrap(); + + assert_eq!(reply.status, answer); + assert_eq!(seen.requests.load(Ordering::SeqCst), requests, "{answer}"); + } +} diff --git a/crates/openshell-server/Cargo.toml b/crates/openshell-server/Cargo.toml index cbc45122e4..5084d23e48 100644 --- a/crates/openshell-server/Cargo.toml +++ b/crates/openshell-server/Cargo.toml @@ -145,6 +145,7 @@ tokio = { workspace = true, features = ["test-util"] } openshell-providers = { path = "../openshell-providers", features = ["example-profiles"] } openshell-ocsf = { path = "../openshell-ocsf", features = ["test-support"] } openshell-ocsf-validate = { path = "../openshell-ocsf-validate" } +jsonschema = { workspace = true } base64 = { workspace = true } hyper-rustls = { version = "0.27", default-features = false, features = ["native-tokio", "http1", "tls12", "logging"] } rcgen = { workspace = true } diff --git a/crates/openshell-server/src/auth/audit.rs b/crates/openshell-server/src/auth/audit.rs index 7bc2993b92..725c5a6a5c 100644 --- a/crates/openshell-server/src/auth/audit.rs +++ b/crates/openshell-server/src/auth/audit.rs @@ -748,6 +748,74 @@ pub fn deny(principal: &Principal, denial: AuthzDenial<'_>, message: impl Into { + Allowed, + /// Refused by policy or by the request itself, with the tool's error code. + Refused(&'a str), + /// Allowed, but failed for an internal or transient reason. + Failed(&'a str), +} + +pub fn emit_mcp_tool_call( + origin: &RequestOrigin, + principal: &Principal, + tool: &str, + outcome: McpOutcome<'_>, + details: &[(&str, String)], +) { + ocsf_emit!(mcp_tool_call_event( + origin, principal, tool, outcome, details + )); +} + +pub fn mcp_tool_call_event( + origin: &RequestOrigin, + principal: &Principal, + tool: &str, + outcome: McpOutcome<'_>, + details: &[(&str, String)], +) -> openshell_ocsf::OcsfEvent { + let ctx = crate::gateway_ocsf::context("", ""); + let mut builder = ApiActivityBuilder::new(&ctx, tool) + .actor_user(principal_user(principal)) + .src_endpoint(origin.source.map_or_else( + || Endpoint::from_name("unknown"), + ConnectionSource::endpoint, + )) + .api_service(Service::new("mcp")) + .http_request(post("/mcp")); + for (key, value) in details { + builder = builder.unmapped(key, value.clone()); + } + let builder = match outcome { + McpOutcome::Allowed => builder + .action(ActionId::Allowed) + .disposition(DispositionId::Allowed) + .severity(SeverityId::Informational) + .status(StatusId::Success) + .message(format!("mcp tool call {tool}: allowed")), + McpOutcome::Refused(code) => builder + .action(ActionId::Denied) + .disposition(DispositionId::Blocked) + .severity(SeverityId::Low) + .status(StatusId::Failure) + .status_detail(code) + .message(format!("mcp tool call {tool}: refused ({code})")), + McpOutcome::Failed(code) => builder + .action(ActionId::Allowed) + .disposition(DispositionId::Unknown) + .severity(SeverityId::Low) + .status(StatusId::Failure) + .status_detail(code) + .message(format!("mcp tool call {tool}: failed ({code})")), + }; + builder.build() +} + /// Emit an API Activity denial for a gRPC request to `path`, paired with a /// Detection Finding when a sandbox principal crossed its boundary. pub fn emit_authorization_denial_for( diff --git a/crates/openshell-server/src/auth/workspace_authz.rs b/crates/openshell-server/src/auth/workspace_authz.rs index 035d8aa354..9dd55c377e 100644 --- a/crates/openshell-server/src/auth/workspace_authz.rs +++ b/crates/openshell-server/src/auth/workspace_authz.rs @@ -216,6 +216,26 @@ pub async fn authorize_workspace( } } +/// Whether `subject` is a member of `workspace` with at least `min_role`. +/// Platform admins are not recognized here: only the subject is known. +pub async fn subject_has_workspace_role( + store: &Store, + workspace: &str, + subject: &str, + min_role: MinWorkspaceRole, +) -> Result { + let member = store + .get_message_by_name::(workspace, subject) + .await + .map_err(|e| Status::internal(format!("membership lookup failed: {e}")))?; + Ok(member.is_some_and(|member| { + role_satisfies( + ProtoWorkspaceRole::try_from(member.role).unwrap_or(ProtoWorkspaceRole::Unspecified), + min_role, + ) + })) +} + /// Used by `ExecSandbox`, `ForwardTcp`, `WatchSandbox`, `CreateSshSession` — these /// RPCs identify a sandbox by its canonical name within an explicit workspace. /// User requests authorize that workspace before lookup; sandbox principals diff --git a/crates/openshell-server/src/cli.rs b/crates/openshell-server/src/cli.rs index c2aedba17d..4fa0633883 100644 --- a/crates/openshell-server/src/cli.rs +++ b/crates/openshell-server/src/cli.rs @@ -894,6 +894,24 @@ fn assemble_server_config( config.provisioning_repair_window_seconds = window; } + if let Some(enabled) = file + .as_ref() + .and_then(|f| f.openshell.gateway.experimental_enable_child_sandboxes) + { + config.enable_child_sandboxes = enabled; + } + if let Some(limit) = file + .as_ref() + .and_then(|f| f.openshell.gateway.experimental_max_concurrent_children) + { + if limit > 1000 { + return Err(miette::miette!( + "experimental_max_concurrent_children must be between 0 and 1000" + )); + } + config.max_concurrent_children = limit; + } + if let Some(issuer) = args.oidc_issuer.clone() { config = config.with_oidc(openshell_core::OidcConfig { issuer, @@ -6059,6 +6077,86 @@ mem_mib = "not-a-number" }); } + #[test] + fn server_config_reads_child_sandbox_settings() { + let state = tempfile::tempdir().unwrap(); + let tls = tempfile::tempdir().unwrap(); + Environment::new() + .set("XDG_STATE_HOME", state.path().to_str().unwrap()) + .set("OPENSHELL_LOCAL_TLS_DIR", tls.path().to_str().unwrap()) + .run(|| { + let state = std::path::PathBuf::from(std::env::var_os("XDG_STATE_HOME").unwrap()); + let config_path = state.join("gateway.toml"); + let cases = [ + ("", false, 10), + ("experimental_enable_child_sandboxes = true\n", true, 10), + ("experimental_max_concurrent_children = 0\n", false, 0), + ( + "experimental_enable_child_sandboxes = true\nexperimental_max_concurrent_children = 1000\n", + true, + 1000, + ), + ]; + for (settings, enabled, limit) in cases { + std::fs::write( + &config_path, + format!("[openshell]\nversion = 2\n[openshell.gateway]\n{settings}"), + ) + .unwrap(); + let (mut args, matches) = parse_with_args(&[ + "openshell-gateway", + "--config", + config_path.to_str().unwrap(), + "--db-url", + "sqlite::memory:", + "--compute-driver", + "podman", + "--disable-tls", + ]); + let prepared = super::prepare_server_config(&mut args, &matches) + .expect("server config is prepared"); + assert_eq!(prepared.config.enable_child_sandboxes, enabled, "{settings}"); + assert_eq!(prepared.config.max_concurrent_children, limit, "{settings}"); + } + }); + } + + #[test] + fn server_config_rejects_too_many_concurrent_children() { + let state = tempfile::tempdir().unwrap(); + let tls = tempfile::tempdir().unwrap(); + Environment::new() + .set("XDG_STATE_HOME", state.path().to_str().unwrap()) + .set("OPENSHELL_LOCAL_TLS_DIR", tls.path().to_str().unwrap()) + .run(|| { + let state = std::path::PathBuf::from(std::env::var_os("XDG_STATE_HOME").unwrap()); + let config_path = state.join("gateway.toml"); + std::fs::write( + &config_path, + "[openshell]\nversion = 2\n[openshell.gateway]\nexperimental_max_concurrent_children = 1001\n", + ) + .unwrap(); + let (mut args, matches) = parse_with_args(&[ + "openshell-gateway", + "--config", + config_path.to_str().unwrap(), + "--db-url", + "sqlite::memory:", + "--compute-driver", + "podman", + "--disable-tls", + ]); + let Err(error) = super::prepare_server_config(&mut args, &matches) else { + panic!("a limit above 1000 must be rejected"); + }; + assert!( + error + .to_string() + .contains("experimental_max_concurrent_children must be between 0 and 1000") + ); + }); + } + #[test] fn explicit_launch_signing_config_ignores_partial_local_bundle() { let directory = tempfile::tempdir().unwrap(); diff --git a/crates/openshell-server/src/compute/image_update.rs b/crates/openshell-server/src/compute/image_update.rs index 58bee31e09..ca0abb47c9 100644 --- a/crates/openshell-server/src/compute/image_update.rs +++ b/crates/openshell-server/src/compute/image_update.rs @@ -429,6 +429,16 @@ impl ComputeRuntime { &self, id: &str, now: tokio::time::Instant, + ) -> Result<(), Status> { + // The recovery future carries full persisted sandbox records; keep it + // off the caller's stack (clippy::large_futures). + Box::pin(self.recover_one_sandbox_update_at_unboxed(id, now)).await + } + + async fn recover_one_sandbox_update_at_unboxed( + &self, + id: &str, + now: tokio::time::Instant, ) -> Result<(), Status> { let Some(_gate) = self.lifecycle_gates.try_lock_for(id) else { return Ok(()); diff --git a/crates/openshell-server/src/compute/mod.rs b/crates/openshell-server/src/compute/mod.rs index 8b2adb5570..6ced223ef5 100644 --- a/crates/openshell-server/src/compute/mod.rs +++ b/crates/openshell-server/src/compute/mod.rs @@ -12,7 +12,7 @@ mod provisioning_operation; pub mod rootfs_tar; pub use mutation_guard::MutationScope; -use mutation_guard::{LocalMutationGuard, LocalMutationLocks, MutationGuard}; +use mutation_guard::{LocalMutationGuard, LocalMutationLocks, MutationGuard, SandboxDeleteGuard}; use crate::grpc::policy::SANDBOX_SETTINGS_OBJECT_TYPE; use crate::otel_tracing::TraceContextInterceptor; @@ -1364,6 +1364,9 @@ pub struct ComputeRuntime { image_preparation_timeout_seconds: u32, provisioning_repair_window_ms: i64, sandbox_updates_enabled: bool, + /// `experimental_enable_child_sandboxes`. Off, a root delete skips the + /// child count, which reads every sandbox in the workspace. + child_sandboxes_enabled: bool, update_recovery_sweep: Arc, update_recovery_backoff: Arc>>, store: Arc, @@ -1489,6 +1492,7 @@ impl ComputeRuntime { image_preparation_timeout_seconds: 1800, provisioning_repair_window_ms: 300_000, sandbox_updates_enabled: false, + child_sandboxes_enabled: false, update_recovery_sweep: Arc::new(tokio::sync::Semaphore::new(1)), update_recovery_backoff: Arc::default(), store, @@ -1765,6 +1769,11 @@ impl ComputeRuntime { }) } + pub(crate) fn with_child_sandboxes(mut self, enabled: bool) -> Self { + self.child_sandboxes_enabled = enabled; + self + } + /// Validate the budget once at startup. Persisted attempts keep their /// original deadline even if the operator changes this value on restart. pub(crate) fn with_image_preparation_timeout(mut self, seconds: u32) -> Result { @@ -2730,9 +2739,13 @@ impl ComputeRuntime { Ok(settled) } Err(err) => { - if let Some(terminal) = self - .recover_failed_lifecycle(&lifecycle_guard, &transition, &previous, true) - .await + if let Some(terminal) = Box::pin(self.recover_failed_lifecycle( + &lifecycle_guard, + &transition, + &previous, + true, + )) + .await { return Ok(terminal); } @@ -3213,9 +3226,13 @@ impl ComputeRuntime { settled, }) => { provisioning_operation::ensure_current_result(&settled, &settled)?; - let _ = self - .recover_failed_lifecycle(&lifecycle_guard, &settled, &previous, false) - .await; + let _ = Box::pin(self.recover_failed_lifecycle( + &lifecycle_guard, + &settled, + &previous, + false, + )) + .await; Err(Status::new( err.code(), format!("start sandbox failed: {}", err.message()), @@ -3882,7 +3899,11 @@ impl ComputeRuntime { preconditions: SandboxDeletePreconditions, ) -> Result { let delete_guard = self.lifecycle_gates.lock_for(&target.sandbox_id).await; - let sandbox_guard = self.lock_sandbox_for_lifecycle(&delete_guard).await; + let sandbox_guard = Box::pin(self.lock_sandbox_for_delete(&delete_guard)) + .await + .map_err(|err| { + crate::grpc::persistence_error_to_status(err, "acquire sandbox delete lock") + })?; // There is no await between acquiring the initial guards and spawning // the worker. From this commitment point onward, request cancellation @@ -3916,7 +3937,7 @@ impl ComputeRuntime { target: SandboxDeleteTarget, preconditions: SandboxDeletePreconditions, delete_guard: SandboxLifecycleGuard, - guard: LocalMutationGuard, + guard: SandboxDeleteGuard, ) -> Result { let current = self .store @@ -3955,6 +3976,19 @@ impl ComputeRuntime { "sandbox resource version changed before delete mutation", )); } + // Checked under the root's mutation guard, which a child create on any + // replica also takes on its parent, so a child cannot be added between + // this check and the delete. A child whose delete has started blocks + // too: until it finishes its compute resources may still run, and the + // root must not leave it without a parent. + if self.child_sandboxes_enabled && current.parent.is_none() { + let children = + count_children(&self.store, current.object_workspace(), current.object_id()) + .await?; + if children.total() > 0 { + return Err(root_has_children(&target.sandbox_name, children)); + } + } // `Started` carries both sides of the CAS transition: the durable // `Deleting` row used to fence recovery, and the prior row used only @@ -4803,6 +4837,27 @@ impl ComputeRuntime { failed += 1; continue; } + // A child whose parent record is gone is never started again; the + // startup child sync stops it. Read by id; a store error only + // skips the check, so a brief outage cannot strand every child. + if let Some(parent) = sandbox.parent.as_ref() { + match self.store.get_message::(&parent.id).await { + Ok(None) => { + warn!( + sandbox_id, + parent_id = %parent.id, + "Not starting child sandbox whose parent no longer exists" + ); + continue; + } + Ok(Some(_)) => {} + Err(err) => warn!( + sandbox_id, + error = %err, + "Failed to check child sandbox's parent during gateway startup" + ), + } + } if is_automatic_restart_transition(&sandbox) { // The restart loop resumes both scheduled and claimed // attempts. It always stops the old runtime before starting @@ -8840,6 +8895,74 @@ fn rewrite_user_facing_conditions(status: &mut Option, spec: Opti } } +/// A parent's children, split by whether their delete has started. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct ChildCount { + pub live: usize, + pub being_deleted: usize, +} + +impl ChildCount { + pub fn total(self) -> usize { + self.live + self.being_deleted + } +} + +/// Why a root with children cannot be deleted yet. +fn root_has_children(name: &str, children: ChildCount) -> Status { + let noun = |count: usize| { + if count == 1 { + "child sandbox" + } else { + "child sandboxes" + } + }; + if children.live > 0 { + return Status::failed_precondition(format!( + "sandbox '{name}' has {} {}; delete them first", + children.live, + noun(children.live) + )); + } + Status::failed_precondition(format!( + "sandbox '{name}' has {} {} still being deleted; try again once they are gone", + children.being_deleted, + noun(children.being_deleted) + )) +} + +/// Whether a sandbox's delete has started. It keeps its record, and its +/// compute resources may still run, until the driver finishes. +pub fn is_being_deleted(sandbox: &Sandbox) -> bool { + sandbox.phase() == SandboxPhase::Deleting as i32 +} + +/// Count a parent's children by scanning its workspace. +pub async fn count_children( + store: &Store, + workspace: &str, + parent_id: &str, +) -> Result { + let sandboxes = store + .collect_messages::(ObjectListQuery::Workspace(workspace)) + .await + .map_err(|e| Status::internal(format!("list sandboxes failed: {e}")))?; + let mut count = ChildCount::default(); + for sandbox in sandboxes.iter().filter(|sandbox| { + sandbox + .parent + .as_ref() + .is_some_and(|parent| parent.id == parent_id) + }) { + if is_being_deleted(sandbox) { + count.being_deleted += 1; + } else { + count.live += 1; + } + } + Ok(count) +} + /// Phases for which a sandbox should have a running compute resource. /// Terminal and lifecycle-controller-owned phases are intentionally excluded: /// they must not be silently revived or bypass a persisted transition/backoff. @@ -9380,6 +9503,7 @@ pub fn new_test_runtime_with_driver( image_preparation_timeout_seconds: 1800, provisioning_repair_window_ms: 300_000, sandbox_updates_enabled: false, + child_sandboxes_enabled: false, update_recovery_sweep: Arc::new(tokio::sync::Semaphore::new(1)), update_recovery_backoff: Arc::default(), store, @@ -10925,6 +11049,7 @@ mod tests { image_preparation_timeout_seconds: 1800, provisioning_repair_window_ms: 300_000, sandbox_updates_enabled: false, + child_sandboxes_enabled: false, update_recovery_sweep: Arc::new(Semaphore::new(1)), update_recovery_backoff: Arc::default(), store, diff --git a/crates/openshell-server/src/compute/mutation_guard.rs b/crates/openshell-server/src/compute/mutation_guard.rs index 40197ee568..20f042d34b 100644 --- a/crates/openshell-server/src/compute/mutation_guard.rs +++ b/crates/openshell-server/src/compute/mutation_guard.rs @@ -52,6 +52,13 @@ pub enum MutationScope<'a> { workspace: &'a str, sandbox_id: &'a str, }, + /// Creation of a child sandbox. Also excludes other writers of the parent, + /// so concurrent creates under one parent count its children in turn. + ChildSandbox { + workspace: &'a str, + sandbox_id: &'a str, + parent_id: &'a str, + }, } impl<'a> MutationScope<'a> { @@ -83,6 +90,7 @@ impl<'a> MutationScope<'a> { /// - `Sandbox`: S(global) S(workspace) X(sandbox). A legacy sandbox with /// an empty workspace locks the default workspace, where its providers /// resolve. + /// - `ChildSandbox`: S(global) S(workspace) X(parent) X(sandbox). pub(crate) fn lock_set(&self) -> MutationLockSet { let mut set = MutationLockSet::default(); match *self { @@ -110,6 +118,19 @@ impl<'a> MutationScope<'a> { ); set.insert(MutationLockKey::Sandbox(sandbox_id), LockMode::Exclusive); } + Self::ChildSandbox { + workspace, + sandbox_id, + parent_id, + } => { + set.insert(MutationLockKey::Global, LockMode::Shared); + set.insert( + MutationLockKey::Workspace(sandbox_workspace_key(workspace)), + LockMode::Shared, + ); + set.insert(MutationLockKey::Sandbox(parent_id), LockMode::Exclusive); + set.insert(MutationLockKey::Sandbox(sandbox_id), LockMode::Exclusive); + } } set } @@ -120,7 +141,7 @@ impl<'a> MutationScope<'a> { Self::Global => LockScope::Global, Self::Workspace(workspace) if workspace.is_empty() => LockScope::Global, Self::Workspace(_) => LockScope::Workspace, - Self::Sandbox { .. } => LockScope::Sandbox, + Self::Sandbox { .. } | Self::ChildSandbox { .. } => LockScope::Sandbox, } } } @@ -287,6 +308,18 @@ pub struct MutationGuard { _local: LocalMutationGuard, } +/// Lock held by a sandbox delete until it marks the sandbox `Deleting`. +#[must_use = "dropping the guard releases the sandbox's delete lock"] +pub enum SandboxDeleteGuard { + /// A root's mutation guard, which excludes child creates on every replica. + Root { + _guard: MutationGuard, + }, + Local { + _guard: LocalMutationGuard, + }, +} + /// Times one [`MutationGuard`] from acquisition to release. Guarded work has /// no time limit of its own, so a hold longer than the wait timeout means /// conflicting acquisitions may have timed out behind it. @@ -429,6 +462,25 @@ impl ComputeRuntime { Ok((lifecycle_guard, mutation_guard)) } + /// Lifecycle gate, then the child-create mutation guard, for a new child + /// of `parent_id`. Callers must re-read the parent after locking. + pub(crate) async fn child_sandbox_create_guards( + &self, + workspace: &str, + sandbox_id: &str, + parent_id: &str, + ) -> PersistenceResult<(SandboxLifecycleGuard, MutationGuard)> { + let lifecycle_guard = self.lifecycle_gates.lock_for(sandbox_id).await; + let mutation_guard = self + .mutation_guard(MutationScope::ChildSandbox { + workspace, + sandbox_id, + parent_id, + }) + .await?; + Ok((lifecycle_guard, mutation_guard)) + } + /// Local S(global) X(sandbox) for code that already holds the sandbox's /// lifecycle gate. The guard parameter documents and enforces the /// lifecycle-gate -> mutation-lock order. @@ -439,10 +491,49 @@ impl ComputeRuntime { self.lock_sandbox_local(&lifecycle_guard.sandbox_id).await } + /// Lock for a sandbox delete, for code that holds its lifecycle gate. + /// + /// A root's delete checks that the root has no children, which a child + /// create on any replica can change, so it takes the sandbox's mutation + /// guard: on `PostgreSQL` the same database lock a child create takes on + /// its parent. Other sandboxes take the local lock of + /// [`Self::lock_sandbox_local`]. One read before locking picks the lock; + /// a sandbox's parent and workspace never change. + /// + /// With child sandboxes off no sandbox has children, so every delete + /// takes the local lock and nothing is read. + pub(super) async fn lock_sandbox_for_delete( + &self, + lifecycle_guard: &SandboxLifecycleGuard, + ) -> PersistenceResult { + if !self.child_sandboxes_enabled { + return Ok(SandboxDeleteGuard::Local { + _guard: self.lock_sandbox_for_lifecycle(lifecycle_guard).await, + }); + } + let sandbox_id = &lifecycle_guard.sandbox_id; + let sandbox = self.store.get_message::(sandbox_id).await?; + match sandbox { + Some(sandbox) if sandbox.parent.is_none() => { + let guard = self + .mutation_guard(MutationScope::sandbox( + sandbox.object_workspace(), + sandbox_id, + )) + .await?; + Ok(SandboxDeleteGuard::Root { _guard: guard }) + } + _ => Ok(SandboxDeleteGuard::Local { + _guard: self.lock_sandbox_for_lifecycle(lifecycle_guard).await, + }), + } + } + /// Local S(global) X(sandbox) for lifecycle, driver-watch, and reconcile /// paths. They write only this sandbox and its owned records and rely on /// compare-and-swap across replicas, so they take no database lock and - /// never exclude another sandbox or a provider writer. + /// never exclude another sandbox or a provider writer. A root's delete is + /// the exception; see [`Self::lock_sandbox_for_delete`]. pub(super) async fn lock_sandbox_local(&self, sandbox_id: &str) -> LocalMutationGuard { self.mutation_locks .acquire(&MutationLockSet::sandbox_lifecycle(sandbox_id)) @@ -1545,6 +1636,108 @@ mod tests { schema.drop_schema().await; } + /// With child sandboxes off a delete takes only the sandbox's local lock, + /// as it did before the feature, so a workspace writer does not delay it. + #[tokio::test] + async fn a_root_delete_waits_for_a_workspace_writer_only_with_child_sandboxes_on() { + for (enabled, workspace, lead) in [ + (false, "team-off", "lead-off"), + (true, "team-on", "lead-on"), + ] { + let runtime = test_runtime().await.with_child_sandboxes(enabled); + runtime + .store + .put_message(&stored_sandbox(lead, workspace)) + .await + .expect("seed the root"); + let writer = runtime + .mutation_guard(MutationScope::Workspace(workspace)) + .await + .expect("workspace writer"); + let mut delete = { + let runtime = runtime.clone(); + tokio::spawn(async move { runtime.delete_sandbox(workspace, lead).await }) + }; + if enabled { + assert_blocked(&mut delete, "a root delete with child sandboxes on").await; + } + let writer = (!enabled).then_some(writer); + assert_proceeds(delete, "the root delete") + .await + .expect("the root is deleted"); + drop(writer); + } + } + + #[tokio::test] + #[ignore = "requires a disposable PostgreSQL database in OPENSHELL_TEST_POSTGRES_URL; run mise run test:rust:postgres"] + async fn postgres_root_delete_waits_for_a_child_create_on_another_replica() { + let schema = TestSchema::create("rootdel").await; + let replica_a = postgres_runtime(&schema).await.with_child_sandboxes(true); + let replica_b = postgres_runtime(&schema).await.with_child_sandboxes(true); + let lead_id = format!("lead-{}", Uuid::new_v4()); + let worker_id = format!("worker-{}", Uuid::new_v4()); + replica_a + .store + .put_message(&stored_sandbox(&lead_id, DEFAULT_WORKSPACE_NAME)) + .await + .expect("seed the root"); + + // Replica A is creating a child of the root. + let create_guards = replica_a + .child_sandbox_create_guards(DEFAULT_WORKSPACE_NAME, &worker_id, &lead_id) + .await + .expect("child create guards on replica A"); + let mut delete = { + let replica_b = replica_b.clone(); + let lead_id = lead_id.clone(); + tokio::spawn(async move { + replica_b + .delete_sandbox(DEFAULT_WORKSPACE_NAME, &lead_id) + .await + }) + }; + assert!( + tokio::time::timeout(Duration::from_millis(200), &mut delete) + .await + .is_err(), + "the root delete should wait for the child create on the other replica" + ); + + let mut worker = stored_sandbox(&worker_id, DEFAULT_WORKSPACE_NAME); + worker.parent = Some(openshell_core::proto::SandboxParent { + name: lead_id.clone(), + id: lead_id.clone(), + }); + replica_a + .store + .put_message(&worker) + .await + .expect("store the new child"); + drop(create_guards); + + let err = tokio::time::timeout(PROCEEDS_WITHIN, delete) + .await + .expect("the root delete should proceed after release") + .expect("delete task") + .expect_err("the root now has a child"); + assert_eq!(err.code(), tonic::Code::FailedPrecondition, "{err}"); + let lead = replica_b + .store + .get_message::(&lead_id) + .await + .expect("read the root") + .expect("the refused root still exists"); + assert!( + !crate::compute::is_being_deleted(&lead), + "a refused delete must not mark the root as deleting" + ); + + replica_a.store.close().await; + replica_b.store.close().await; + schema.drop_schema().await; + } + /// Measures lock waits in a paced reconnect burst into one replica: one /// session every 12 ms (1000 sessions spread over 12 s), all into one /// receiving replica with the production lock pool. Run it with diff --git a/crates/openshell-server/src/config_delivery/mod.rs b/crates/openshell-server/src/config_delivery/mod.rs index 335c1a0b09..641e328e2b 100644 --- a/crates/openshell-server/src/config_delivery/mod.rs +++ b/crates/openshell-server/src/config_delivery/mod.rs @@ -1497,6 +1497,121 @@ mod tests { assert!(!rejected.configuration_error.is_empty()); } + /// Store `version` of a policy for `sandbox_id` as loaded. + async fn put_loaded_policy(state: &ServerState, sandbox_id: &str, version: i64, host: &str) { + use crate::policy_store::PolicyStoreExt as _; + use prost::Message as _; + + let mut policy = openshell_policy::restrictive_default_policy(); + policy.network_policies.insert( + "api".to_string(), + openshell_core::proto::NetworkPolicyRule { + name: "api".to_string(), + endpoints: vec![openshell_core::proto::NetworkEndpoint { + host: host.to_string(), + port: 443, + ..Default::default() + }], + ..Default::default() + }, + ); + state + .store + .put_policy_revision( + &uuid::Uuid::new_v4().to_string(), + sandbox_id, + "default", + version, + &policy.encode_to_vec(), + &crate::grpc::policy::deterministic_policy_hash(&policy), + ) + .await + .unwrap(); + state + .store + .update_policy_status(sandbox_id, version, "loaded", None, Some(1)) + .await + .unwrap(); + let mut sandbox = state + .store + .get_message::(sandbox_id) + .await + .unwrap() + .unwrap(); + sandbox.set_current_policy_version(u32::try_from(version).unwrap()); + state.store.put_message(&sandbox).await.unwrap(); + } + + /// Receive the next configuration update and acknowledge it, as a + /// supervisor does before it is sent another. + async fn next_applied_config( + harness: &mut SupervisorStreamHarness, + what: &str, + ) -> SandboxConfigSnapshot { + let message = next_update(harness, Duration::from_secs(5)) + .await + .unwrap_or_else(|| panic!("{what}")); + let Some(gateway_message::Payload::ConfigUpdate(update)) = message.payload else { + panic!("expected a configuration update: {what}"); + }; + harness + .outbound + .send(openshell_core::proto::SupervisorMessage { + payload: Some( + openshell_core::proto::supervisor_message::Payload::ConfigUpdateResult( + session::applied_result(&update), + ), + ), + }) + .await + .unwrap(); + update.sandbox_config.expect("sandbox configuration") + } + + #[tokio::test] + async fn a_child_sync_pushes_the_new_copy_to_a_connected_child() { + let mut state = push_state().await; + let inner = Arc::get_mut(&mut state).unwrap(); + inner.config.enable_child_sandboxes = true; + inner.compute = inner.compute.clone().with_child_sandboxes(true); + put_sandbox(&state, "lead", &[]).await; + put_loaded_policy(&state, "lead", 1, "v1.example.com").await; + let worker = Sandbox { + metadata: Some(ObjectMeta { + id: "worker".into(), + name: "worker".into(), + workspace: "default".into(), + ..Default::default() + }), + spec: Some(SandboxSpec::default()), + parent: Some(openshell_core::proto::SandboxParent { + name: "lead".into(), + id: "lead".into(), + }), + ..Default::default() + }; + state.store.put_message(&worker).await.unwrap(); + let (mut harness, _) = accepted_session(&state, "worker").await; + let allows = |config: SandboxConfigSnapshot, host: &str| { + config.configuration_admitted + && config + .policy + .expect("policy") + .network_policies + .values() + .any(|rule| rule.endpoints.iter().any(|e| e.host == host)) + }; + + crate::grpc::sync_all_children(&state).await.unwrap(); + let first = next_applied_config(&mut harness, "update after the first copy").await; + assert!(allows(first, "v1.example.com")); + + put_loaded_policy(&state, "lead", 2, "v2.example.com").await; + crate::grpc::sync_all_children(&state).await.unwrap(); + let second = next_applied_config(&mut harness, "update after the second copy").await; + assert!(allows(second, "v2.example.com")); + } + #[tokio::test] async fn provider_change_reaches_only_attached_sessions() { let state = push_state().await; diff --git a/crates/openshell-server/src/config_delivery/session.rs b/crates/openshell-server/src/config_delivery/session.rs index 3441fdfac4..fde292d8bb 100644 --- a/crates/openshell-server/src/config_delivery/session.rs +++ b/crates/openshell-server/src/config_delivery/session.rs @@ -333,6 +333,16 @@ impl SupervisorSessionRegistry { }); } + /// Whether an update, the bootstrap included, still waits for its + /// result to be recorded. + #[cfg(test)] + pub(crate) fn config_update_in_flight(&self, sandbox_id: &str, session_id: &str) -> bool { + self.with_config_session(sandbox_id, session_id, |session| { + session.is_some_and(|session| session.in_flight.is_some()) + }) + .unwrap_or(false) + } + fn complete_config_update( &self, sandbox_id: &str, diff --git a/crates/openshell-server/src/config_file/mod.rs b/crates/openshell-server/src/config_file/mod.rs index 5c2bdf606e..201cf57737 100644 --- a/crates/openshell-server/src/config_file/mod.rs +++ b/crates/openshell-server/src/config_file/mod.rs @@ -192,6 +192,17 @@ pub struct GatewayFileSection { #[serde(default, skip_serializing_if = "Option::is_none")] pub config_delivery_mode: Option, + // ── Child sandboxes ────────────────────────────────────────────────── + /// Allow creating child sandboxes under a root sandbox. Experimental; + /// disabled when omitted. Affects only new children. + #[serde(default)] + pub experimental_enable_child_sandboxes: Option, + /// Most children one parent may have at once, counting every child that + /// exists. Experimental. Omit for the default of 10; 0 allows none; at + /// most 1000. + #[serde(default)] + pub experimental_max_concurrent_children: Option, + // ── Service routing ────────────────────────────────────────────────── /// Publish gateway URLs and forward application requests. Defaults to true. #[serde(default)] diff --git a/crates/openshell-server/src/grpc/mod.rs b/crates/openshell-server/src/grpc/mod.rs index 5bfb592196..ecef85b8ed 100644 --- a/crates/openshell-server/src/grpc/mod.rs +++ b/crates/openshell-server/src/grpc/mod.rs @@ -14,6 +14,7 @@ mod sandbox; pub mod secret; pub mod supervisor_host; pub use sandbox::mint_persisted_authentication; +pub use sandbox::sync_all_children; mod service; pub mod service_advertisement; pub mod service_discovery; diff --git a/crates/openshell-server/src/grpc/policy.rs b/crates/openshell-server/src/grpc/policy.rs index b9d5fa8fff..b58961f1ee 100644 --- a/crates/openshell-server/src/grpc/policy.rs +++ b/crates/openshell-server/src/grpc/policy.rs @@ -1902,6 +1902,7 @@ async fn auto_approve_chunk( } }; crate::config_delivery::publish_sandbox(state, sandbox_id); + sync_children_after_commit(state, sandbox_id).await; let chunk_summary = summarize_draft_chunk_rule(&chunk)?; let now_ms = current_time_ms(); @@ -2866,15 +2867,25 @@ pub fn unadmitted_sandbox_config( .and_then(|status| status.configuration_admission.as_ref()) .map_or_else(String::new, |admission| admission.instance_id.clone()), workspace: sandbox.object_workspace().to_string(), - policy_validation_failure_mode: state - .config - .policy_validation_failure_mode - .as_str() - .to_string(), + policy_validation_failure_mode: policy_failure_mode(state, sandbox).as_str().to_string(), ..Default::default() } } +/// The failure mode a sandbox's supervisor applies when it rejects a policy. +/// Children always fail closed: a child keeping its previous copy could keep +/// access its parent just lost. +fn policy_failure_mode( + state: &ServerState, + sandbox: &Sandbox, +) -> openshell_core::PolicyValidationFailureMode { + if sandbox.parent.is_some() { + openshell_core::PolicyValidationFailureMode::FailClosed + } else { + state.config.policy_validation_failure_mode + } +} + async fn handle_get_sandbox_config_inner( state: &Arc, request: Request, @@ -3106,7 +3117,7 @@ async fn build_sandbox_config_snapshot_with_sources( &settings, policy_source, &supervisor_middleware_services, - state.config.policy_validation_failure_mode, + policy_failure_mode(state, sandbox), state.extension_jwt_issuer.is_some(), ); if let Some(policy) = policy.as_ref() { @@ -3163,11 +3174,7 @@ async fn build_sandbox_config_snapshot_with_sources( provider_env_revision, supervisor_middleware_services, workspace, - policy_validation_failure_mode: state - .config - .policy_validation_failure_mode - .as_str() - .to_string(), + policy_validation_failure_mode: policy_failure_mode(state, sandbox).as_str().to_string(), extension_authentication_enabled: state.extension_jwt_issuer.is_some(), provider_attachment_epoch: sandbox .spec @@ -4273,6 +4280,47 @@ pub(super) async fn handle_update_config( result } +/// Why a child sandbox's own policy cannot be changed. +const CHILD_POLICY_WRITE_REFUSED: &str = + "child sandboxes use their parent's policy; change the parent's policy instead"; + +/// Refuse a caller's policy change on a child sandbox. Gateway-internal writes, +/// such as copying the parent's policy, do not pass through here. +fn refuse_child_policy_write(sandbox: &Sandbox) -> Result<(), Status> { + if sandbox.parent.is_some() { + return Err(Status::failed_precondition(CHILD_POLICY_WRITE_REFUSED)); + } + Ok(()) +} + +/// Accept and drop a policy write from a child's own supervisor. The +/// supervisor re-reads the stored policy after writing, so the child keeps +/// exactly its parent's copy. +async fn ignore_child_supervisor_policy_write( + state: &Arc, + sandbox: &Sandbox, +) -> Result, Status> { + debug!( + sandbox_id = %sandbox.object_id(), + "UpdateConfig: dropped startup policy write from child sandbox" + ); + let latest = state + .store + .get_latest_policy(sandbox.object_id()) + .await + .map_err(|e| Status::internal(format!("fetch latest policy failed: {e}")))?; + let (version, hash) = latest.map_or((0, String::new()), |record| { + (record.version, record.policy_hash) + }); + Ok(update_config_response( + u32::try_from(version).unwrap_or(0), + hash, + 0, + false, + HashMap::new(), + )) +} + async fn handle_update_config_inner( state: &Arc, request: Request, @@ -4545,6 +4593,15 @@ async fn handle_update_config_inner( } let sandbox = sandbox.expect("non-global config update resolves a sandbox"); + if has_policy || has_merge_ops { + // A child's supervisor writes back its startup paths like any other + // sandbox. Accept and drop the write so the child keeps exactly its + // parent's policy. + if sandbox_caller && sandbox.parent.is_some() { + return ignore_child_supervisor_policy_write(state, &sandbox).await; + } + refuse_child_policy_write(&sandbox)?; + } let sandbox_id = sandbox.object_id().to_string(); replay_facts.resource(&sandbox)?; let mut response_annotations = sandbox_metadata_annotations(&sandbox); @@ -4655,7 +4712,7 @@ async fn handle_update_config_inner( )); } - let _mutation_guard = state + let mutation_guard = state .compute .mutation_guard(MutationScope::sandbox(&workspace, &sandbox_id)) .await @@ -4756,6 +4813,8 @@ async fn handle_update_config_inner( emit_config_update_policy_success(sandbox_caller); publish_sandbox_config_update(state, &sandbox_id); + drop(mutation_guard); + sync_children_after_commit(state, &sandbox_id).await; return Ok(update_config_response( u32::try_from(version).unwrap_or(0), @@ -4951,6 +5010,8 @@ async fn handle_update_config_inner( ); spawn_pending_chunk_refresh(state, &workspace, &sandbox); emit_full_policy_update_success(sandbox_caller, next_version); + drop(mutation_guard); + sync_children_after_commit(state, &sandbox_id).await; Ok(update_config_response( u32::try_from(next_version).unwrap_or(0), @@ -5365,6 +5426,19 @@ pub(super) async fn handle_report_policy_status( Ok(Response::new(ReportPolicyStatusResponse {})) } +/// Copy a root's newly committed policy into its children, after the root's +/// lock is released: each child copy takes the root's lock too. A copy this +/// misses, such as on a cancelled request, is made by the next periodic scan. +async fn sync_children_after_commit(state: &Arc, sandbox_id: &str) { + if let Err(error) = super::sandbox::sync_children(state, sandbox_id).await { + warn!( + parent_id = sandbox_id, + error = %error, + "failed to copy policy into child sandboxes" + ); + } +} + /// Persist the exact sandbox policy revision attempted by a supervisor. /// Unary rollout reports and stream acknowledgements share this path. pub async fn record_policy_apply_result( @@ -5488,19 +5562,36 @@ pub(super) async fn handle_get_sandbox_logs( request: Request, ) -> Result, Status> { let principal = super::extract_principal(&request)?; - let req = request.into_inner(); - let sandbox = super::sandbox::resolve_and_authorize_sandbox_name( - state, - &principal, - &req.sandbox, - selected_workspace_name(req.workspace_scope.as_ref())?, - MinWorkspaceRole::User, - ) - .await?; + let mut req = request.into_inner(); + // A sandbox caller (only through `/mcp`) reads one of its own children, + // ready or not, and only the child's own output: gateway lines about it + // can carry audit and internal detail. + let sandbox_caller = matches!(principal, Principal::Sandbox(_)); + let sandbox = if let Principal::Sandbox(caller) = &principal { + refuse_log_fields_for_sandbox_caller(&req)?; + req.sources = vec!["sandbox".to_string()]; + super::sandbox::resolve_caller_child(state, caller, &req.sandbox).await? + } else { + super::sandbox::resolve_and_authorize_sandbox_name( + state, + &principal, + &req.sandbox, + selected_workspace_name(req.workspace_scope.as_ref())?, + MinWorkspaceRole::User, + ) + .await? + }; let sandbox_id = sandbox.object_id(); let lines = if req.lines == 0 { 2000 } else { req.lines }; - let tail = state.tracing_log_bus.tail(sandbox_id, lines as usize); + // A sandbox caller's line count applies after its source filter, so + // dropped gateway lines do not shrink the reply. + let tail_len = if sandbox_caller { + usize::MAX + } else { + lines as usize + }; + let tail = state.tracing_log_bus.tail(sandbox_id, tail_len); let buffer_total = tail.len() as u32; @@ -5536,6 +5627,13 @@ pub(super) async fn handle_get_sandbox_logs( } }) .collect(); + let logs = if sandbox_caller { + let mut logs: Vec = logs; + let keep_from = logs.len().saturating_sub(lines as usize); + logs.split_off(keep_from) + } else { + logs + }; Ok(Response::new(GetSandboxLogsResponse { logs, buffer_total })) } @@ -5569,6 +5667,34 @@ impl LogStreamState { } } +/// A sandbox caller's log request may set only the child, the line count and +/// a start time. +fn refuse_log_fields_for_sandbox_caller(request: &GetSandboxLogsRequest) -> Result<(), Status> { + let set = [ + ("workspace_scope", request.workspace_scope.is_some()), + ("sources", !request.sources.is_empty()), + ("min_level", !request.min_level.is_empty()), + ]; + if let Some((field, _)) = set.iter().find(|(_, is_set)| *is_set) { + return Err(Status::invalid_argument(format!( + "field '{field}' is not allowed for sandbox callers" + ))); + } + let allowed = GetSandboxLogsRequest { + sandbox: request.sandbox.clone(), + lines: request.lines, + since_time: request.since_time, + ..Default::default() + }; + if *request == allowed { + Ok(()) + } else { + Err(Status::invalid_argument( + "the request sets fields that are not allowed for sandbox callers", + )) + } +} + pub(super) async fn handle_push_sandbox_logs( state: &Arc, request: Request>, @@ -5771,6 +5897,20 @@ pub(super) async fn handle_submit_policy_analysis( accepted_chunk_ids: Vec::new(), })); } + // A child's proposals are rejected before they are stored, so no route + // can approve them later. + if sandbox.parent.is_some() { + return Ok(Response::new(SubmitPolicyAnalysisResponse { + accepted_chunks: 0, + rejected_chunks: u32::try_from(req.proposed_chunks.len()).unwrap_or(u32::MAX), + rejection_reasons: req + .proposed_chunks + .iter() + .map(|chunk| format!("chunk '{}': {CHILD_POLICY_WRITE_REFUSED}", chunk.rule_name)) + .collect(), + accepted_chunk_ids: Vec::new(), + })); + } // `current_policy` is captured ONCE at the top of the batch and frozen // for every chunk's delta computation, even if an earlier chunk in the @@ -6271,6 +6411,7 @@ async fn handle_approve_draft_chunk_inner( require_no_global_policy(state).await?; + refuse_child_policy_write(&sandbox)?; let sandbox_id = sandbox.object_id().to_string(); replay_facts.resource(&sandbox)?; @@ -6336,6 +6477,7 @@ async fn handle_approve_draft_chunk_inner( } }; crate::config_delivery::publish_sandbox(state, &sandbox_id); + sync_children_after_commit(state, &sandbox_id).await; let chunk_summary = summarize_draft_chunk_rule(&chunk)?; let now_ms = current_time_ms(); @@ -6453,6 +6595,7 @@ async fn handle_reject_draft_chunk_inner( let (version, hash) = remove_chunk_from_policy(state, &sandbox_id, &workspace, &chunk).await?; crate::config_delivery::publish_sandbox(state, &sandbox_id); + sync_children_after_commit(state, &sandbox_id).await; emit_gateway_policy_audit_log( &sandbox_id, sandbox.object_name(), @@ -6522,6 +6665,7 @@ async fn handle_approve_all_draft_chunks_inner( require_no_global_policy(state).await?; + refuse_child_policy_write(&sandbox)?; let sandbox_id = sandbox.object_id().to_string(); replay_facts.resource(&sandbox)?; @@ -6741,6 +6885,7 @@ async fn handle_approve_all_draft_chunks_inner( if !accepted.is_empty() { crate::config_delivery::publish_sandbox(state, &sandbox_id); + sync_children_after_commit(state, &sandbox_id).await; } for (chunk, _, chunk_summary) in &accepted { @@ -6903,6 +7048,7 @@ async fn handle_undo_draft_chunk_inner( return Err(Status::invalid_argument("chunk_id is required")); } + refuse_child_policy_write(&sandbox)?; let sandbox_id = sandbox.object_id().to_string(); replay_facts.resource(&sandbox)?; @@ -6932,6 +7078,7 @@ async fn handle_undo_draft_chunk_inner( let (version, hash) = remove_chunk_from_policy(state, &sandbox_id, &workspace, &chunk).await?; crate::config_delivery::publish_sandbox(state, &sandbox_id); + sync_children_after_commit(state, &sandbox_id).await; // Clear any prior rejection_reason on the way back to "pending" so an // agent reading the chunk via policy.local cannot see a stale guidance @@ -7087,7 +7234,7 @@ pub(super) async fn handle_get_draft_history( /// `PolicyRecord::policy_hash` is persisted metadata and cannot prove what the /// payload contains. Decode and validate every record before using its identity /// so legacy encodings deduplicate semantically and damaged rows fail closed. -fn canonical_policy_record_identity( +pub(super) fn canonical_policy_record_identity( record: &PolicyRecord, ) -> Result<(ProtoSandboxPolicy, String), Status> { let decoded = decode_stored_policy(record.policy_payload.as_slice()) @@ -7103,7 +7250,7 @@ fn canonical_policy_record_identity( /// policy. A full, already-validated replacement is different: treating an /// unreadable current row as non-matching lets the write path append a good /// revision instead of making the corrupt or legacy row permanently terminal. -fn canonical_policy_record_matches_for_deduplication( +pub(super) fn canonical_policy_record_matches_for_deduplication( record: &PolicyRecord, expected_hash: &str, ) -> bool { @@ -8199,6 +8346,13 @@ pub(super) async fn load_global_settings(store: &Store) -> Result Result { + Ok(load_global_settings(store) + .await? + .settings + .contains_key(POLICY_SETTING_KEY)) +} + pub(super) async fn save_global_settings( store: &Store, settings: &StoredSettings, diff --git a/crates/openshell-server/src/grpc/policy/config_inputs.rs b/crates/openshell-server/src/grpc/policy/config_inputs.rs index f8905bc992..2b1a2662fd 100644 --- a/crates/openshell-server/src/grpc/policy/config_inputs.rs +++ b/crates/openshell-server/src/grpc/policy/config_inputs.rs @@ -44,10 +44,15 @@ impl SandboxConfigInputs { /// Load the inputs both configuration builders share. Independent reads run /// concurrently; a failure here fails every component built from them. +/// +/// A child is checked against its parent's live record first, so every build +/// serves it only providers its parent still has, whether or not a sync has +/// reached it. pub async fn load_sandbox_config_inputs( state: &ServerState, - sandbox: Sandbox, + mut sandbox: Sandbox, ) -> Result { + super::super::sandbox::keep_parent_providers(state, &mut sandbox).await?; let store = state.store.as_ref(); let workspace = sandbox.object_workspace(); let provider_names = sandbox diff --git a/crates/openshell-server/src/grpc/provider_readiness.rs b/crates/openshell-server/src/grpc/provider_readiness.rs index 8a690c6c74..1801a13dcb 100644 --- a/crates/openshell-server/src/grpc/provider_readiness.rs +++ b/crates/openshell-server/src/grpc/provider_readiness.rs @@ -224,10 +224,9 @@ async fn current_target_identity( sandbox: &Sandbox, provider_name: &str, ) -> Result { - let attached = sandbox - .spec - .as_ref() - .is_some_and(|spec| spec.providers.iter().any(|name| name == provider_name)); + let attached = super::sandbox::provider_attached_for_delivery(state, sandbox, provider_name) + .await + .map_err(|_| registry_unavailable())?; let provider = if attached { state .store diff --git a/crates/openshell-server/src/grpc/sandbox.rs b/crates/openshell-server/src/grpc/sandbox.rs index 8e5762a33b..d6f0cc36a8 100644 --- a/crates/openshell-server/src/grpc/sandbox.rs +++ b/crates/openshell-server/src/grpc/sandbox.rs @@ -23,6 +23,7 @@ use crate::persistence::{ ObjectLabels, ObjectListQuery, ObjectType, PersistenceResult, Store, WriteCondition, generate_name, }; +use crate::policy_store::PolicyStoreExt; use crate::tracing_bus::CursoredEvent; use crate::watch_cursor::WatchCursor; use futures::future; @@ -281,6 +282,72 @@ pub(super) async fn resolve_and_authorize_sandbox_name( Ok(sandbox) } +/// Resolve `name` for a sandbox caller (only through `/mcp`): one of its own +/// children, in its own workspace. Everything else, the caller itself +/// included, reads as missing. +pub(super) async fn resolve_caller_child( + state: &ServerState, + caller: &crate::auth::principal::SandboxPrincipal, + name: &str, +) -> Result { + let not_found = || Status::not_found(format!("sandbox '{name}' not found")); + let caller = state + .store + .get_message::(&caller.sandbox_id) + .await + .map_err(|e| Status::internal(format!("fetch sandbox failed: {e}")))? + .ok_or_else(not_found)?; + let child = state + .store + .get_message_by_name::(caller.object_workspace(), name) + .await + .map_err(|e| Status::internal(format!("fetch sandbox failed: {e}")))? + .ok_or_else(not_found)?; + if child + .parent + .as_ref() + .is_some_and(|parent| parent.id == caller.object_id()) + { + Ok(child) + } else { + Err(not_found()) + } +} + +/// A sandbox caller's exec may set only the target, command, working +/// directory, stdin and timeout. +fn refuse_exec_fields_for_sandbox_caller(request: &ExecSandboxRequest) -> Result<(), Status> { + let set = [ + ("workspace_scope", request.workspace_scope.is_some()), + ("environment", !request.environment.is_empty()), + ("tty", request.tty), + ("cols", request.cols != 0), + ("rows", request.rows != 0), + ("no_login_shell", request.no_login_shell), + ("request_id", !request.request_id.is_empty()), + ]; + if let Some((field, _)) = set.iter().find(|(_, is_set)| *is_set) { + return Err(Status::invalid_argument(format!( + "field '{field}' is not allowed for sandbox callers" + ))); + } + let allowed = ExecSandboxRequest { + sandbox: request.sandbox.clone(), + command: request.command.clone(), + workdir: request.workdir.clone(), + stdin: request.stdin.clone(), + execution_timeout: request.execution_timeout, + ..Default::default() + }; + if *request == allowed { + Ok(()) + } else { + Err(Status::invalid_argument( + "the request sets fields that are not allowed for sandbox callers", + )) + } +} + fn require_ready_sandbox(sandbox: &Sandbox) -> Result<(), Status> { match SandboxPhase::try_from(sandbox.phase()).ok() { Some(SandboxPhase::Ready) => Ok(()), @@ -472,6 +539,22 @@ fn principal_subject(principal: &crate::auth::principal::Principal) -> Result Option { + match principal { + crate::auth::principal::Principal::User(user) => Some(openshell_core::proto::UserRef { + subject: user.identity.subject.clone(), + identity_provider: crate::multiplex::identity_provider_name(user.identity.provider) + .to_string(), + }), + _ => None, + } +} + /// Read the staging token a caller named for the active driver, without /// removing it. The gateway consumes it later, inside `create_sandbox`. fn staging_token_in_spec(spec: &SandboxSpec, driver_name: &str) -> Option { @@ -560,1367 +643,1280 @@ fn sandbox_create_telemetry_attrs( } } -async fn handle_create_sandbox_inner( - state: &Arc, - request: Request, -) -> Result, Status> { - let principal = super::extract_principal(&request)?; - let request = request.into_inner(); - let await_main_process_attachment = request.await_main_process_attachment; - let workload_template_name = request.workload_template.trim().to_string(); - - validate_create_sandbox_request_pre_io(&request, &workload_template_name)?; - - let authz = authorize_workspace( - &state.store, - &state.admin_role, - &principal, - crate::auth::workspace_authz::selected_workspace_name(request.workspace_scope.as_ref())?, - MinWorkspaceRole::User, - ) - .await?; - let workspace = super::workspace::resolve_workspace(state.store.as_ref(), &authz.workspace) - .await? - .ensure_active()?; +/// Check the parent named in a create request and return the link to store on +/// the new child. Returns `None` when no parent is named, for a root sandbox. +async fn resolve_create_parent( + state: &ServerState, + workspace: &str, + parent_name: &str, + spec: &mut SandboxSpec, +) -> Result, Status> { + if parent_name.is_empty() { + return Ok(None); + } + ensure_child_sandboxes_enabled(state)?; + let parent = state + .store + .get_message_by_name::(workspace, parent_name) + .await + .map_err(|e| Status::internal(format!("fetch parent sandbox failed: {e}")))? + .ok_or_else(|| { + Status::failed_precondition(format!("parent sandbox '{parent_name}' not found")) + })?; + check_create_parent(&parent, spec).map(Some) +} - let (mut spec, created_from_workload_template) = if workload_template_name.is_empty() { - let spec = request - .spec - .ok_or_else(|| Status::invalid_argument("spec is required"))?; - (spec, None) +fn ensure_child_sandboxes_enabled(state: &ServerState) -> Result<(), Status> { + if state.config.enable_child_sandboxes { + Ok(()) } else { - let governance_spec = request.spec.unwrap_or_default(); - let template = state - .store - .get_message_by_name::(&workspace, &workload_template_name) - .await - .map_err(|e| Status::internal(format!("fetch sandbox template failed: {e}")))? - .ok_or_else(|| Status::not_found("sandbox template not found"))?; - let provenance = SandboxWorkloadTemplateProvenance { - name: template.object_name().to_string(), - resource_version: template.get_resource_version().to_string(), - }; - let mut resolved = sandbox_spec_from_stored_workload_template(&template)?; - resolved.policy = governance_spec.policy; - resolved.providers = governance_spec.providers; - resolved.command = governance_spec.command; - resolved.tty = governance_spec.tty; - resolved.restart_policy = governance_spec.restart_policy; - (resolved, Some(provenance)) - }; - - // Attachment identity belongs to the gateway. Accepting an epoch from a - // create request or workload template could revive stale installation proof. - spec.provider_attachment_epoch = uuid::Uuid::new_v4().to_string(); - if spec.restart_policy == SandboxRestartPolicy::Unspecified as i32 { - spec.restart_policy = SandboxRestartPolicy::Never as i32; + Err(Status::failed_precondition( + "child sandboxes are disabled on this gateway", + )) } +} - // Leave an omitted command empty rather than persisting a concrete shell: - // the sandbox boundary resolves the default login shell against the agent image - // (bash when present, otherwise /bin/sh on minimal images like Alpine), - // which the gateway cannot do since it does not see the sandbox filesystem. - // The default is an interactive login shell, so request a TTY. - if spec.command.is_empty() { - spec.tty = true; +/// Check that `parent` can take a child with `spec`, and return the link to +/// store on the child. A child that names no providers gets all of its +/// parent's providers. Users and sandbox callers share these checks. +fn check_create_parent( + parent: &Sandbox, + spec: &mut SandboxSpec, +) -> Result { + let parent_name = parent.object_name(); + if crate::compute::is_being_deleted(parent) { + return Err(Status::failed_precondition(format!( + "parent sandbox '{parent_name}' is being deleted" + ))); + } + if parent.parent.is_some() { + return Err(Status::failed_precondition( + "only one level of child sandboxes is supported", + )); + } + if spec.policy.is_some() { + return Err(Status::invalid_argument( + "a child sandbox uses its parent's policy; omit the policy", + )); + } + let parent_providers = parent + .spec + .as_ref() + .map_or(&[][..], |parent_spec| parent_spec.providers.as_slice()); + if let Some(provider) = spec + .providers + .iter() + .find(|provider| !parent_providers.contains(provider)) + { + return Err(Status::failed_precondition(format!( + "provider '{provider}' is not attached to parent '{parent_name}'" + ))); } + if spec.providers.is_empty() { + spec.providers = parent_providers.to_vec(); + } + Ok(openshell_core::proto::SandboxParent { + name: parent_name.to_string(), + id: parent.object_id().to_string(), + }) +} - // Validate field sizes before any create-side effects. - validate_sandbox_spec(&request.name, &spec)?; +/// A sandbox caller (only through `/mcp`) creating a child of itself: read its +/// own record and check the request and its creator. The child always goes in +/// the caller's workspace with the caller as its parent. +async fn sandbox_caller_create( + state: &ServerState, + caller: &crate::auth::principal::SandboxPrincipal, + request: &CreateSandboxRequest, +) -> Result { + refuse_fields_for_sandbox_caller(request)?; + ensure_child_sandboxes_enabled(state)?; + let caller = state + .store + .get_message::(&caller.sandbox_id) + .await + .map_err(|e| Status::internal(format!("fetch sandbox failed: {e}")))? + .ok_or_else(|| Status::not_found("sandbox not found"))?; + if caller.parent.is_some() { + return Err(Status::failed_precondition( + "only root sandboxes can create child sandboxes", + )); + } + refuse_caller_with_driver_config(&caller)?; + check_creator_has_access(state, &caller).await?; + Ok(caller) +} - // A staging slot may only be redeemed by the caller it was issued to. This - // is the only point in the create path where the principal is in scope. - if let Some(token) = staging_token_in_spec(&spec, state.compute.configured_driver_name()) { - let subject = principal_subject(&principal)?; - state - .compute - .rootfs_tar_staging() - .authorize(&token, &workspace, &subject)?; +/// A sandbox caller may set only `name`, `workload_template` and +/// `spec.providers`; the gateway decides everything else. +fn refuse_fields_for_sandbox_caller(request: &CreateSandboxRequest) -> Result<(), Status> { + let spec = request.spec.clone().unwrap_or_default(); + let set = [ + ("workspace_scope", request.workspace_scope.is_some()), + ("parent", !request.parent.is_empty()), + ("labels", !request.labels.is_empty()), + ("annotations", !request.annotations.is_empty()), + ( + "await_main_process_attachment", + request.await_main_process_attachment, + ), + ("request_id", !request.request_id.is_empty()), + ("service_exposures", !request.service_exposures.is_empty()), + ("spec.log_level", !spec.log_level.is_empty()), + ("spec.environment", !spec.environment.is_empty()), + ("spec.template", spec.template.is_some()), + ("spec.policy", spec.policy.is_some()), + ( + "spec.resource_requirements", + spec.resource_requirements.is_some(), + ), + ("spec.command", !spec.command.is_empty()), + ("spec.tty", spec.tty), + ( + "spec.provider_attachment_epoch", + !spec.provider_attachment_epoch.is_empty(), + ), + ("spec.restart_policy", spec.restart_policy != 0), + ]; + if let Some((field, _)) = set.iter().find(|(_, is_set)| *is_set) { + return Err(Status::invalid_argument(format!( + "field '{field}' is not allowed for sandbox callers" + ))); } + refuse_unlisted_fields_for_sandbox_caller(request) +} - let id = uuid::Uuid::new_v4().to_string(); - let name = if request.name.is_empty() { - generate_routable_name() - } else { - request.name.clone() +/// Backstop for fields the named checks above do not list, such as ones added +/// to the request later: anything beyond what a sandbox caller may send. +fn refuse_unlisted_fields_for_sandbox_caller(request: &CreateSandboxRequest) -> Result<(), Status> { + let allowed = CreateSandboxRequest { + name: request.name.clone(), + workload_template: request.workload_template.clone(), + spec: request.spec.as_ref().map(|spec| SandboxSpec { + providers: spec.providers.clone(), + ..Default::default() + }), + ..Default::default() }; - let (sandbox_lifecycle_guard, mutation_guard) = state - .compute - .sandbox_create_guards(&workspace, &id) - .await - .map_err(|err| super::persistence_error_to_status(err, "acquire sandbox mutation lock"))?; + if *request == allowed { + Ok(()) + } else { + Err(Status::invalid_argument( + "the request sets fields that are not allowed for sandbox callers", + )) + } +} - // Validate provider names exist (fail fast). - for name in &spec.providers { - state - .store - .get_message_by_name::(&workspace, name) - .await - .map_err(|e| Status::internal(format!("fetch provider failed: {e}")))? - .ok_or_else(|| Status::failed_precondition(format!("provider '{name}' not found")))?; +/// The user who created a root must still be a workspace member with at least +/// the user role for the root to create children. A root with no recorded +/// creator fails closed. Checked on every create. +async fn check_creator_has_access(state: &ServerState, caller: &Sandbox) -> Result<(), Status> { + let Some(creator) = caller + .created_on_behalf_of + .as_ref() + .filter(|creator| !creator.subject.is_empty()) + else { + return Err(Status::failed_precondition( + "this sandbox was not started by a workspace user, so it cannot create children", + )); + }; + // With no admin role configured every authenticated user is a platform + // admin and needs no membership, as in `authorize_workspace`. Only the + // creator's subject is recorded, so an admin by role is not recognized + // once an admin role is configured. + if state.admin_role.is_empty() { + return Ok(()); } - let provider_profile_catalog = state - .provider_profile_sources - .snapshot_catalog(state.store.as_ref(), &workspace) - .await?; - super::provider::validate_provider_profiles_present( - state.store.as_ref(), - &provider_profile_catalog, - &workspace, - &spec.providers, - ) - .await?; - validate_provider_environment_keys_unique_with_catalog( - state.store.as_ref(), - crate::provider_refresh::RefreshStateReader::Runtime(&state.refresh), - &provider_profile_catalog, - &workspace, - &spec.providers, + // Development gateways create roots as the built-in local user, which has + // no membership; it counts only while such users are still allowed. + if state.config.auth.allow_unauthenticated_users + && creator.identity_provider + == crate::multiplex::identity_provider_name(IdentityProvider::LocalDev) + { + return Ok(()); + } + if !crate::auth::workspace_authz::subject_has_workspace_role( + &state.store, + caller.object_workspace(), + &creator.subject, + MinWorkspaceRole::User, ) - .await?; + .await? + { + // The agent is not told who the creator is; the audit event records it. + let workspace = caller.object_workspace(); + return Err(Status::permission_denied(format!( + "the user who started this sandbox is not a member of workspace '{workspace}' \ + with the user role; a platform admin can add them with: openshell workspace \ + member add --workspace {workspace} --subject --role user" + ))); + } + Ok(()) +} - // Ensure the template always carries the resolved image. - let template = spec.template.get_or_insert_with(SandboxTemplate::default); - if template.image.trim().is_empty() { - template.image = state.compute.default_image().to_string(); +/// The spec a sandbox caller's child gets without a template: the caller's +/// image, CPU and memory, isolation settings, and the named providers. +/// Nothing else is copied, so no GPU or other device. +fn spec_copied_from_caller(caller: &Sandbox, providers: Vec) -> SandboxSpec { + let template = caller.spec.as_ref().and_then(|spec| spec.template.as_ref()); + let mut child = SandboxTemplate { + image: template.map(|t| t.image.clone()).unwrap_or_default(), + resources: template.and_then(|t| cpu_and_memory_only(t.resources.as_ref())), + ..Default::default() + }; + copy_isolation_from_caller(caller, &mut child); + SandboxSpec { + template: Some(child), + providers, + ..Default::default() } +} - if let Some(ref mut policy) = spec.policy { - super::policy::clear_provider_credentialed_markers(policy); - validate_no_reserved_provider_policy_keys(policy)?; - *policy = validate_and_canonicalize_policy(policy.clone())?; +/// A child is never less isolated than its root or its template: the root's +/// runtime class wins when it has one, and user namespaces stay on when +/// either asks for them. +fn copy_isolation_from_caller(caller: &Sandbox, child: &mut SandboxTemplate) { + let root = caller.spec.as_ref().and_then(|spec| spec.template.as_ref()); + if let Some(root) = root.filter(|root| !root.runtime_class_name.is_empty()) { + child + .runtime_class_name + .clone_from(&root.runtime_class_name); } + if root.and_then(|root| root.user_namespaces) == Some(true) { + child.user_namespaces = Some(true); + } +} - // Process identity and MCP default materialization can increase the - // protobuf size. Recheck the exact canonical spec before any middleware or - // compute boundary can observe or persist it. The initial check remains - // above so requests that are already oversized still fail before I/O. - validate_sandbox_spec(&request.name, &spec)?; +/// Driver configuration can set isolation, devices and mounts that cannot be +/// copied safely, so a root that has any cannot create children over MCP. +fn refuse_caller_with_driver_config(caller: &Sandbox) -> Result<(), Status> { + let has_driver_config = caller + .spec + .as_ref() + .and_then(|spec| spec.template.as_ref()) + .is_some_and(|template| template.driver_config.is_some()); + if has_driver_config { + return Err(Status::failed_precondition( + "this sandbox has driver configuration, which children cannot copy", + )); + } + Ok(()) +} - if let Some(ref policy) = spec.policy { - validate_policy_safety(policy)?; - crate::middleware::validate_policy(state.middleware_registry.as_ref(), policy).await?; +/// Keep only `cpu` and `memory` under `limits` and `requests`; drop GPUs and +/// any other extended resource. +fn cpu_and_memory_only(resources: Option<&Struct>) -> Option { + let fields: std::collections::BTreeMap<_, _> = resources? + .fields + .iter() + .filter(|(section, _)| matches!(section.as_str(), "limits" | "requests")) + .filter_map(|(section, value)| { + let Some(Kind::StructValue(quantities)) = value.kind.as_ref() else { + return None; + }; + let kept: std::collections::BTreeMap<_, _> = quantities + .fields + .iter() + .filter(|(name, _)| matches!(name.as_str(), "cpu" | "memory")) + .map(|(name, quantity)| (name.clone(), quantity.clone())) + .collect(); + (!kept.is_empty()).then(|| { + let value = Value { + kind: Some(Kind::StructValue(Struct { fields: kept })), + }; + (section.clone(), value) + }) + }) + .collect(); + (!fields.is_empty()).then_some(Struct { fields }) +} + +/// Agents may create children only from templates an administrator marked +/// for them, and never from one with driver configuration. +fn check_agent_usable_template(template: &SandboxWorkloadTemplate) -> Result<(), Status> { + let labelled = template + .metadata + .as_ref() + .and_then(|metadata| metadata.labels.get(AGENT_USABLE_TEMPLATE_LABEL)) + .is_some_and(|value| value == "true"); + let has_driver_config = template + .spec + .as_ref() + .is_some_and(|spec| spec.driver_config.is_some()); + if labelled && !has_driver_config { + Ok(()) + } else { + Err(template_not_available(template.object_name())) } - super::policy::validate_candidate_sandbox_credential_policy( - state, - &workspace, - &spec.providers, - spec.policy.as_ref(), - ) - .await?; +} - let now_ms = current_time_ms(); +const AGENT_USABLE_TEMPLATE_LABEL: &str = "openshell.ai/agent-usable"; - let mut sandbox = Sandbox { - host_key_fingerprint: String::new(), - metadata: Some(ObjectMeta { - id: id.clone(), - name: name.clone(), - created_time: openshell_core::time::timestamp_from_millis(now_ms).ok(), - labels: request.labels.clone(), - resource_version: 0, - annotations: request.annotations.clone(), - workspace, - deletion_time: None, - }), - spec: Some(spec), - status: None, - created_from_workload_template, - }; - sandbox.set_phase(SandboxPhase::Provisioning as i32); - sandbox - .status - .get_or_insert_with(Default::default) - .configuration_admission = Some(openshell_core::proto::SandboxConfigurationAdmission { - state: openshell_core::proto::ConfigurationAdmissionState::Pending.into(), - ..Default::default() +fn template_not_available(name: &str) -> Status { + Status::failed_precondition(format!("template '{name}' is not available to agents")) +} + +/// Under the child-create lock, re-read the parent and check that it can take +/// one more child and still has the child's providers. Every existing child +/// counts, whatever its state. +async fn check_parent_has_room( + state: &ServerState, + workspace: &str, + parent: &openshell_core::proto::SandboxParent, + providers: &[String], +) -> Result<(), Status> { + let current = state + .store + .get_message::(&parent.id) + .await + .map_err(|e| Status::internal(format!("fetch parent sandbox failed: {e}")))?; + let usable = current.as_ref().is_some_and(|current| { + current.parent.is_none() && !crate::compute::is_being_deleted(current) }); - sandbox - .status - .as_mut() - .expect("status initialized") - .configuration_activated = Some(false); - sandbox - .status - .as_mut() - .expect("status initialized") - .provisioning = Some( - crate::compute::provisioning_deadline::new_preparation_record( - now_ms, - state.config.image_preparation_timeout_seconds, - state.config.provisioning_repair_window_seconds * 1000, - ), - ); - crate::compute::provisioning_deadline::refresh_configuration( - &state.store, - &mut sandbox, - now_ms, - state.config.provisioning_repair_window_seconds * 1000, - ) - .await - .map_err(Status::internal)?; - crate::compute::apply_configuration_readiness(&mut sandbox); + if !usable { + return Err(Status::failed_precondition(format!( + "parent sandbox '{}' is no longer available", + parent.name + ))); + } + let parent_providers = current + .as_ref() + .and_then(|current| current.spec.as_ref()) + .map_or(&[][..], |parent_spec| parent_spec.providers.as_slice()); + if let Some(provider) = providers + .iter() + .find(|provider| !parent_providers.contains(provider)) + { + return Err(Status::failed_precondition(format!( + "provider '{provider}' is not attached to parent '{}'", + parent.name + ))); + } + // A child keeps its slot until its delete finishes: until then its + // compute resources may still run, and a stuck delete must not let a + // looping agent exceed the limit. + let limit = state.config.max_concurrent_children; + let children = crate::compute::count_children(&state.store, workspace, &parent.id).await?; + if children.total() >= limit as usize { + let leaving = match children.being_deleted { + 0 => String::new(), + n => format!(", {n} of them still being deleted; try again shortly"), + }; + return Err(Status::resource_exhausted(format!( + "sandbox '{}' has reached its limit of {limit} children{leaving}", + parent.name + ))); + } + Ok(()) +} - // Ensure metadata is valid (defense in depth - should always be true for server-constructed metadata) - super::validation::validate_object_metadata(sandbox.metadata.as_ref(), "sandbox")?; - super::policy::validate_candidate_provider_attachments( - state, - sandbox.object_workspace(), - &sandbox, - sandbox - .spec - .as_ref() - .map(|spec| spec.providers.as_slice()) - .unwrap_or_default(), - ) - .await?; +/// A root's policy revision as copied into a child: the policy, cleaned +/// exactly as a create cleans it, and its hash. +struct ParentPolicyCopy { + policy: openshell_core::proto::SandboxPolicy, + hash: String, +} - // Provider and policy reads must stay under the create mutation guard so - // their revisions cannot change before the sandbox's launch is committed. - let mut runtime_inputs = - super::policy::resolve_sandbox_create_runtime_inputs(state.as_ref(), &sandbox).await?; +impl ParentPolicyCopy { + /// Create and sync both copy through here, so a child's first revision + /// and its later copies of the same root revision are identical. + fn of(record: &crate::persistence::PolicyRecord) -> Result { + let (mut policy, _) = super::policy::canonical_policy_record_identity(record)?; + super::policy::clear_provider_credentialed_markers(&mut policy); + validate_no_reserved_provider_policy_keys(&policy)?; + let policy = validate_and_canonicalize_policy(policy)?; + let hash = openshell_core::policy_identity::deterministic_policy_hash(&policy); + Ok(Self { policy, hash }) + } +} +/// The copy of a root's latest policy revision, or none when it has no +/// policy yet. Children follow the latest revision whether or not the root +/// has loaded it: each sandbox handles its own load result. +async fn parent_policy_copy( + state: &ServerState, + parent_id: &str, +) -> Result, Status> { state - .compute - .validate_launch_signer_configured(state.sandbox_session_jwt_authority.is_some())?; - state - .compute - .validate_sandbox_create_with_runtime_inputs( - &sandbox, - &runtime_inputs, - await_main_process_attachment, - ) + .store + .get_latest_policy(parent_id) .await - .map_err(|status| { - warn!(error = %status, "Rejecting sandbox create request"); - status - })?; + .map_err(|e| Status::internal(format!("fetch parent policy failed: {e}")))? + .map(|record| ParentPolicyCopy::of(&record)) + .transpose() +} - let runtime_identity = crate::auth::sandbox_session::PersistedSandboxIdentity::new() - .map_err(|error| Status::internal(error.to_string()))?; - if let Some(metadata) = sandbox.metadata.as_mut() { - runtime_identity.write(&mut metadata.annotations); +/// Under the child-create lock, copy the root's latest policy revision. +/// +/// A root started under a global policy has no revision, because its startup +/// upload is refused. Its child gets none either: both run the global policy, +/// and the sync copies the root's policy once it has one. +async fn copy_parent_policy( + state: &ServerState, + parent: &openshell_core::proto::SandboxParent, +) -> Result, Status> { + if let Some(copy) = parent_policy_copy(state, &parent.id).await? { + return Ok(Some(copy)); + } + if super::policy::global_policy_is_set(state.store.as_ref()).await? { + return Ok(None); + } + Err(Status::failed_precondition(format!( + "parent sandbox '{}' has no policy yet; try again once it is running", + parent.name + ))) +} + +/// Bring each live child of a root up to it: detach providers the root no +/// longer has, and copy the root's latest policy revision into a child whose +/// policy differs. Safe to run again: the startup and periodic scans rerun +/// it. One child's failure does not hold the change back from the others. +pub(super) async fn sync_children(state: &Arc, parent_id: &str) -> Result<(), Status> { + if !state.config.enable_child_sandboxes { + return Ok(()); } - let launch_authentication = if let Some(authority) = &state.sandbox_session_jwt_authority { - Some(authority.mint_persisted_launch(&id, &runtime_identity)?) - } else { - None + let Some(parent) = state + .store + .get_message::(parent_id) + .await + .map_err(|e| Status::internal(format!("fetch parent sandbox failed: {e}")))? + else { + return Ok(()); }; - let sandbox_token = launch_authentication.as_ref().map(|authentication| { - authentication - .supervisor - .gateway_token - .expose_secret() - .to_string() - }); - let launch_authentication = launch_authentication - .map(|authentication| { - serde_json::to_vec(&authentication) - .map_err(|error| Status::internal(format!("encode launch authentication: {error}"))) + if parent.parent.is_some() { + return Ok(()); + } + // A child created after this list copies the root's latest revision + // itself, under the root's lock. + let workspace = parent.object_workspace().to_string(); + let children: Vec = state + .store + .collect_messages::(ObjectListQuery::Workspace(&workspace)) + .await + .map_err(|e| Status::internal(format!("list sandboxes failed: {e}")))? + .iter() + .filter(|sandbox| { + sandbox + .parent + .as_ref() + .is_some_and(|parent| parent.id == parent_id) }) - .transpose()?; - runtime_inputs.launch_authentication = launch_authentication; - - let sandbox = Box::pin(state.compute.create_sandbox_with_runtime_inputs_and_guards( - sandbox, - sandbox_token, - await_main_process_attachment, - runtime_inputs, - sandbox_lifecycle_guard, - mutation_guard, - )) - .await?; + .map(|sandbox| sandbox.object_id().to_string()) + .collect(); - let mut service_urls = HashMap::with_capacity(request.service_exposures.len()); - let mut application_service_urls = HashMap::new(); - let mut gateway_service_urls = HashMap::new(); - for exposure in &request.service_exposures { - let endpoint = match super::service::expose_service_endpoint( - state, - sandbox.object_workspace(), - &sandbox, - &exposure.service, - exposure.target_port, - super::service::validate_service_exposure_request( - &exposure.service, - exposure.target_port, - exposure.authorization_mode, - )?, - ServiceBackendHttpVersion::Unspecified, - ) - .await - { - Ok(endpoint) => endpoint, - Err(exposure_error) => { - let rollback = state - .compute - .delete_sandbox_by_id(sandbox.object_id(), sandbox.object_name()) - .await; - if let Err(rollback_error) = rollback { - warn!( - sandbox_id = %sandbox.object_id(), - sandbox_name = %sandbox.object_name(), - service_name = %exposure.service, - exposure_error = %exposure_error, - rollback_error = %rollback_error, - "Failed to roll back sandbox after service exposure failed" - ); - return Err(Status::internal(format!( - "create sandbox failed while exposing service '{}': {}; rollback failed: {}; sandbox '{}' may require manual deletion", - exposure.service, - exposure_error.message(), - rollback_error.message(), - sandbox.object_name(), - ))); - } - return Err(exposure_error); + let mut failed = 0_usize; + for child_id in children { + match Box::pin(sync_child(state, &workspace, parent_id, &child_id)).await { + Ok(true) => { + state.sandbox_watch_bus.notify(&child_id); + crate::config_delivery::publish_sandbox(state, &child_id); + } + Ok(false) => {} + Err(error) => { + warn!(parent_id, child_id, error = %error, "failed to sync child sandbox"); + failed += 1; } - }; - let endpoint = endpoint.into_inner(); - if !endpoint.application_url.is_empty() { - application_service_urls.insert(exposure.service.clone(), endpoint.application_url); - } - if !endpoint.gateway_url.is_empty() { - gateway_service_urls.insert(exposure.service.clone(), endpoint.gateway_url); } - service_urls.insert(exposure.service.clone(), endpoint.url); } - - info!( - sandbox_id = %id, - sandbox_name = %name, - "CreateSandbox request completed successfully" - ); - Ok(Response::new(SandboxResponse { - application_service_urls, - gateway_service_urls, - sandbox: Some(sandbox), - service_urls, - })) + if failed > 0 { + return Err(Status::unavailable(format!( + "{failed} child sandboxes of '{}' were not synced", + parent.object_name() + ))); + } + Ok(()) } -fn validate_create_sandbox_request_pre_io( - request: &CreateSandboxRequest, - workload_template_name: &str, -) -> Result<(), Status> { - // Validate labels (keys and values must meet Kubernetes requirements). - crate::grpc::validation::validate_labels(&request.labels)?; - crate::grpc::validation::validate_caller_annotations(&request.annotations, "annotations")?; - - if request.service_exposures.len() > MAX_CREATE_SERVICE_EXPOSURES { - return Err(Status::invalid_argument(format!( - "service_exposures must contain at most {MAX_CREATE_SERVICE_EXPOSURES} entries" - ))); +/// Bring every root's children up to it: at gateway start, for changes made +/// while it was down, and periodically, for copies a failed or cancelled +/// request or another replica left undone. +pub async fn sync_all_children(state: &Arc) -> Result<(), Status> { + // The scan reads every sandbox in every workspace; with the feature off + // there are no children to find. + if !state.config.enable_child_sandboxes { + return Ok(()); } - let mut service_names = HashSet::with_capacity(request.service_exposures.len()); - for exposure in &request.service_exposures { - super::service::validate_service_exposure_request( - &exposure.service, - exposure.target_port, - exposure.authorization_mode, - )?; - if !service_names.insert(exposure.service.as_str()) { - return Err(Status::invalid_argument(format!( - "duplicate service exposure name: '{}'", - exposure.service - ))); + let parent_ids: std::collections::BTreeSet = state + .store + .collect_messages::(ObjectListQuery::AllWorkspaces) + .await + .map_err(|e| Status::internal(format!("list sandboxes failed: {e}")))? + .into_iter() + .filter_map(|sandbox| sandbox.parent.map(|parent| parent.id)) + .collect(); + let mut failed = 0_usize; + for parent_id in parent_ids { + if let Err(error) = sync_children(state, &parent_id).await { + warn!(parent_id, error = %error, "failed to sync child sandboxes"); + failed += 1; } } - - if workload_template_name.is_empty() { - let spec = request - .spec - .as_ref() - .ok_or_else(|| Status::invalid_argument("spec is required"))?; - return validate_sandbox_spec(&request.name, spec); + if failed > 0 { + return Err(Status::unavailable(format!( + "the children of {failed} parent sandboxes were not all synced" + ))); } + Ok(()) +} - validate_dns1123_label(workload_template_name, "workload_template_name")?; - if let Some(spec) = request.spec.as_ref() { - validate_template_create_governance_spec(spec)?; - validate_sandbox_governance_spec(&request.name, spec)?; - } else { - validate_sandbox_governance_spec(&request.name, &SandboxSpec::default())?; +/// Before a child's configuration is built, keep only the providers its +/// parent still has, in the child's order. A child whose parent record is +/// gone keeps none. A root passes unchanged. +pub(super) async fn keep_parent_providers( + state: &ServerState, + child: &mut Sandbox, +) -> Result<(), Status> { + let Some(parent_ref) = child.parent.as_ref() else { + return Ok(()); + }; + let parent_providers = state + .store + .get_message::(&parent_ref.id) + .await + .map_err(|e| Status::internal(format!("fetch parent sandbox failed: {e}")))? + .and_then(|parent| parent.spec) + .map(|spec| spec.providers) + .unwrap_or_default(); + if let Some(spec) = child.spec.as_mut() { + spec.providers + .retain(|name| parent_providers.contains(name)); } Ok(()) } -fn validate_template_create_governance_spec(spec: &SandboxSpec) -> Result<(), Status> { - if !spec.log_level.is_empty() { - return Err(Status::invalid_argument( - "spec.log_level cannot be set when workload_template_name is set", - )); - } - if !spec.environment.is_empty() { - return Err(Status::invalid_argument( - "spec.environment cannot be set when workload_template_name is set", - )); - } - if spec.template.is_some() { - return Err(Status::invalid_argument( - "spec.template cannot be set when workload_template_name is set", - )); - } - if spec.resource_requirements.is_some() { - return Err(Status::invalid_argument( - "spec.resource_requirements cannot be set when workload_template_name is set", - )); +/// Whether `provider` is attached to `sandbox` as delivery sees it: for a +/// child, attached to the child and still to its parent. +pub(super) async fn provider_attached_for_delivery( + state: &ServerState, + sandbox: &Sandbox, + provider: &str, +) -> Result { + let attached = |sandbox: &Sandbox| { + sandbox + .spec + .as_ref() + .is_some_and(|spec| spec.providers.iter().any(|name| name == provider)) + }; + if !attached(sandbox) { + return Ok(false); } - Ok(()) -} - -fn sandbox_spec_from_stored_workload_template( - template: &SandboxWorkloadTemplate, -) -> Result { - sandbox_spec_from_workload_template(template, tonic::Code::Internal) + let Some(parent) = sandbox.parent.as_ref() else { + return Ok(true); + }; + Ok(state + .store + .get_message::(&parent.id) + .await + .map_err(|e| Status::internal(format!("fetch parent sandbox failed: {e}")))? + .is_some_and(|parent| attached(&parent))) } -fn sandbox_spec_from_user_workload_template( - template: &SandboxWorkloadTemplate, -) -> Result { - sandbox_spec_from_workload_template(template, tonic::Code::InvalidArgument) -} +/// Bring one child up to its parent under the child-sandbox lock set, which +/// includes the parent: the root's latest revision and providers read here +/// are current, and a root commit waits for this copy or lands before it. +/// Returns whether the child changed. +async fn sync_child( + state: &Arc, + workspace: &str, + parent_id: &str, + child_id: &str, +) -> Result { + let _guard = state + .compute + .mutation_guard(MutationScope::ChildSandbox { + workspace, + sandbox_id: child_id, + parent_id, + }) + .await + .map_err(|e| super::persistence_error_to_status(e, "acquire sandbox mutation lock"))?; + let Some(child) = state + .store + .get_message::(child_id) + .await + .map_err(|e| Status::internal(format!("fetch child sandbox failed: {e}")))? + else { + return Ok(false); + }; + if crate::compute::is_being_deleted(&child) { + return Ok(false); + } + let Some(parent) = state + .store + .get_message::(parent_id) + .await + .map_err(|e| Status::internal(format!("fetch parent sandbox failed: {e}")))? + else { + return Ok(false); + }; -fn sandbox_spec_from_workload_template( - template: &SandboxWorkloadTemplate, - missing_field_code: tonic::Code, -) -> Result { - let spec = template + // Losing a provider is a revocation: detach it before the policy copy, + // which can fail. + let parent_providers = parent.spec.map(|spec| spec.providers).unwrap_or_default(); + let lost: Vec = child .spec .as_ref() - .ok_or_else(|| Status::new(missing_field_code, "sandbox template spec is required"))?; - let workload = spec - .workload - .as_ref() - .ok_or_else(|| Status::new(missing_field_code, "sandbox template workload is required"))?; - let resources = workload.resources.as_ref(); - Ok(SandboxSpec { - environment: workload.environment.clone(), - template: Some(SandboxTemplate { - image: workload.image.clone(), - resources: resources.and_then(template_resource_struct), - driver_config: spec.driver_config.clone(), - ..SandboxTemplate::default() - }), - resource_requirements: resources.and_then(template_gpu_requirements), - ..SandboxSpec::default() - }) -} - -fn template_gpu_requirements(resources: &SandboxResources) -> Option { - Some(ResourceRequirements { - gpu: Some(resources.gpu?), - }) -} - -fn template_resource_struct(resources: &SandboxResources) -> Option { - let mut limits = std::collections::BTreeMap::new(); - if !resources.cpu.is_empty() { - limits.insert( - "cpu".to_string(), - Value { - kind: Some(Kind::StringValue(resources.cpu.clone())), - }, - ); - } - if !resources.memory.is_empty() { - limits.insert( - "memory".to_string(), - Value { - kind: Some(Kind::StringValue(resources.memory.clone())), - }, - ); - } - if limits.is_empty() { - None - } else { - let mut fields = std::collections::BTreeMap::new(); - fields.insert( - "limits".to_string(), - Value { - kind: Some(Kind::StructValue(Struct { fields: limits })), - }, + .map(|spec| spec.providers.as_slice()) + .unwrap_or_default() + .iter() + .filter(|name| !parent_providers.contains(name)) + .cloned() + .collect(); + for provider in &lost { + detach_provider_locked(state, child_id, 0, provider).await?; + info!( + parent_id, + child_id, provider, "detached a provider its parent lost from child sandbox" ); - Some(Struct { fields }) } -} -fn owner_requested(request: &Request) -> bool { - request - .metadata() - .contains_key(openshell_core::replica_routing::OWNER_REQUEST_HEADER) + let Some(copy) = parent_policy_copy(state, parent_id).await? else { + return Ok(!lost.is_empty()); + }; + let latest = state + .store + .get_latest_policy(child_id) + .await + .map_err(|e| Status::internal(format!("fetch child policy failed: {e}")))?; + if latest.as_ref().is_some_and(|record| { + super::policy::canonical_policy_record_matches_for_deduplication(record, ©.hash) + }) { + return Ok(!lost.is_empty()); + } + let write = crate::policy_store::AtomicPolicyRevisionWrite { + id: uuid::Uuid::new_v4().to_string(), + sandbox_id: child_id.to_string(), + workspace: workspace.to_string(), + version: latest.as_ref().map_or(1, |record| record.version + 1), + policy_payload: copy.policy.encode_to_vec(), + policy_hash: copy.hash, + provenance: HashMap::new(), + expected_resource_version: 0, + annotations: HashMap::new(), + backfill_policy: None, + }; + state + .store + .put_policy_revision_atomic(&write) + .await + .map_err(|e| super::persistence_error_to_status(e, "write child policy"))?; + info!( + parent_id, + child_id, + version = write.version, + "copied parent policy into child sandbox" + ); + Ok(true) } -/// Direct admission replaces the grant lifecycle only for verified user -/// credentials and when no gateway extension observes or controls that lifecycle. -fn direct_ssh_available( +/// Under the parent's lock, check that a provider being attached to a child is +/// attached to its parent. +async fn check_parent_has_provider( state: &ServerState, - principal: &crate::auth::principal::Principal, -) -> bool { - use crate::auth::principal::Principal; - const CREATE_SSH: &str = "/openshell.v1.OpenShell/CreateSshSession"; - const REVOKE_SSH: &str = "/openshell.v1.OpenShell/RevokeSshSession"; - let authorized = match principal { - Principal::Operator(_) => true, - Principal::User(user) => { - user.identity.provider != IdentityProvider::LocalDev - && state.config.oidc.as_ref().is_none_or(|oidc| { - AuthzPolicy::from(oidc) - .check(&user.identity, CREATE_SSH) - .is_ok() - }) - } - _ => false, - }; - authorized - && state.gateway_interceptors.as_ref().is_none_or(|hooks| { - !hooks.should_intercept_path(CREATE_SSH) && !hooks.should_intercept_path(REVOKE_SSH) - }) + parent: &openshell_core::proto::SandboxParent, + provider: &str, +) -> Result<(), Status> { + let current = state + .store + .get_message::(&parent.id) + .await + .map_err(|e| Status::internal(format!("fetch parent sandbox failed: {e}")))?; + let attached = current + .as_ref() + .and_then(|current| current.spec.as_ref()) + .is_some_and(|spec| spec.providers.iter().any(|name| name == provider)); + if !attached { + return Err(Status::failed_precondition(format!( + "provider '{provider}' is not attached to parent '{}'", + parent.name + ))); + } + Ok(()) } -pub(super) async fn handle_get_sandbox( +async fn handle_create_sandbox_inner( state: &Arc, - request: Request, + request: Request, ) -> Result, Status> { let principal = super::extract_principal(&request)?; - let wants_owner = owner_requested(&request); - let req = request.into_inner(); - let sandbox = resolve_and_authorize_sandbox_name( - state, - &principal, - &req.name, - crate::auth::workspace_authz::selected_workspace_name(req.workspace_scope.as_ref())?, - MinWorkspaceRole::User, - ) - .await?; - let owner = if wants_owner { - crate::supervisor_session::owner_replica_id(state, sandbox.object_id()).await + let request = request.into_inner(); + let await_main_process_attachment = request.await_main_process_attachment; + let workload_template_name = request.workload_template.trim().to_string(); + + validate_create_sandbox_request_pre_io(&request, &workload_template_name)?; + + // `authorize_workspace` admits a sandbox caller to any workspace, so a + // sandbox caller's workspace comes from its own record instead. + let caller = match &principal { + crate::auth::principal::Principal::Sandbox(caller) => { + Some(sandbox_caller_create(state, caller, &request).await?) + } + _ => None, + }; + let workspace = match &caller { + Some(caller) => caller.object_workspace().to_string(), + None => { + authorize_workspace( + &state.store, + &state.admin_role, + &principal, + crate::auth::workspace_authz::selected_workspace_name( + request.workspace_scope.as_ref(), + )?, + MinWorkspaceRole::User, + ) + .await? + .workspace + } + }; + let workspace = super::workspace::resolve_workspace(state.store.as_ref(), &workspace) + .await? + .ensure_active()?; + + let (mut spec, created_from_workload_template) = if workload_template_name.is_empty() { + let spec = match &caller { + Some(caller) => spec_copied_from_caller( + caller, + request.spec.map(|spec| spec.providers).unwrap_or_default(), + ), + None => request + .spec + .ok_or_else(|| Status::invalid_argument("spec is required"))?, + }; + (spec, None) } else { - None + let governance_spec = request.spec.unwrap_or_default(); + let template = state + .store + .get_message_by_name::(&workspace, &workload_template_name) + .await + .map_err(|e| Status::internal(format!("fetch sandbox template failed: {e}")))?; + let template = match (template, &caller) { + (Some(template), Some(_)) => { + check_agent_usable_template(&template)?; + template + } + (Some(template), None) => template, + (None, Some(_)) => return Err(template_not_available(&workload_template_name)), + (None, None) => return Err(Status::not_found("sandbox template not found")), + }; + let provenance = SandboxWorkloadTemplateProvenance { + name: template.object_name().to_string(), + resource_version: template.get_resource_version().to_string(), + }; + let mut resolved = sandbox_spec_from_stored_workload_template(&template)?; + if let Some(caller) = &caller { + copy_isolation_from_caller(caller, resolved.template.get_or_insert_default()); + } + resolved.policy = governance_spec.policy; + resolved.providers = governance_spec.providers; + resolved.command = governance_spec.command; + resolved.tty = governance_spec.tty; + resolved.restart_policy = governance_spec.restart_policy; + (resolved, Some(provenance)) }; - let mut response = Response::new(SandboxResponse { - application_service_urls: HashMap::new(), - gateway_service_urls: HashMap::new(), - sandbox: Some(sandbox), - service_urls: HashMap::new(), - }); - if let Some(value) = owner.and_then(|owner| owner.parse().ok()) { - response - .metadata_mut() - .insert(openshell_core::replica_routing::OWNER_REPLICA_HEADER, value); - } - if direct_ssh_available(state, &principal) { - response.metadata_mut().insert( - DIRECT_SSH_HEADER, - tonic::metadata::MetadataValue::from_static("1"), - ); + + // Attachment identity belongs to the gateway. Accepting an epoch from a + // create request or workload template could revive stale installation proof. + spec.provider_attachment_epoch = uuid::Uuid::new_v4().to_string(); + if spec.restart_policy == SandboxRestartPolicy::Unspecified as i32 { + spec.restart_policy = SandboxRestartPolicy::Never as i32; } - Ok(response) -} -pub(super) async fn handle_list_sandboxes( - state: &Arc, - request: Request, -) -> Result, Status> { - let principal = super::extract_principal(&request)?; - let request = request.into_inner(); - let scope = authorize_list_workspace_selector( - &state.store, - &state.admin_role, - &principal, - request.workspace_scope.as_ref(), - MinWorkspaceRole::User, - ) - .await?; - if !request.label_selector.is_empty() { - crate::grpc::validation::validate_label_selector(&request.label_selector)?; + // Leave an omitted command empty rather than persisting a concrete shell: + // the sandbox boundary resolves the default login shell against the agent image + // (bash when present, otherwise /bin/sh on minimal images like Alpine), + // which the gateway cannot do since it does not see the sandbox filesystem. + // The default is an interactive login shell, so request a TTY. + if spec.command.is_empty() { + spec.tty = true; } - let workspace = if matches!(scope, AuthorizedWorkspaceScope::AllWorkspaces) { - None - } else { - let AuthorizedWorkspaceScope::Workspace(authz) = scope else { - unreachable!("all-workspaces scope handled above") - }; - let workspace = super::workspace::resolve_workspace(state.store.as_ref(), &authz.workspace) - .await? - .name; - Some(workspace) - }; - let scope_fingerprint = workspace.as_deref().unwrap_or("*"); - let pagination = Pagination::new( - request.page_size, - &request.page_token, - "ListSandboxes", - &[scope_fingerprint, &request.label_selector], - )?; - let after = pagination.object_cursor()?; - let query = match (workspace.as_deref(), request.label_selector.as_str()) { - (None, "") => ObjectListQuery::AllWorkspaces, - (None, selector) => ObjectListQuery::AllWorkspacesSelector(selector), - (Some(workspace), "") => ObjectListQuery::Workspace(workspace), - (Some(workspace), selector) => ObjectListQuery::WorkspaceSelector { - workspace, - label_selector: selector, - }, + + let parent = match &caller { + Some(caller) => Some(check_create_parent(caller, &mut spec)?), + None => resolve_create_parent(state, &workspace, &request.parent, &mut spec).await?, }; - let page = state - .store - .list_message_page::(query, after.as_ref(), pagination.page_size()) - .await - .map_err(|e| Status::internal(format!("list sandboxes failed: {e}")))?; - let next_page_token = pagination.next_object_token(page.next_cursor.as_ref()); - Ok(Response::new(ListSandboxesResponse { - sandboxes: page.messages, - next_page_token, - })) -} -pub(super) async fn handle_create_sandbox_template( - state: &Arc, - request: Request, -) -> Result, Status> { - let principal = super::extract_principal(&request)?; - let req = request.into_inner(); - let template = req - .template - .ok_or_else(|| Status::invalid_argument("template is required"))?; - let metadata = template.metadata.clone().unwrap_or_default(); - let authz = authorize_workspace( - &state.store, - &state.admin_role, - &principal, - crate::auth::workspace_authz::selected_workspace_name(req.workspace_scope.as_ref())?, - MinWorkspaceRole::Admin, - ) - .await?; - let workspace = super::workspace::resolve_workspace(state.store.as_ref(), &authz.workspace) - .await? - .ensure_active()?; - if !metadata.workspace.is_empty() && metadata.workspace != workspace { - return Err(Status::invalid_argument( - "template.metadata.workspace must match request workspace", - )); - } - if metadata.name.is_empty() { - return Err(Status::invalid_argument( - "template.metadata.name is required", - )); - } + // Validate field sizes before any create-side effects. + validate_sandbox_spec(&request.name, &spec)?; - let mut resolved = template; - resolved.metadata = Some(ObjectMeta { - id: uuid::Uuid::new_v4().to_string(), - name: metadata.name, - created_time: openshell_core::time::timestamp_from_millis(current_time_ms()).ok(), - labels: metadata.labels, - resource_version: 0, - annotations: metadata.annotations, - workspace: workspace.clone(), - deletion_time: None, - }); - validate_sandbox_workload_template(&resolved)?; - let spec = sandbox_spec_from_user_workload_template(&resolved)?; - state - .compute - .validate_caller_driver_config(spec.template.as_ref())?; + // A staging slot may only be redeemed by the caller it was issued to. This + // is the only point in the create path where the principal is in scope. + if let Some(token) = staging_token_in_spec(&spec, state.compute.configured_driver_name()) { + let subject = principal_subject(&principal)?; + state + .compute + .rootfs_tar_staging() + .authorize(&token, &workspace, &subject)?; + } - let labels_map = resolved.object_labels(); - let labels_json = if labels_map.as_ref().is_none_or(HashMap::is_empty) { - None + let id = uuid::Uuid::new_v4().to_string(); + let name = if request.name.is_empty() { + generate_routable_name() } else { - Some( - serde_json::to_string(&labels_map) - .map_err(|e| Status::internal(format!("failed to serialize labels: {e}")))?, - ) + request.name.clone() }; - let write = state - .store - .create_if_workspace_count_below( - SandboxWorkloadTemplate::object_type(), - resolved.object_id(), - resolved.object_name(), - &workspace, - &resolved.encode_to_vec(), - labels_json.as_deref(), - u64::from(MAX_TEMPLATES_PER_WORKSPACE), - ) - .await; - let write = match write { - Ok(Some(write)) => write, - Ok(None) => { - return Err(Status::resource_exhausted(format!( - "workspace has reached the maximum of {MAX_TEMPLATES_PER_WORKSPACE} sandbox templates" - ))); - } - Err(crate::persistence::PersistenceError::UniqueViolation { .. }) => { - return Err(Status::already_exists("sandbox template already exists")); - } - Err(err) => { - return Err(Status::internal(format!( - "persist sandbox template failed: {err}" - ))); + let guards = match &parent { + Some(parent) => { + state + .compute + .child_sandbox_create_guards(&workspace, &id, &parent.id) + .await } + None => state.compute.sandbox_create_guards(&workspace, &id).await, }; - if let Some(metadata) = resolved.metadata.as_mut() { - metadata.resource_version = write.resource_version; + let (sandbox_lifecycle_guard, mutation_guard) = guards + .map_err(|err| super::persistence_error_to_status(err, "acquire sandbox mutation lock"))?; + if let Some(parent) = &parent { + check_parent_has_room(state, &workspace, parent, &spec.providers).await?; + spec.policy = copy_parent_policy(state, parent) + .await? + .map(|copy| copy.policy); } - Ok(Response::new(SandboxTemplateResponse { - template: Some(resolved), - })) -} - -pub(super) async fn handle_get_sandbox_template( - state: &Arc, - request: Request, -) -> Result, Status> { - let principal = super::extract_principal(&request)?; - let req = request.into_inner(); - if req.name.is_empty() { - return Err(Status::invalid_argument("name is required")); + // Validate provider names exist (fail fast). + for name in &spec.providers { + state + .store + .get_message_by_name::(&workspace, name) + .await + .map_err(|e| Status::internal(format!("fetch provider failed: {e}")))? + .ok_or_else(|| Status::failed_precondition(format!("provider '{name}' not found")))?; } - let authz = authorize_workspace( - &state.store, - &state.admin_role, - &principal, - crate::auth::workspace_authz::selected_workspace_name(req.workspace_scope.as_ref())?, - MinWorkspaceRole::User, + let provider_profile_catalog = state + .provider_profile_sources + .snapshot_catalog(state.store.as_ref(), &workspace) + .await?; + super::provider::validate_provider_profiles_present( + state.store.as_ref(), + &provider_profile_catalog, + &workspace, + &spec.providers, ) .await?; - let workspace = super::workspace::resolve_workspace(state.store.as_ref(), &authz.workspace) - .await? - .name; - let template = state - .store - .get_message_by_name::(&workspace, &req.name) - .await - .map_err(|e| Status::internal(format!("fetch sandbox template failed: {e}")))? - .ok_or_else(|| Status::not_found("sandbox template not found"))?; - Ok(Response::new(SandboxTemplateResponse { - template: Some(template), - })) -} - -pub(super) async fn handle_list_sandbox_templates( - state: &Arc, - request: Request, -) -> Result, Status> { - let principal = super::extract_principal(&request)?; - let request = request.into_inner(); - let scope = authorize_list_workspace_selector( - &state.store, - &state.admin_role, - &principal, - request.workspace_scope.as_ref(), - MinWorkspaceRole::User, + validate_provider_environment_keys_unique_with_catalog( + state.store.as_ref(), + crate::provider_refresh::RefreshStateReader::Runtime(&state.refresh), + &provider_profile_catalog, + &workspace, + &spec.providers, ) .await?; - if !request.label_selector.is_empty() { - crate::grpc::validation::validate_label_selector(&request.label_selector)?; + + // Ensure the template always carries the resolved image. + let template = spec.template.get_or_insert_with(SandboxTemplate::default); + if template.image.trim().is_empty() { + template.image = state.compute.default_image().to_string(); } - let workspace = if matches!(scope, AuthorizedWorkspaceScope::AllWorkspaces) { - None - } else { - let AuthorizedWorkspaceScope::Workspace(authz) = scope else { - unreachable!("all-workspaces scope handled above") - }; - let workspace = super::workspace::resolve_workspace(state.store.as_ref(), &authz.workspace) - .await? - .name; - Some(workspace) - }; - let scope_fingerprint = workspace.as_deref().unwrap_or("*"); - let pagination = Pagination::new( - request.page_size, - &request.page_token, - "ListSandboxTemplates", - &[scope_fingerprint, &request.label_selector], - )?; - let after = pagination.object_cursor()?; - let query = match (workspace.as_deref(), request.label_selector.as_str()) { - (None, "") => ObjectListQuery::AllWorkspaces, - (None, selector) => ObjectListQuery::AllWorkspacesSelector(selector), - (Some(workspace), "") => ObjectListQuery::Workspace(workspace), - (Some(workspace), selector) => ObjectListQuery::WorkspaceSelector { - workspace, - label_selector: selector, - }, - }; - let page = state - .store - .list_message_page::(query, after.as_ref(), pagination.page_size()) - .await - .map_err(|e| Status::internal(format!("list sandbox templates failed: {e}")))?; - let next_page_token = pagination.next_object_token(page.next_cursor.as_ref()); - Ok(Response::new(ListSandboxTemplatesResponse { - templates: page.messages, - next_page_token, - })) -} -pub(super) async fn handle_delete_sandbox_template( - state: &Arc, - request: Request, -) -> Result, Status> { - let principal = super::extract_principal(&request)?; - let req = request.into_inner(); - if req.name.is_empty() { - return Err(Status::invalid_argument("name is required")); + if let Some(ref mut policy) = spec.policy { + super::policy::clear_provider_credentialed_markers(policy); + validate_no_reserved_provider_policy_keys(policy)?; + *policy = validate_and_canonicalize_policy(policy.clone())?; } - let authz = authorize_workspace( - &state.store, - &state.admin_role, - &principal, - crate::auth::workspace_authz::selected_workspace_name(req.workspace_scope.as_ref())?, - MinWorkspaceRole::Admin, - ) - .await?; - let workspace = super::workspace::resolve_workspace(state.store.as_ref(), &authz.workspace) - .await? - .name; - let deleted = state - .store - .delete_by_name( - SandboxWorkloadTemplate::object_type(), - &workspace, - &req.name, - ) - .await - .map_err(|e| Status::internal(format!("delete sandbox template failed: {e}")))?; - Ok(Response::new(DeleteSandboxTemplateResponse { - outcome: super::deletion_outcome(deleted, req.allow_missing, "sandbox template")?, - })) -} - -fn validate_sandbox_workload_template(template: &SandboxWorkloadTemplate) -> Result<(), Status> { - super::validation::validate_object_metadata(template.metadata.as_ref(), "sandbox_template")?; - let name = template.object_name().to_string(); - validate_dns1123_label(&name, "template.metadata.name")?; - validate_sandbox_workload_template_service_level(template)?; - let spec = sandbox_spec_from_user_workload_template(template)?; - validate_sandbox_spec(&name, &spec)?; - Ok(()) -} -fn validate_sandbox_workload_template_service_level( - template: &SandboxWorkloadTemplate, -) -> Result<(), Status> { - let Some(startup) = template - .spec - .as_ref() - .and_then(|spec| spec.desired_service_level.as_ref()) - .and_then(|service_level| service_level.startup.as_ref()) - else { - return Ok(()); - }; - if let Some(ready_within) = &startup.ready_within { - validate_positive_normalized_duration( - ready_within, - "template.spec.desired_service_level.startup.ready_within", - )?; - } - Ok(()) -} + // Process identity and MCP default materialization can increase the + // protobuf size. Recheck the exact canonical spec before any middleware or + // compute boundary can observe or persist it. The initial check remains + // above so requests that are already oversized still fail before I/O. + validate_sandbox_spec(&request.name, &spec)?; -fn validate_positive_normalized_duration( - duration: &prost_types::Duration, - field: &str, -) -> Result<(), Status> { - const MAX_DURATION_SECONDS: u64 = 315_576_000_000; - if duration.seconds.unsigned_abs() > MAX_DURATION_SECONDS - || duration.nanos.unsigned_abs() >= 1_000_000_000 - { - return Err(Status::invalid_argument(format!( - "{field} must be a valid protobuf Duration" - ))); - } - if (duration.seconds > 0 && duration.nanos < 0) || (duration.seconds < 0 && duration.nanos > 0) - { - return Err(Status::invalid_argument(format!( - "{field} must be a normalized protobuf Duration" - ))); - } - if duration.seconds < 0 || duration.nanos < 0 || (duration.seconds == 0 && duration.nanos == 0) - { - return Err(Status::invalid_argument(format!( - "{field} must be greater than zero" - ))); + if let Some(ref policy) = spec.policy { + validate_policy_safety(policy)?; + crate::middleware::validate_policy(state.middleware_registry.as_ref(), policy).await?; } - Ok(()) -} - -pub(super) async fn handle_list_sandbox_providers( - state: &Arc, - request: Request, -) -> Result, Status> { - let principal = super::extract_principal(&request)?; - let req = request.into_inner(); - let sandbox = resolve_and_authorize_sandbox_name( + super::policy::validate_candidate_sandbox_credential_policy( state, - &principal, - &req.sandbox, - crate::auth::workspace_authz::selected_workspace_name(req.workspace_scope.as_ref())?, - MinWorkspaceRole::User, + &workspace, + &spec.providers, + spec.policy.as_ref(), ) .await?; - let workspace = sandbox.object_workspace().to_string(); - let pagination = Pagination::new( - req.page_size, - &req.page_token, - "ListSandboxProviders", - &[&workspace, &req.sandbox], - )?; - let mut providers = providers_for_sandbox(state, &sandbox, &workspace) - .await? - .into_iter() - .map(|provider| { - let name = provider - .metadata - .as_ref() - .filter(|metadata| !metadata.name.is_empty()) - .map(|metadata| metadata.name.clone()) - .ok_or_else(|| Status::internal("provider metadata name is missing"))?; - Ok((name, provider)) - }) - .collect::, Status>>()?; - providers.sort_unstable_by(|left, right| left.0.cmp(&right.0)); - let start = pagination.provider_cursor()?.map_or(0, |cursor| { - providers.partition_point(|(name, _)| name.as_str() <= cursor) + + let now_ms = current_time_ms(); + + let mut sandbox = Sandbox { + host_key_fingerprint: String::new(), + metadata: Some(ObjectMeta { + id: id.clone(), + name: name.clone(), + created_time: openshell_core::time::timestamp_from_millis(now_ms).ok(), + labels: request.labels.clone(), + resource_version: 0, + annotations: request.annotations.clone(), + workspace, + deletion_time: None, + }), + spec: Some(spec), + status: None, + created_from_workload_template, + parent, + // Always the user: the one who made the request, or for a child + // created over MCP, the user its root was created on behalf of. + created_on_behalf_of: caller.as_ref().map_or_else( + || user_ref(&principal), + |root| root.created_on_behalf_of.clone(), + ), + }; + sandbox.set_phase(SandboxPhase::Provisioning as i32); + sandbox + .status + .get_or_insert_with(Default::default) + .configuration_admission = Some(openshell_core::proto::SandboxConfigurationAdmission { + state: openshell_core::proto::ConfigurationAdmissionState::Pending.into(), + ..Default::default() }); - let end = start - .saturating_add(usize::try_from(pagination.page_size()).expect("u32 fits in usize")) - .min(providers.len()); - let next_page_token = pagination - .next_provider_token((end < providers.len()).then(|| providers[end - 1].0.as_str())); - Ok(Response::new(ListSandboxProvidersResponse { - providers: providers - .into_iter() - .skip(start) - .take(end - start) - .map(|(_, provider)| provider) - .collect(), - next_page_token, - })) -} + sandbox + .status + .as_mut() + .expect("status initialized") + .configuration_activated = Some(false); + sandbox + .status + .as_mut() + .expect("status initialized") + .provisioning = Some( + crate::compute::provisioning_deadline::new_preparation_record( + now_ms, + state.config.image_preparation_timeout_seconds, + state.config.provisioning_repair_window_seconds * 1000, + ), + ); + crate::compute::provisioning_deadline::refresh_configuration( + &state.store, + &mut sandbox, + now_ms, + state.config.provisioning_repair_window_seconds * 1000, + ) + .await + .map_err(Status::internal)?; + crate::compute::apply_configuration_readiness(&mut sandbox); -pub(super) async fn handle_attach_sandbox_provider( - state: &Arc, - request: Request, -) -> Result, Status> { - let principal = super::extract_principal(&request)?; - #[cfg(test)] - let attach_wait_probe = request - .extensions() - .get::>() - .cloned(); - let request = request.into_inner(); - let sandbox = resolve_and_authorize_sandbox_name( + // Ensure metadata is valid (defense in depth - should always be true for server-constructed metadata) + super::validation::validate_object_metadata(sandbox.metadata.as_ref(), "sandbox")?; + super::policy::validate_candidate_provider_attachments( state, - &principal, - &request.sandbox, - crate::auth::workspace_authz::selected_workspace_name(request.workspace_scope.as_ref())?, - MinWorkspaceRole::User, + sandbox.object_workspace(), + &sandbox, + sandbox + .spec + .as_ref() + .map(|spec| spec.providers.as_slice()) + .unwrap_or_default(), ) .await?; - let workspace = - super::workspace::resolve_workspace(state.store.as_ref(), sandbox.object_workspace()) - .await? - .ensure_active()?; - if request.provider.is_empty() { - return Err(Status::invalid_argument("provider_name is required")); - } - // Validate provider name would not violate sandbox spec constraints if added - // (pre-validation ensures CAS mutations preserve invariants) - if request.provider.len() > super::MAX_NAME_LEN { - return Err(Status::invalid_argument(format!( - "provider_name exceeds maximum length ({} > {})", - request.provider.len(), - super::MAX_NAME_LEN - ))); - } + // Provider and policy reads must stay under the create mutation guard so + // their revisions cannot change before the sandbox's launch is committed. + let mut runtime_inputs = + super::policy::resolve_sandbox_create_runtime_inputs(state.as_ref(), &sandbox).await?; - // The receipt must capture the provider revision selected by this - // serialized mutation, after any preceding credential update has finished. - #[cfg(test)] - if let Some(probe) = attach_wait_probe { - probe.notify_one(); - } - let _mutation_guard = state + state .compute - .mutation_guard(MutationScope::sandbox( - sandbox.object_workspace(), - sandbox.object_id(), - )) - .await - .map_err(|err| super::persistence_error_to_status(err, "acquire sandbox mutation lock"))?; - let provider_record = get_provider_record(state.store.as_ref(), &workspace, &request.provider) + .validate_launch_signer_configured(state.sandbox_session_jwt_authority.is_some())?; + state + .compute + .validate_sandbox_create_with_runtime_inputs( + &sandbox, + &runtime_inputs, + await_main_process_attachment, + ) .await - .map_err(|err| { - if err.code() == tonic::Code::NotFound { - Status::failed_precondition(format!("provider '{}' not found", request.provider)) - } else { - err - } + .map_err(|status| { + warn!(error = %status, "Rejecting sandbox create request"); + status })?; - let sandbox_name = sandbox.object_name().to_string(); - let sandbox_id = sandbox - .metadata - .as_ref() - .ok_or_else(|| Status::internal("sandbox metadata is missing"))? - .id - .clone(); - - // Pre-check: fail fast if sandbox spec is missing (invariant violation) - let spec = sandbox - .spec - .as_ref() - .ok_or_else(|| Status::internal("sandbox spec is missing"))?; - // Pre-check: fail fast if already at MAX_PROVIDERS limit (avoid spurious CAS conflicts) - // Note: This is an optimization; the CAS closure rechecks after dedupe in case of races - if spec.providers.len() >= MAX_PROVIDERS - && !spec.providers.iter().any(|name| name == &request.provider) - { - return Err(Status::invalid_argument(format!( - "providers list exceeds maximum ({MAX_PROVIDERS})" - ))); - } - let mut candidate_spec = spec.clone(); - dedupe_provider_names(&mut candidate_spec.providers); - if !candidate_spec - .providers - .iter() - .any(|name| name == &request.provider) - { - candidate_spec.providers.push(request.provider.clone()); + let runtime_identity = crate::auth::sandbox_session::PersistedSandboxIdentity::new() + .map_err(|error| Status::internal(error.to_string()))?; + if let Some(metadata) = sandbox.metadata.as_mut() { + runtime_identity.write(&mut metadata.annotations); } - validate_sandbox_spec(&sandbox_name, &candidate_spec)?; - let provider_profile_catalog = state - .provider_profile_sources - .snapshot_catalog(state.store.as_ref(), &workspace) - .await?; - super::provider::validate_provider_profiles_present( - state.store.as_ref(), - &provider_profile_catalog, - &workspace, - &candidate_spec.providers, - ) - .await?; - validate_provider_environment_keys_unique_with_catalog( - state.store.as_ref(), - crate::provider_refresh::RefreshStateReader::Runtime(&state.refresh), - &provider_profile_catalog, - &workspace, - &candidate_spec.providers, - ) - .await?; - super::policy::validate_candidate_provider_attachments( - state, - &workspace, - &sandbox, - &candidate_spec.providers, - ) - .await?; - let current_policy = - super::policy::current_base_policy_for_sandbox(state.store.as_ref(), &sandbox).await?; - super::policy::validate_candidate_sandbox_credential_policy( - state, - &workspace, - &candidate_spec.providers, - Some(¤t_policy), - ) - .await?; - - let provider_name = request.provider.clone(); - let attached = Arc::new(AtomicBool::new(false)); - let attached_clone = attached.clone(); - let mutation_id = uuid::Uuid::new_v4().to_string(); - - let sandbox = update_sandbox_cas( - state, - &sandbox_id, - request.expected_resource_version, - |sandbox| { - attached_clone.store(false, Ordering::Relaxed); - let Some(ref mut spec) = sandbox.spec else { - // Spec should always exist post-creation; if missing, fail CAS to surface error - return; - }; + let launch_authentication = if let Some(authority) = &state.sandbox_session_jwt_authority { + Some(authority.mint_persisted_launch(&id, &runtime_identity)?) + } else { + None + }; + let sandbox_token = launch_authentication.as_ref().map(|authentication| { + authentication + .supervisor + .gateway_token + .expose_secret() + .to_string() + }); + let launch_authentication = launch_authentication + .map(|authentication| { + serde_json::to_vec(&authentication) + .map_err(|error| Status::internal(format!("encode launch authentication: {error}"))) + }) + .transpose()?; + runtime_inputs.launch_authentication = launch_authentication; - if spec.provider_attachment_epoch.is_empty() { - spec.provider_attachment_epoch.clone_from(&mutation_id); - } + let sandbox = Box::pin(state.compute.create_sandbox_with_runtime_inputs_and_guards( + sandbox, + sandbox_token, + await_main_process_attachment, + runtime_inputs, + sandbox_lifecycle_guard, + mutation_guard, + )) + .await?; - dedupe_provider_names(&mut spec.providers); - if !spec.providers.iter().any(|name| name == &provider_name) - && spec.providers.len() < MAX_PROVIDERS - { - spec.providers.push(provider_name.clone()); - spec.provider_attachment_epoch.clone_from(&mutation_id); - attached_clone.store(true, Ordering::Relaxed); - crate::compute::provisioning_deadline::attachments_changed( - sandbox, - current_time_ms(), - ); + let mut service_urls = HashMap::with_capacity(request.service_exposures.len()); + let mut application_service_urls = HashMap::new(); + let mut gateway_service_urls = HashMap::new(); + for exposure in &request.service_exposures { + let endpoint = match super::service::expose_service_endpoint( + state, + sandbox.object_workspace(), + &sandbox, + &exposure.service, + exposure.target_port, + super::service::validate_service_exposure_request( + &exposure.service, + exposure.target_port, + exposure.authorization_mode, + )?, + ServiceBackendHttpVersion::Unspecified, + ) + .await + { + Ok(endpoint) => endpoint, + Err(exposure_error) => { + let rollback = state + .compute + .delete_sandbox_by_id(sandbox.object_id(), sandbox.object_name()) + .await; + if let Err(rollback_error) = rollback { + warn!( + sandbox_id = %sandbox.object_id(), + sandbox_name = %sandbox.object_name(), + service_name = %exposure.service, + exposure_error = %exposure_error, + rollback_error = %rollback_error, + "Failed to roll back sandbox after service exposure failed" + ); + return Err(Status::internal(format!( + "create sandbox failed while exposing service '{}': {}; rollback failed: {}; sandbox '{}' may require manual deletion", + exposure.service, + exposure_error.message(), + rollback_error.message(), + sandbox.object_name(), + ))); + } + return Err(exposure_error); } - }, - ) - .await - .map_err(|e| super::persistence_error_to_status(e, "attach sandbox provider"))?; - - let attached = attached.load(Ordering::Relaxed); - if attached { - crate::config_delivery::publish_sandbox(state, &sandbox_id); - state.sandbox_watch_bus.notify(&sandbox_id); + }; + let endpoint = endpoint.into_inner(); + if !endpoint.application_url.is_empty() { + application_service_urls.insert(exposure.service.clone(), endpoint.application_url); + } + if !endpoint.gateway_url.is_empty() { + gateway_service_urls.insert(exposure.service.clone(), endpoint.gateway_url); + } + service_urls.insert(exposure.service.clone(), endpoint.url); } - let receipt = super::provider_readiness::record_provider_mutation( - state, - &sandbox, - &request.provider, - ProviderMutationKind::Attach, - Some(( - provider_record.object_id(), - provider_record.get_resource_version(), - )), - &mutation_id, - ) - .await?; info!( - sandbox_name = %sandbox_name, - provider_name = %request.provider, - attached, - "AttachSandboxProvider request completed successfully" + sandbox_id = %id, + sandbox_name = %name, + "CreateSandbox request completed successfully" ); - - Ok(Response::new(AttachSandboxProviderResponse { + Ok(Response::new(SandboxResponse { + application_service_urls, + gateway_service_urls, sandbox: Some(sandbox), - attached, - receipt: Some(receipt), + service_urls, })) } -pub(super) async fn handle_detach_sandbox_provider( - state: &Arc, - request: Request, -) -> Result, Status> { - let principal = super::extract_principal(&request)?; - let request = request.into_inner(); - let sandbox = resolve_and_authorize_sandbox_name( - state, - &principal, - &request.sandbox, - crate::auth::workspace_authz::selected_workspace_name(request.workspace_scope.as_ref())?, - MinWorkspaceRole::User, - ) - .await?; - let workspace = sandbox.object_workspace().to_string(); - if request.provider.is_empty() { - return Err(Status::invalid_argument("provider_name is required")); - } +fn validate_create_sandbox_request_pre_io( + request: &CreateSandboxRequest, + workload_template_name: &str, +) -> Result<(), Status> { + // Validate labels (keys and values must meet Kubernetes requirements). + crate::grpc::validation::validate_labels(&request.labels)?; + crate::grpc::validation::validate_caller_annotations(&request.annotations, "annotations")?; - // Validate provider name (pre-validation ensures CAS mutations preserve invariants) - if request.provider.len() > super::MAX_NAME_LEN { + if request.service_exposures.len() > MAX_CREATE_SERVICE_EXPOSURES { return Err(Status::invalid_argument(format!( - "provider_name exceeds maximum length ({} > {})", - request.provider.len(), - super::MAX_NAME_LEN + "service_exposures must contain at most {MAX_CREATE_SERVICE_EXPOSURES} entries" ))); } + let mut service_names = HashSet::with_capacity(request.service_exposures.len()); + for exposure in &request.service_exposures { + super::service::validate_service_exposure_request( + &exposure.service, + exposure.target_port, + exposure.authorization_mode, + )?; + if !service_names.insert(exposure.service.as_str()) { + return Err(Status::invalid_argument(format!( + "duplicate service exposure name: '{}'", + exposure.service + ))); + } + } - let _mutation_guard = state - .compute - .mutation_guard(MutationScope::sandbox( - sandbox.object_workspace(), - sandbox.object_id(), - )) - .await - .map_err(|err| super::persistence_error_to_status(err, "acquire sandbox mutation lock"))?; - let sandbox_name = sandbox.object_name().to_string(); - let sandbox_id = sandbox - .metadata - .as_ref() - .ok_or_else(|| Status::internal("sandbox metadata is missing"))? - .id - .clone(); - - // Pre-check: fail fast if sandbox spec is missing (invariant violation) - let spec = sandbox - .spec - .as_ref() - .ok_or_else(|| Status::internal("sandbox spec is missing"))?; - let mut candidate_spec = spec.clone(); - candidate_spec - .providers - .retain(|name| name != &request.provider); - dedupe_provider_names(&mut candidate_spec.providers); - super::policy::validate_candidate_provider_attachments( - state, - &workspace, - &sandbox, - &candidate_spec.providers, - ) - .await?; - - let provider_name = request.provider.clone(); - let detached = Arc::new(AtomicBool::new(false)); - let detached_clone = detached.clone(); - let mutation_id = uuid::Uuid::new_v4().to_string(); - - let sandbox = update_sandbox_cas( - state, - &sandbox_id, - request.expected_resource_version, - |sandbox| { - detached_clone.store(false, Ordering::Relaxed); - let Some(ref mut spec) = sandbox.spec else { - // Spec should always exist post-creation; if missing, fail CAS to surface error - return; - }; - - if spec.provider_attachment_epoch.is_empty() { - spec.provider_attachment_epoch.clone_from(&mutation_id); - } + if workload_template_name.is_empty() { + let spec = request + .spec + .as_ref() + .ok_or_else(|| Status::invalid_argument("spec is required"))?; + return validate_sandbox_spec(&request.name, spec); + } - let before_len = spec.providers.len(); - spec.providers.retain(|name| name != &provider_name); - if spec.providers.len() != before_len { - spec.provider_attachment_epoch.clone_from(&mutation_id); - detached_clone.store(true, Ordering::Relaxed); - // Only dedupe after making a change - dedupe_provider_names(&mut spec.providers); - crate::compute::provisioning_deadline::attachments_changed( - sandbox, - current_time_ms(), - ); - } - }, - ) - .await - .map_err(|e| super::persistence_error_to_status(e, "detach sandbox provider"))?; + validate_dns1123_label(workload_template_name, "workload_template_name")?; + if let Some(spec) = request.spec.as_ref() { + validate_template_create_governance_spec(spec)?; + validate_sandbox_governance_spec(&request.name, spec)?; + } else { + validate_sandbox_governance_spec(&request.name, &SandboxSpec::default())?; + } + Ok(()) +} - let detached = detached.load(Ordering::Relaxed); - if detached { - crate::config_delivery::publish_sandbox(state, &sandbox_id); - state.sandbox_watch_bus.notify(&sandbox_id); +fn validate_template_create_governance_spec(spec: &SandboxSpec) -> Result<(), Status> { + if !spec.log_level.is_empty() { + return Err(Status::invalid_argument( + "spec.log_level cannot be set when workload_template_name is set", + )); } - let receipt = super::provider_readiness::record_provider_mutation( - state, - &sandbox, - &request.provider, - ProviderMutationKind::Detach, - None, - &mutation_id, - ) - .await?; + if !spec.environment.is_empty() { + return Err(Status::invalid_argument( + "spec.environment cannot be set when workload_template_name is set", + )); + } + if spec.template.is_some() { + return Err(Status::invalid_argument( + "spec.template cannot be set when workload_template_name is set", + )); + } + if spec.resource_requirements.is_some() { + return Err(Status::invalid_argument( + "spec.resource_requirements cannot be set when workload_template_name is set", + )); + } + Ok(()) +} - info!( - sandbox_name = %sandbox_name, - provider_name = %request.provider, - detached, - "DetachSandboxProvider request completed successfully" - ); +fn sandbox_spec_from_stored_workload_template( + template: &SandboxWorkloadTemplate, +) -> Result { + sandbox_spec_from_workload_template(template, tonic::Code::Internal) +} - Ok(Response::new(DetachSandboxProviderResponse { - sandbox: Some(sandbox), - detached, - receipt: Some(receipt), - })) +fn sandbox_spec_from_user_workload_template( + template: &SandboxWorkloadTemplate, +) -> Result { + sandbox_spec_from_workload_template(template, tonic::Code::InvalidArgument) } -pub(super) async fn handle_delete_sandbox( - state: &Arc, - request: Request, -) -> Result, Status> { - let result = handle_delete_sandbox_inner(state, request).await; - let outcome = match &result { - Ok(_) => TelemetryOutcome::Success, - _ => TelemetryOutcome::Failure, - }; - openshell_core::telemetry::emit_lifecycle( - LifecycleResource::Sandbox, - LifecycleOperation::Delete, - outcome, - ); - result +fn sandbox_spec_from_workload_template( + template: &SandboxWorkloadTemplate, + missing_field_code: tonic::Code, +) -> Result { + let spec = template + .spec + .as_ref() + .ok_or_else(|| Status::new(missing_field_code, "sandbox template spec is required"))?; + let workload = spec + .workload + .as_ref() + .ok_or_else(|| Status::new(missing_field_code, "sandbox template workload is required"))?; + let resources = workload.resources.as_ref(); + Ok(SandboxSpec { + environment: workload.environment.clone(), + template: Some(SandboxTemplate { + image: workload.image.clone(), + resources: resources.and_then(template_resource_struct), + driver_config: spec.driver_config.clone(), + ..SandboxTemplate::default() + }), + resource_requirements: resources.and_then(template_gpu_requirements), + ..SandboxSpec::default() + }) } -async fn handle_delete_sandbox_inner( - state: &Arc, - request: Request, -) -> Result, Status> { - let principal = super::extract_principal(&request)?; - let req = request.into_inner(); - let name = req.name; - if name.is_empty() { - return Err(Status::invalid_argument("sandbox is required")); +fn template_gpu_requirements(resources: &SandboxResources) -> Option { + Some(ResourceRequirements { + gpu: Some(resources.gpu?), + }) +} + +fn template_resource_struct(resources: &SandboxResources) -> Option { + let mut limits = std::collections::BTreeMap::new(); + if !resources.cpu.is_empty() { + limits.insert( + "cpu".to_string(), + Value { + kind: Some(Kind::StringValue(resources.cpu.clone())), + }, + ); } - let authz = authorize_workspace( - &state.store, - &state.admin_role, - &principal, - crate::auth::workspace_authz::selected_workspace_name(req.workspace_scope.as_ref())?, - MinWorkspaceRole::User, - ) - .await - .map_err(|status| { - if status.code() == tonic::Code::PermissionDenied { - Status::not_found("sandbox not found") - } else { - status - } - })?; - 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(); - let result = state - .compute - .delete_sandbox_allow_missing_with_preconditions( - &workspace, - &name, - req.allow_missing, - preconditions, - ) - .await?; - if !result.sandbox_id.is_empty() { - state.telemetry.end_sandbox_session(&result.sandbox_id); + if !resources.memory.is_empty() { + limits.insert( + "memory".to_string(), + Value { + kind: Some(Kind::StringValue(resources.memory.clone())), + }, + ); + } + if limits.is_empty() { + None + } else { + let mut fields = std::collections::BTreeMap::new(); + fields.insert( + "limits".to_string(), + Value { + kind: Some(Kind::StructValue(Struct { fields: limits })), + }, + ); + Some(Struct { fields }) } - info!(sandbox_name = %name, "DeleteSandbox request completed successfully"); - Ok(Response::new(DeleteSandboxResponse { - outcome: result.outcome.into(), - sandbox_id: result.sandbox_id, - })) } -pub(super) async fn handle_stop_sandbox( - state: &Arc, - request: Request, -) -> Result, Status> { - let result = handle_stop_sandbox_inner(state, request).await; - openshell_core::telemetry::emit_lifecycle( - LifecycleResource::Sandbox, - LifecycleOperation::Stop, - if result.is_ok() { - TelemetryOutcome::Success - } else { - TelemetryOutcome::Failure - }, - ); - result +fn owner_requested(request: &Request) -> bool { + request + .metadata() + .contains_key(openshell_core::replica_routing::OWNER_REQUEST_HEADER) } -async fn handle_stop_sandbox_inner( +/// Direct admission replaces the grant lifecycle only for verified user +/// credentials and when no gateway extension observes or controls that lifecycle. +fn direct_ssh_available( + state: &ServerState, + principal: &crate::auth::principal::Principal, +) -> bool { + use crate::auth::principal::Principal; + const CREATE_SSH: &str = "/openshell.v1.OpenShell/CreateSshSession"; + const REVOKE_SSH: &str = "/openshell.v1.OpenShell/RevokeSshSession"; + let authorized = match principal { + Principal::Operator(_) => true, + Principal::User(user) => { + user.identity.provider != IdentityProvider::LocalDev + && state.config.oidc.as_ref().is_none_or(|oidc| { + AuthzPolicy::from(oidc) + .check(&user.identity, CREATE_SSH) + .is_ok() + }) + } + _ => false, + }; + authorized + && state.gateway_interceptors.as_ref().is_none_or(|hooks| { + !hooks.should_intercept_path(CREATE_SSH) && !hooks.should_intercept_path(REVOKE_SSH) + }) +} + +pub(super) async fn handle_get_sandbox( state: &Arc, - request: Request, + request: Request, ) -> Result, Status> { let principal = super::extract_principal(&request)?; + let wants_owner = owner_requested(&request); let req = request.into_inner(); - let resolved = resolve_and_authorize_sandbox_name( + let sandbox = resolve_and_authorize_sandbox_name( state, &principal, &req.name, @@ -1928,279 +1924,519 @@ async fn handle_stop_sandbox_inner( MinWorkspaceRole::User, ) .await?; - let workspace = resolved.object_workspace(); - let name = resolved.object_name(); - let sandbox = state.compute.stop_sandbox(workspace, name).await?; - info!(sandbox_name = %name, "StopSandbox request completed successfully"); - Ok(Response::new(SandboxResponse { + let owner = if wants_owner { + crate::supervisor_session::owner_replica_id(state, sandbox.object_id()).await + } else { + None + }; + let mut response = Response::new(SandboxResponse { application_service_urls: HashMap::new(), gateway_service_urls: HashMap::new(), sandbox: Some(sandbox), service_urls: HashMap::new(), - })) + }); + if let Some(value) = owner.and_then(|owner| owner.parse().ok()) { + response + .metadata_mut() + .insert(openshell_core::replica_routing::OWNER_REPLICA_HEADER, value); + } + if direct_ssh_available(state, &principal) { + response.metadata_mut().insert( + DIRECT_SSH_HEADER, + tonic::metadata::MetadataValue::from_static("1"), + ); + } + Ok(response) } -pub(super) async fn handle_start_sandbox( +pub(super) async fn handle_list_sandboxes( state: &Arc, - request: Request, -) -> Result, Status> { - let result = handle_start_sandbox_inner(state, request).await; - openshell_core::telemetry::emit_lifecycle( - LifecycleResource::Sandbox, - LifecycleOperation::Start, - if result.is_ok() { - TelemetryOutcome::Success + request: Request, +) -> Result, Status> { + let principal = super::extract_principal(&request)?; + let request = request.into_inner(); + if !request.label_selector.is_empty() { + crate::grpc::validation::validate_label_selector(&request.label_selector)?; + } + let lists_children = !request.parent.is_empty() + || matches!(principal, crate::auth::principal::Principal::Sandbox(_)); + if lists_children { + ensure_child_sandboxes_enabled(state)?; + } + let (workspace, parent_id) = + if let crate::auth::principal::Principal::Sandbox(caller) = &principal { + // A sandbox caller (only through `/mcp`) lists its own children, in + // its own workspace, whatever scope or parent the request names. + let caller = state + .store + .get_message::(&caller.sandbox_id) + .await + .map_err(|e| Status::internal(format!("fetch sandbox failed: {e}")))? + .ok_or_else(|| Status::not_found("sandbox not found"))?; + ( + Some(caller.object_workspace().to_string()), + Some(caller.object_id().to_string()), + ) } else { - TelemetryOutcome::Failure + let scope = authorize_list_workspace_selector( + &state.store, + &state.admin_role, + &principal, + request.workspace_scope.as_ref(), + MinWorkspaceRole::User, + ) + .await?; + let workspace = if matches!(scope, AuthorizedWorkspaceScope::AllWorkspaces) { + None + } else { + let AuthorizedWorkspaceScope::Workspace(authz) = scope else { + unreachable!("all-workspaces scope handled above") + }; + let workspace = + super::workspace::resolve_workspace(state.store.as_ref(), &authz.workspace) + .await? + .name; + Some(workspace) + }; + // Names are unique only within a workspace, so the parent is resolved + // there, once, and filtered on by id. + let parent_id = if request.parent.is_empty() { + None + } else { + let Some(workspace) = workspace.as_deref() else { + return Err(Status::invalid_argument( + "a parent filter needs a single workspace", + )); + }; + let parent = state + .store + .get_message_by_name::(workspace, &request.parent) + .await + .map_err(|e| Status::internal(format!("fetch parent sandbox failed: {e}")))? + .ok_or_else(|| { + Status::not_found(format!("parent sandbox '{}' not found", request.parent)) + })?; + Some(parent.object_id().to_string()) + }; + (workspace, parent_id) + }; + let scope_fingerprint = workspace.as_deref().unwrap_or("*"); + // The parent's id, not its name, so a token stops working if the parent + // is deleted and a new sandbox takes its name. + let mut fingerprint = vec![scope_fingerprint, request.label_selector.as_str()]; + if let Some(parent_id) = parent_id.as_deref() { + fingerprint.push(parent_id); + } + let pagination = Pagination::new( + request.page_size, + &request.page_token, + "ListSandboxes", + &fingerprint, + )?; + let after = pagination.object_cursor()?; + let query = match (workspace.as_deref(), request.label_selector.as_str()) { + (None, "") => ObjectListQuery::AllWorkspaces, + (None, selector) => ObjectListQuery::AllWorkspacesSelector(selector), + (Some(workspace), "") => ObjectListQuery::Workspace(workspace), + (Some(workspace), selector) => ObjectListQuery::WorkspaceSelector { + workspace, + label_selector: selector, }, - ); - result + }; + if let Some(parent_id) = parent_id { + let (sandboxes, next_cursor) = + list_children_page(state, query, after, pagination.page_size(), &parent_id).await?; + return Ok(Response::new(ListSandboxesResponse { + sandboxes, + next_page_token: pagination.next_object_token(next_cursor.as_ref()), + })); + } + let page = state + .store + .list_message_page::(query, after.as_ref(), pagination.page_size()) + .await + .map_err(|e| Status::internal(format!("list sandboxes failed: {e}")))?; + let next_page_token = pagination.next_object_token(page.next_cursor.as_ref()); + Ok(Response::new(ListSandboxesResponse { + sandboxes: page.messages, + next_page_token, + })) } -async fn handle_start_sandbox_inner( +/// Fill one response page with a parent's children, reading as many store +/// pages as needed. When the response fills partway through a store page, +/// the next cursor is the last record read, so the next page starts right +/// after it instead of skipping the rest of that store page. +async fn list_children_page( + state: &ServerState, + query: ObjectListQuery<'_>, + mut after: Option, + page_size: u32, + parent_id: &str, +) -> Result<(Vec, Option), Status> { + let limit = page_size as usize; + let mut children = Vec::new(); + loop { + let page = state + .store + .list_object_page(Sandbox::object_type(), query, after.as_ref(), page_size) + .await + .map_err(|e| Status::internal(format!("list sandboxes failed: {e}")))?; + let read = page.records.len(); + for (index, record) in page.records.into_iter().enumerate() { + let cursor = crate::persistence::ObjectCursor::from(&record); + let sandbox: Sandbox = crate::persistence::decode_record(record) + .map_err(|e| Status::internal(format!("list sandboxes failed: {e}")))?; + if sandbox + .parent + .as_ref() + .is_some_and(|parent| parent.id == parent_id) + { + children.push(sandbox); + } + if children.len() == limit && index + 1 < read { + return Ok((children, Some(cursor))); + } + } + match page.next_cursor { + Some(cursor) if children.len() < limit => after = Some(cursor), + next_cursor => return Ok((children, next_cursor)), + } + } +} + +pub(super) async fn handle_create_sandbox_template( state: &Arc, - request: Request, -) -> Result, Status> { + request: Request, +) -> Result, Status> { let principal = super::extract_principal(&request)?; let req = request.into_inner(); - let resolved = resolve_and_authorize_sandbox_name( - state, + let template = req + .template + .ok_or_else(|| Status::invalid_argument("template is required"))?; + let metadata = template.metadata.clone().unwrap_or_default(); + let authz = authorize_workspace( + &state.store, + &state.admin_role, &principal, - &req.name, crate::auth::workspace_authz::selected_workspace_name(req.workspace_scope.as_ref())?, - MinWorkspaceRole::User, + MinWorkspaceRole::Admin, ) .await?; - if let Some(policy) = resolved.spec.as_ref().and_then(|spec| spec.policy.as_ref()) { - require_gateway_cedar_support(policy)?; + let workspace = super::workspace::resolve_workspace(state.store.as_ref(), &authz.workspace) + .await? + .ensure_active()?; + if !metadata.workspace.is_empty() && metadata.workspace != workspace { + return Err(Status::invalid_argument( + "template.metadata.workspace must match request workspace", + )); } - let workspace = resolved.object_workspace().to_string(); - let name = resolved.object_name().to_string(); - let mut sandbox = state + if metadata.name.is_empty() { + return Err(Status::invalid_argument( + "template.metadata.name is required", + )); + } + + let mut resolved = template; + resolved.metadata = Some(ObjectMeta { + id: uuid::Uuid::new_v4().to_string(), + name: metadata.name, + created_time: openshell_core::time::timestamp_from_millis(current_time_ms()).ok(), + labels: metadata.labels, + resource_version: 0, + annotations: metadata.annotations, + workspace: workspace.clone(), + deletion_time: None, + }); + validate_sandbox_workload_template(&resolved)?; + let spec = sandbox_spec_from_user_workload_template(&resolved)?; + state .compute - .start_sandbox_authenticated( + .validate_caller_driver_config(spec.template.as_ref())?; + + let labels_map = resolved.object_labels(); + let labels_json = if labels_map.as_ref().is_none_or(HashMap::is_empty) { + None + } else { + Some( + serde_json::to_string(&labels_map) + .map_err(|e| Status::internal(format!("failed to serialize labels: {e}")))?, + ) + }; + let write = state + .store + .create_if_workspace_count_below( + SandboxWorkloadTemplate::object_type(), + resolved.object_id(), + resolved.object_name(), &workspace, - &name, - state.sandbox_session_jwt_authority.as_deref(), + &resolved.encode_to_vec(), + labels_json.as_deref(), + u64::from(MAX_TEMPLATES_PER_WORKSPACE), ) - .await?; - let remote_authority = - crate::supervisor_session::remote_supervisor_owner(state, sandbox.object_id()) - .await? - .is_some(); - state - .supervisor_sessions - .project_endpoint_status(&mut sandbox, remote_authority); - info!(sandbox_name = %name, "StartSandbox request completed successfully"); - Ok(Response::new(SandboxResponse { - application_service_urls: HashMap::new(), - gateway_service_urls: HashMap::new(), - sandbox: Some(sandbox), - service_urls: HashMap::new(), - })) -} + .await; + let write = match write { + Ok(Some(write)) => write, + Ok(None) => { + return Err(Status::resource_exhausted(format!( + "workspace has reached the maximum of {MAX_TEMPLATES_PER_WORKSPACE} sandbox templates" + ))); + } + Err(crate::persistence::PersistenceError::UniqueViolation { .. }) => { + return Err(Status::already_exists("sandbox template already exists")); + } + Err(err) => { + return Err(Status::internal(format!( + "persist sandbox template failed: {err}" + ))); + } + }; + if let Some(metadata) = resolved.metadata.as_mut() { + metadata.resource_version = write.resource_version; + } -pub(super) async fn handle_suspend_sandbox( - state: &Arc, - request: Request, -) -> Result, Status> { - let result = handle_suspend_sandbox_inner(state, request).await; - openshell_core::telemetry::emit_lifecycle( - LifecycleResource::Sandbox, - LifecycleOperation::Suspend, - if result.is_ok() { - TelemetryOutcome::Success - } else { - TelemetryOutcome::Failure - }, - ); - result + Ok(Response::new(SandboxTemplateResponse { + template: Some(resolved), + })) } -async fn handle_suspend_sandbox_inner( +pub(super) async fn handle_get_sandbox_template( state: &Arc, - request: Request, -) -> Result, Status> { + request: Request, +) -> Result, Status> { let principal = super::extract_principal(&request)?; let req = request.into_inner(); - let resolved = resolve_and_authorize_sandbox_name( - state, + if req.name.is_empty() { + return Err(Status::invalid_argument("name is required")); + } + let authz = authorize_workspace( + &state.store, + &state.admin_role, &principal, - &req.name, crate::auth::workspace_authz::selected_workspace_name(req.workspace_scope.as_ref())?, MinWorkspaceRole::User, ) .await?; - let workspace = resolved.object_workspace(); - let name = resolved.object_name(); - let sandbox = state.compute.suspend_sandbox(workspace, name).await?; - info!(sandbox_name = %name, "SuspendSandbox request completed successfully"); - Ok(Response::new(SandboxResponse { - application_service_urls: HashMap::new(), - gateway_service_urls: HashMap::new(), - sandbox: Some(sandbox), - service_urls: HashMap::new(), + let workspace = super::workspace::resolve_workspace(state.store.as_ref(), &authz.workspace) + .await? + .name; + let template = state + .store + .get_message_by_name::(&workspace, &req.name) + .await + .map_err(|e| Status::internal(format!("fetch sandbox template failed: {e}")))? + .ok_or_else(|| Status::not_found("sandbox template not found"))?; + Ok(Response::new(SandboxTemplateResponse { + template: Some(template), })) } -pub(super) async fn handle_resume_sandbox( +pub(super) async fn handle_list_sandbox_templates( state: &Arc, - request: Request, -) -> Result, Status> { - let result = handle_resume_sandbox_inner(state, request).await; - openshell_core::telemetry::emit_lifecycle( - LifecycleResource::Sandbox, - LifecycleOperation::Resume, - if result.is_ok() { - TelemetryOutcome::Success - } else { - TelemetryOutcome::Failure + request: Request, +) -> Result, Status> { + let principal = super::extract_principal(&request)?; + let request = request.into_inner(); + if let crate::auth::principal::Principal::Sandbox(caller) = &principal { + return list_agent_templates(state, &caller.sandbox_id).await; + } + let scope = authorize_list_workspace_selector( + &state.store, + &state.admin_role, + &principal, + request.workspace_scope.as_ref(), + MinWorkspaceRole::User, + ) + .await?; + if !request.label_selector.is_empty() { + crate::grpc::validation::validate_label_selector(&request.label_selector)?; + } + let workspace = if matches!(scope, AuthorizedWorkspaceScope::AllWorkspaces) { + None + } else { + let AuthorizedWorkspaceScope::Workspace(authz) = scope else { + unreachable!("all-workspaces scope handled above") + }; + let workspace = super::workspace::resolve_workspace(state.store.as_ref(), &authz.workspace) + .await? + .name; + Some(workspace) + }; + let scope_fingerprint = workspace.as_deref().unwrap_or("*"); + let pagination = Pagination::new( + request.page_size, + &request.page_token, + "ListSandboxTemplates", + &[scope_fingerprint, &request.label_selector], + )?; + let after = pagination.object_cursor()?; + let query = match (workspace.as_deref(), request.label_selector.as_str()) { + (None, "") => ObjectListQuery::AllWorkspaces, + (None, selector) => ObjectListQuery::AllWorkspacesSelector(selector), + (Some(workspace), "") => ObjectListQuery::Workspace(workspace), + (Some(workspace), selector) => ObjectListQuery::WorkspaceSelector { + workspace, + label_selector: selector, }, - ); - result + }; + let page = state + .store + .list_message_page::(query, after.as_ref(), pagination.page_size()) + .await + .map_err(|e| Status::internal(format!("list sandbox templates failed: {e}")))?; + let next_page_token = pagination.next_object_token(page.next_cursor.as_ref()); + Ok(Response::new(ListSandboxTemplatesResponse { + templates: page.messages, + next_page_token, + })) } -async fn handle_resume_sandbox_inner( +/// Most templates a sandbox caller is shown; MCP puts every name into the +/// `create_sandbox` tool, so the list stays short. +const MAX_AGENT_TEMPLATES: u32 = 50; + +/// A sandbox caller (only through `/mcp`) sees the templates it may create +/// children from, in its own workspace, whatever scope or selector the request +/// names, and without their environment. +async fn list_agent_templates( + state: &ServerState, + caller_id: &str, +) -> Result, Status> { + let caller = state + .store + .get_message::(caller_id) + .await + .map_err(|e| Status::internal(format!("fetch sandbox failed: {e}")))? + .ok_or_else(|| Status::not_found("sandbox not found"))?; + let selector = format!("{AGENT_USABLE_TEMPLATE_LABEL}=true"); + let page = state + .store + .list_message_page::( + ObjectListQuery::WorkspaceSelector { + workspace: caller.object_workspace(), + label_selector: &selector, + }, + None, + MAX_AGENT_TEMPLATES, + ) + .await + .map_err(|e| Status::internal(format!("list sandbox templates failed: {e}")))?; + let templates = page + .messages + .into_iter() + .filter(|template| check_agent_usable_template(template).is_ok()) + .map(|mut template| { + if let Some(workload) = template + .spec + .as_mut() + .and_then(|spec| spec.workload.as_mut()) + { + workload.environment.clear(); + } + template + }) + .collect(); + Ok(Response::new(ListSandboxTemplatesResponse { + templates, + next_page_token: String::new(), + })) +} + +pub(super) async fn handle_delete_sandbox_template( state: &Arc, - request: Request, -) -> Result, Status> { + request: Request, +) -> Result, Status> { let principal = super::extract_principal(&request)?; let req = request.into_inner(); - let resolved = resolve_and_authorize_sandbox_name( - state, + if req.name.is_empty() { + return Err(Status::invalid_argument("name is required")); + } + let authz = authorize_workspace( + &state.store, + &state.admin_role, &principal, - &req.name, crate::auth::workspace_authz::selected_workspace_name(req.workspace_scope.as_ref())?, - MinWorkspaceRole::User, + MinWorkspaceRole::Admin, ) .await?; - if let Some(policy) = resolved.spec.as_ref().and_then(|spec| spec.policy.as_ref()) { - require_gateway_cedar_support(policy)?; - } - let workspace = resolved.object_workspace().to_string(); - let name = resolved.object_name().to_string(); - let mut sandbox = state - .compute - .resume_sandbox_authenticated( + let workspace = super::workspace::resolve_workspace(state.store.as_ref(), &authz.workspace) + .await? + .name; + let deleted = state + .store + .delete_by_name( + SandboxWorkloadTemplate::object_type(), &workspace, - &name, - req.restart_if_restore_fails, - state.sandbox_session_jwt_authority.as_deref(), + &req.name, ) - .await?; - let remote_authority = - crate::supervisor_session::remote_supervisor_owner(state, sandbox.object_id()) - .await? - .is_some(); - state - .supervisor_sessions - .project_endpoint_status(&mut sandbox, remote_authority); - info!(sandbox_name = %name, "ResumeSandbox request completed successfully"); - Ok(Response::new(SandboxResponse { - application_service_urls: HashMap::new(), - gateway_service_urls: HashMap::new(), - sandbox: Some(sandbox), - service_urls: HashMap::new(), + .await + .map_err(|e| Status::internal(format!("delete sandbox template failed: {e}")))?; + Ok(Response::new(DeleteSandboxTemplateResponse { + outcome: super::deletion_outcome(deleted, req.allow_missing, "sandbox template")?, })) } -pub async fn mint_persisted_authentication( - state: &ServerState, - sandbox: &Sandbox, -) -> Result { - let authority = state - .sandbox_session_jwt_authority - .as_ref() - .ok_or_else(|| Status::failed_precondition("sandbox session authority is unavailable"))?; - let metadata = sandbox - .metadata - .as_ref() - .ok_or_else(|| Status::failed_precondition("sandbox metadata is missing"))?; - let identity = - crate::auth::sandbox_session::PersistedSandboxIdentity::read(&metadata.annotations) - .map_err(|error| Status::failed_precondition(error.to_string()))?; - let mut authentication = authority.mint_persisted_launch(sandbox.object_id(), &identity)?; - let mut with_identity = sandbox.clone(); - state - .compute - .prepare_ssh_identity(&mut with_identity, &mut authentication) - .await?; - Ok(authentication) +fn validate_sandbox_workload_template(template: &SandboxWorkloadTemplate) -> Result<(), Status> { + super::validation::validate_object_metadata(template.metadata.as_ref(), "sandbox_template")?; + let name = template.object_name().to_string(); + validate_dns1123_label(&name, "template.metadata.name")?; + validate_sandbox_workload_template_service_level(template)?; + let spec = sandbox_spec_from_user_workload_template(template)?; + validate_sandbox_spec(&name, &spec)?; + Ok(()) } -async fn providers_for_sandbox( - state: &Arc, - sandbox: &Sandbox, - workspace: &str, -) -> Result, Status> { - let provider_names = sandbox +fn validate_sandbox_workload_template_service_level( + template: &SandboxWorkloadTemplate, +) -> Result<(), Status> { + let Some(startup) = template .spec .as_ref() - .map(|spec| spec.providers.as_slice()) - .ok_or_else(|| Status::failed_precondition("sandbox spec is missing"))?; - - let mut providers = Vec::with_capacity(provider_names.len()); - for name in provider_names { - let provider = get_provider_record(state.store.as_ref(), workspace, name) - .await - .map_err(|err| { - if err.code() == tonic::Code::NotFound { - Status::failed_precondition(format!("provider '{name}' not found")) - } else { - err - } - })?; - providers.push(provider); + .and_then(|spec| spec.desired_service_level.as_ref()) + .and_then(|service_level| service_level.startup.as_ref()) + else { + return Ok(()); + }; + if let Some(ready_within) = &startup.ready_within { + validate_positive_normalized_duration( + ready_within, + "template.spec.desired_service_level.startup.ready_within", + )?; } - Ok(providers) + Ok(()) } -/// Retry a pure server-owned mutation on a fresh resource version. Explicit -/// client versions still fail on conflict so clients retain their CAS contract. -async fn update_sandbox_cas( - state: &ServerState, - sandbox_id: &str, - expected_resource_version: u64, - mut mutate: F, -) -> PersistenceResult -where - F: FnMut(&mut Sandbox), -{ - for attempt in 1..=SANDBOX_CAS_RETRY_LIMIT { - match state - .store - .update_message_cas::(sandbox_id, expected_resource_version, &mut mutate) - .await - { - Ok(sandbox) => return Ok(sandbox), - Err(crate::persistence::PersistenceError::Conflict { .. }) - if expected_resource_version == 0 && attempt < SANDBOX_CAS_RETRY_LIMIT => {} - Err(error) => return Err(error), - } +fn validate_positive_normalized_duration( + duration: &prost_types::Duration, + field: &str, +) -> Result<(), Status> { + const MAX_DURATION_SECONDS: u64 = 315_576_000_000; + if duration.seconds.unsigned_abs() > MAX_DURATION_SECONDS + || duration.nanos.unsigned_abs() >= 1_000_000_000 + { + return Err(Status::invalid_argument(format!( + "{field} must be a valid protobuf Duration" + ))); } - - unreachable!("sandbox CAS retry loop always returns on its final attempt") -} - -fn dedupe_provider_names(provider_names: &mut Vec) { - let mut index = 0; - while index < provider_names.len() { - if provider_names[..index].contains(&provider_names[index]) { - provider_names.remove(index); - } else { - index += 1; - } + if (duration.seconds > 0 && duration.nanos < 0) || (duration.seconds < 0 && duration.nanos > 0) + { + return Err(Status::invalid_argument(format!( + "{field} must be a normalized protobuf Duration" + ))); + } + if duration.seconds < 0 || duration.nanos < 0 || (duration.seconds == 0 && duration.nanos == 0) + { + return Err(Status::invalid_argument(format!( + "{field} must be greater than zero" + ))); } + Ok(()) } -// --------------------------------------------------------------------------- -// Watch handler -// --------------------------------------------------------------------------- - -pub(super) async fn handle_watch_sandbox( +pub(super) async fn handle_list_sandbox_providers( state: &Arc, - request: Request, -) -> Result, Status> { + request: Request, +) -> Result, Status> { let principal = super::extract_principal(&request)?; let req = request.into_inner(); let sandbox = resolve_and_authorize_sandbox_name( @@ -2211,4639 +2447,8022 @@ pub(super) async fn handle_watch_sandbox( MinWorkspaceRole::User, ) .await?; - let sandbox_id = sandbox.object_id().to_string(); + let workspace = sandbox.object_workspace().to_string(); + let pagination = Pagination::new( + req.page_size, + &req.page_token, + "ListSandboxProviders", + &[&workspace, &req.sandbox], + )?; + let mut providers = providers_for_sandbox(state, &sandbox, &workspace) + .await? + .into_iter() + .map(|provider| { + let name = provider + .metadata + .as_ref() + .filter(|metadata| !metadata.name.is_empty()) + .map(|metadata| metadata.name.clone()) + .ok_or_else(|| Status::internal("provider metadata name is missing"))?; + Ok((name, provider)) + }) + .collect::, Status>>()?; + providers.sort_unstable_by(|left, right| left.0.cmp(&right.0)); + let start = pagination.provider_cursor()?.map_or(0, |cursor| { + providers.partition_point(|(name, _)| name.as_str() <= cursor) + }); + let end = start + .saturating_add(usize::try_from(pagination.page_size()).expect("u32 fits in usize")) + .min(providers.len()); + let next_page_token = pagination + .next_provider_token((end < providers.len()).then(|| providers[end - 1].0.as_str())); + Ok(Response::new(ListSandboxProvidersResponse { + providers: providers + .into_iter() + .skip(start) + .take(end - start) + .map(|(_, provider)| provider) + .collect(), + next_page_token, + })) +} - let follow_status = req.follow_status; - let follow_logs = req.follow_logs; - let follow_events = req.follow_events; - let log_tail = if req.log_tail_lines == 0 { - 200 - } else { - req.log_tail_lines - }; - let stop_on_terminal = req.stop_on_terminal; - if let Some(since_time) = req.since_time.as_ref() { - openshell_core::time::validate_timestamp(since_time) - .map_err(|error| Status::invalid_argument(error.to_string()))?; +pub(super) async fn handle_attach_sandbox_provider( + state: &Arc, + request: Request, +) -> Result, Status> { + let principal = super::extract_principal(&request)?; + #[cfg(test)] + let attach_wait_probe = request + .extensions() + .get::>() + .cloned(); + let request = request.into_inner(); + let sandbox = resolve_and_authorize_sandbox_name( + state, + &principal, + &request.sandbox, + crate::auth::workspace_authz::selected_workspace_name(request.workspace_scope.as_ref())?, + MinWorkspaceRole::User, + ) + .await?; + let workspace = + super::workspace::resolve_workspace(state.store.as_ref(), sandbox.object_workspace()) + .await? + .ensure_active()?; + if request.provider.is_empty() { + return Err(Status::invalid_argument("provider_name is required")); } - let log_since_time = req.since_time; - let log_sources = req.log_sources; - let log_min_level = req.log_min_level; - let event_tail = req.event_tail; - - // Decode the resume cursor before spawning the producer. A token this - // server could not have issued is pure input validation, in the same class - // as the `id is required` check above, so it fails the RPC rather than - // arriving as the first item of an otherwise-established stream. - let resume_after = if req.resume_after_cursor.is_empty() { - None - } else { - Some( - WatchCursor::parse(&req.resume_after_cursor) - .map_err(|e| Status::invalid_argument(e.to_string()))?, - ) - }; - let (tx, rx) = mpsc::channel::>(256); - let state = state.clone(); + // Validate provider name would not violate sandbox spec constraints if added + // (pre-validation ensures CAS mutations preserve invariants) + if request.provider.len() > super::MAX_NAME_LEN { + return Err(Status::invalid_argument(format!( + "provider_name exceeds maximum length ({} > {})", + request.provider.len(), + super::MAX_NAME_LEN + ))); + } - // Spawn producer task. `tokio::spawn` detaches from the current span, so - // carry it across to keep the producer's store reads in the request trace. - let request_span = tracing::Span::current(); - let producer = tokio::spawn(tracing::Instrument::instrument( - async move { - // Validate that the sandbox exists BEFORE subscribing to any buses. - match state.store.get_message::(&sandbox_id).await { - Ok(Some(_)) => {} - Ok(None) => { - let _ = tx.send(Err(Status::not_found("sandbox not found"))).await; - return; - } - Err(e) => { - let _ = tx - .send(Err(Status::internal(format!("fetch sandbox failed: {e}")))) - .await; - return; - } + // The receipt must capture the provider revision selected by this + // serialized mutation, after any preceding credential update has finished. + #[cfg(test)] + if let Some(probe) = attach_wait_probe { + probe.notify_one(); + } + // A child also locks its parent, so the parent's providers cannot change + // before the attach is saved. + let scope = sandbox.parent.as_ref().map_or_else( + || MutationScope::sandbox(sandbox.object_workspace(), sandbox.object_id()), + |parent| MutationScope::ChildSandbox { + workspace: sandbox.object_workspace(), + sandbox_id: sandbox.object_id(), + parent_id: &parent.id, + }, + ); + let _mutation_guard = + state.compute.mutation_guard(scope).await.map_err(|err| { + super::persistence_error_to_status(err, "acquire sandbox mutation lock") + })?; + if let Some(parent) = &sandbox.parent { + check_parent_has_provider(state, parent, &request.provider).await?; + } + let provider_record = get_provider_record(state.store.as_ref(), &workspace, &request.provider) + .await + .map_err(|err| { + if err.code() == tonic::Code::NotFound { + Status::failed_precondition(format!("provider '{}' not found", request.provider)) + } else { + err } + })?; + let sandbox_name = sandbox.object_name().to_string(); + let sandbox_id = sandbox + .metadata + .as_ref() + .ok_or_else(|| Status::internal("sandbox metadata is missing"))? + .id + .clone(); - // Subscribe to all buses BEFORE reading the snapshot. - let mut status_rx = if follow_status { - Some(state.sandbox_watch_bus.subscribe(&sandbox_id)) - } else { - None - }; - let mut log_rx = if follow_logs { - Some(state.tracing_log_bus.subscribe(&sandbox_id)) - } else { - None - }; - let mut platform_rx = if follow_events { - Some( - state - .tracing_log_bus - .platform_event_bus - .subscribe(&sandbox_id), - ) - } else { - None + // Pre-check: fail fast if sandbox spec is missing (invariant violation) + let spec = sandbox + .spec + .as_ref() + .ok_or_else(|| Status::internal("sandbox spec is missing"))?; + + // Pre-check: fail fast if already at MAX_PROVIDERS limit (avoid spurious CAS conflicts) + // Note: This is an optimization; the CAS closure rechecks after dedupe in case of races + if spec.providers.len() >= MAX_PROVIDERS + && !spec.providers.iter().any(|name| name == &request.provider) + { + return Err(Status::invalid_argument(format!( + "providers list exceeds maximum ({MAX_PROVIDERS})" + ))); + } + let mut candidate_spec = spec.clone(); + dedupe_provider_names(&mut candidate_spec.providers); + if !candidate_spec + .providers + .iter() + .any(|name| name == &request.provider) + { + candidate_spec.providers.push(request.provider.clone()); + } + validate_sandbox_spec(&sandbox_name, &candidate_spec)?; + let provider_profile_catalog = state + .provider_profile_sources + .snapshot_catalog(state.store.as_ref(), &workspace) + .await?; + super::provider::validate_provider_profiles_present( + state.store.as_ref(), + &provider_profile_catalog, + &workspace, + &candidate_spec.providers, + ) + .await?; + validate_provider_environment_keys_unique_with_catalog( + state.store.as_ref(), + crate::provider_refresh::RefreshStateReader::Runtime(&state.refresh), + &provider_profile_catalog, + &workspace, + &candidate_spec.providers, + ) + .await?; + super::policy::validate_candidate_provider_attachments( + state, + &workspace, + &sandbox, + &candidate_spec.providers, + ) + .await?; + let current_policy = + super::policy::current_base_policy_for_sandbox(state.store.as_ref(), &sandbox).await?; + super::policy::validate_candidate_sandbox_credential_policy( + state, + &workspace, + &candidate_spec.providers, + Some(¤t_policy), + ) + .await?; + + let provider_name = request.provider.clone(); + let attached = Arc::new(AtomicBool::new(false)); + let attached_clone = attached.clone(); + let mutation_id = uuid::Uuid::new_v4().to_string(); + + let sandbox = update_sandbox_cas( + state, + &sandbox_id, + request.expected_resource_version, + |sandbox| { + attached_clone.store(false, Ordering::Relaxed); + let Some(ref mut spec) = sandbox.spec else { + // Spec should always exist post-creation; if missing, fail CAS to surface error + return; }; - // Re-read the snapshot now that we have subscriptions active. - match state.store.get_message::(&sandbox_id).await { - Ok(Some(sandbox)) => { - state.sandbox_index.update_from_sandbox(&sandbox); - let _ = tx - .send(Ok(SandboxStreamEvent { - payload: Some( - openshell_core::proto::sandbox_stream_event::Payload::Sandbox( - sandbox.clone(), - ), - ), - // Status snapshots are re-read, not resumed by cursor. - cursor: String::new(), - })) - .await; + if spec.provider_attachment_epoch.is_empty() { + spec.provider_attachment_epoch.clone_from(&mutation_id); + } - if stop_on_terminal { - let phase = SandboxPhase::try_from(sandbox.phase()) - .unwrap_or(SandboxPhase::Unknown); - if is_watch_terminal(phase) { - return; - } - } - } - Ok(None) => { - let _ = tx.send(Err(Status::not_found("sandbox not found"))).await; - return; - } - Err(e) => { - let _ = tx - .send(Err(Status::internal(format!("fetch sandbox failed: {e}")))) - .await; - return; - } + dedupe_provider_names(&mut spec.providers); + if !spec.providers.iter().any(|name| name == &provider_name) + && spec.providers.len() < MAX_PROVIDERS + { + spec.providers.push(provider_name.clone()); + spec.provider_attachment_epoch.clone_from(&mutation_id); + attached_clone.store(true, Ordering::Relaxed); + crate::compute::provisioning_deadline::attachments_changed( + sandbox, + current_time_ms(), + ); } + }, + ) + .await + .map_err(|e| super::persistence_error_to_status(e, "attach sandbox provider"))?; - // Highest seq the tail/replay phase already handled, tracked per - // source. The broadcast receivers were subscribed before replay ran, - // so an event published during initialization can sit in both the - // replay buffer and a live receiver; the live loop suppresses events - // at or below its source's mark so each is delivered exactly once. - // - // The two marks must stay separate. Both buses number from one - // shared cursor space, but they are read at different instants and - // bounded independently (`log_tail_lines` vs `event_tail`, which has - // no default and so replays nothing unless the client asks). A - // single shared mark therefore lets the deeper source censor the - // shallower one: with the default `event_tail` of 0 the mark rises - // to the newest buffered log while no platform event was replayed at - // all, and every platform event published in the initialization - // window is dropped as a duplicate of something never sent. Keyed by - // source, an event is suppressed only if its own source's replay - // actually covered it. - // - // No unit test pins this. The only reachable window is between the - // subscribe above and the log tail read below -- an event published - // earlier is replayed rather than live, and one published later - // outranks the mark -- and the producer crosses that window with no - // await a test can wedge open. Reproducing it needs a seam in the - // producer, which is not worth adding to production code. - let resume_seq = resume_after.map_or(0, |resume| resume.seq); - let mut log_cutoff: u64 = resume_seq; - let mut platform_cutoff: u64 = resume_seq; + let attached = attached.load(Ordering::Relaxed); + if attached { + crate::config_delivery::publish_sandbox(state, &sandbox_id); + state.sandbox_watch_bus.notify(&sandbox_id); + } + let receipt = super::provider_readiness::record_provider_mutation( + state, + &sandbox, + &request.provider, + ProviderMutationKind::Attach, + Some(( + provider_record.object_id(), + provider_record.get_resource_version(), + )), + &mutation_id, + ) + .await?; + + info!( + sandbox_name = %sandbox_name, + provider_name = %request.provider, + attached, + "AttachSandboxProvider request completed successfully" + ); + + Ok(Response::new(AttachSandboxProviderResponse { + sandbox: Some(sandbox), + attached, + receipt: Some(receipt), + })) +} + +pub(super) async fn handle_detach_sandbox_provider( + state: &Arc, + request: Request, +) -> Result, Status> { + let principal = super::extract_principal(&request)?; + let request = request.into_inner(); + let sandbox = resolve_and_authorize_sandbox_name( + state, + &principal, + &request.sandbox, + crate::auth::workspace_authz::selected_workspace_name(request.workspace_scope.as_ref())?, + MinWorkspaceRole::User, + ) + .await?; + let workspace = sandbox.object_workspace().to_string(); + if request.provider.is_empty() { + return Err(Status::invalid_argument("provider_name is required")); + } + + // Validate provider name (pre-validation ensures CAS mutations preserve invariants) + if request.provider.len() > super::MAX_NAME_LEN { + return Err(Status::invalid_argument(format!( + "provider_name exceeds maximum length ({} > {})", + request.provider.len(), + super::MAX_NAME_LEN + ))); + } + + let mutation_guard = state + .compute + .mutation_guard(MutationScope::sandbox( + sandbox.object_workspace(), + sandbox.object_id(), + )) + .await + .map_err(|err| super::persistence_error_to_status(err, "acquire sandbox mutation lock"))?; + let sandbox_name = sandbox.object_name().to_string(); + let sandbox_id = sandbox + .metadata + .as_ref() + .ok_or_else(|| Status::internal("sandbox metadata is missing"))? + .id + .clone(); + + // Pre-check: fail fast if sandbox spec is missing (invariant violation) + let spec = sandbox + .spec + .as_ref() + .ok_or_else(|| Status::internal("sandbox spec is missing"))?; + let mut candidate_spec = spec.clone(); + candidate_spec + .providers + .retain(|name| name != &request.provider); + dedupe_provider_names(&mut candidate_spec.providers); + super::policy::validate_candidate_provider_attachments( + state, + &workspace, + &sandbox, + &candidate_spec.providers, + ) + .await?; + + let (sandbox, detached, receipt) = detach_provider_locked( + state, + &sandbox_id, + request.expected_resource_version, + &request.provider, + ) + .await?; + drop(mutation_guard); + + info!( + sandbox_name = %sandbox_name, + provider_name = %request.provider, + detached, + "DetachSandboxProvider request completed successfully" + ); + + // A root's children lose what it loses. Delivery already serves them only + // the root's providers; the sync, never cancelled, removes the provider + // from their records and pushes each child. It runs for every root, so a + // retried detach still reaches children an earlier sync missed. Every + // session that follows the provider rebuilds at once, which includes + // the children: their records name it until the sync runs. + if sandbox.parent.is_none() { + if detached { + crate::config_delivery::publish_provider(state, &workspace, &request.provider); + } + let state = Arc::clone(state); + let parent_id = sandbox_id.clone(); + tokio::spawn(async move { + if let Err(error) = sync_children(&state, &parent_id).await { + warn!(parent_id, error = %error, "failed to sync child sandboxes"); + } + }); + } + + Ok(Response::new(DetachSandboxProviderResponse { + sandbox: Some(sandbox), + detached, + receipt: Some(receipt), + })) +} + +/// Detach `provider` from a sandbox: bump its attachment epoch so its +/// supervisor drops the credential, push the change, and record the +/// readiness receipt. The caller holds the sandbox's mutation lock. +async fn detach_provider_locked( + state: &Arc, + sandbox_id: &str, + expected_resource_version: u64, + provider: &str, +) -> Result< + ( + Sandbox, + bool, + openshell_core::proto::ProviderMutationReceipt, + ), + Status, +> { + let provider_name = provider.to_string(); + let detached = Arc::new(AtomicBool::new(false)); + let detached_clone = detached.clone(); + let mutation_id = uuid::Uuid::new_v4().to_string(); + + let sandbox = update_sandbox_cas(state, sandbox_id, expected_resource_version, |sandbox| { + detached_clone.store(false, Ordering::Relaxed); + let Some(ref mut spec) = sandbox.spec else { + // Spec should always exist post-creation; if missing, fail CAS to surface error + return; + }; + + if spec.provider_attachment_epoch.is_empty() { + spec.provider_attachment_epoch.clone_from(&mutation_id); + } + + let before_len = spec.providers.len(); + spec.providers.retain(|name| name != &provider_name); + if spec.providers.len() != before_len { + spec.provider_attachment_epoch.clone_from(&mutation_id); + detached_clone.store(true, Ordering::Relaxed); + // Only dedupe after making a change + dedupe_provider_names(&mut spec.providers); + crate::compute::provisioning_deadline::attachments_changed(sandbox, current_time_ms()); + } + }) + .await + .map_err(|e| super::persistence_error_to_status(e, "detach sandbox provider"))?; + + let detached = detached.load(Ordering::Relaxed); + if detached { + crate::config_delivery::publish_sandbox(state, sandbox_id); + state.sandbox_watch_bus.notify(sandbox_id); + } + let receipt = super::provider_readiness::record_provider_mutation( + state, + &sandbox, + provider, + ProviderMutationKind::Detach, + None, + &mutation_id, + ) + .await?; + Ok((sandbox, detached, receipt)) +} + +pub(super) async fn handle_delete_sandbox( + state: &Arc, + request: Request, +) -> Result, Status> { + let result = handle_delete_sandbox_inner(state, request).await; + let outcome = match &result { + Ok(_) => TelemetryOutcome::Success, + _ => TelemetryOutcome::Failure, + }; + openshell_core::telemetry::emit_lifecycle( + LifecycleResource::Sandbox, + LifecycleOperation::Delete, + outcome, + ); + result +} + +async fn handle_delete_sandbox_inner( + state: &Arc, + request: Request, +) -> Result, Status> { + let principal = super::extract_principal(&request)?; + let req = request.into_inner(); + if let crate::auth::principal::Principal::Sandbox(caller) = &principal { + return delete_caller_child(state, caller, &req).await; + } + let name = req.name; + if name.is_empty() { + return Err(Status::invalid_argument("sandbox is required")); + } + let authz = authorize_workspace( + &state.store, + &state.admin_role, + &principal, + crate::auth::workspace_authz::selected_workspace_name(req.workspace_scope.as_ref())?, + MinWorkspaceRole::User, + ) + .await + .map_err(|status| { + if status.code() == tonic::Code::PermissionDenied { + Status::not_found("sandbox not found") + } else { + status + } + })?; + 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(); + let result = state + .compute + .delete_sandbox_allow_missing_with_preconditions( + &workspace, + &name, + req.allow_missing, + preconditions, + ) + .await?; + if !result.sandbox_id.is_empty() { + state.telemetry.end_sandbox_session(&result.sandbox_id); + } + info!(sandbox_name = %name, "DeleteSandbox request completed successfully"); + Ok(Response::new(DeleteSandboxResponse { + outcome: result.outcome.into(), + sandbox_id: result.sandbox_id, + })) +} + +/// A sandbox caller (only through `/mcp`) deleting one of its own children. +/// The delete is bound to the id that was checked, so a name reused in the +/// meantime is never deleted in its place. +async fn delete_caller_child( + state: &Arc, + caller: &crate::auth::principal::SandboxPrincipal, + request: &DeleteSandboxRequest, +) -> Result, Status> { + let set = [ + ("workspace_scope", request.workspace_scope.is_some()), + ("allow_missing", request.allow_missing), + ("request_id", !request.request_id.is_empty()), + ]; + if let Some((field, _)) = set.iter().find(|(_, is_set)| *is_set) { + return Err(Status::invalid_argument(format!( + "field '{field}' is not allowed for sandbox callers" + ))); + } + if *request + != (DeleteSandboxRequest { + name: request.name.clone(), + ..Default::default() + }) + { + return Err(Status::invalid_argument( + "the request sets fields that are not allowed for sandbox callers", + )); + } + let child = resolve_caller_child(state, caller, &request.name).await?; + let preconditions = SandboxDeletePreconditions { + expected_sandbox_id: Some(child.object_id().to_string()), + ..Default::default() + }; + let result = match state + .compute + .delete_sandbox_allow_missing_with_preconditions( + child.object_workspace(), + child.object_name(), + false, + preconditions, + ) + .await + { + Ok(result) => result, + // The checked child is gone when its name no longer resolves to it; + // any other conflict is reported as it is. + Err(status) if status.code() == tonic::Code::Aborted => { + return Err(aborted_child_delete( + state, + caller, + &request.name, + child.object_id(), + status, + ) + .await); + } + Err(status) => return Err(status), + }; + state.telemetry.end_sandbox_session(&result.sandbox_id); + info!(sandbox_name = %request.name, "DeleteSandbox request completed successfully"); + Ok(Response::new(DeleteSandboxResponse { + outcome: result.outcome.into(), + sandbox_id: result.sandbox_id, + })) +} + +/// An aborted delete means the checked child is gone when its name no longer +/// resolves to it (a name reused in the meantime); any other conflict is +/// reported as it is. +async fn aborted_child_delete( + state: &ServerState, + caller: &crate::auth::principal::SandboxPrincipal, + name: &str, + checked_id: &str, + status: Status, +) -> Status { + match resolve_caller_child(state, caller, name).await { + Ok(current) if current.object_id() == checked_id => status, + _ => Status::not_found(format!("sandbox '{name}' not found")), + } +} + +pub(super) async fn handle_stop_sandbox( + state: &Arc, + request: Request, +) -> Result, Status> { + let result = handle_stop_sandbox_inner(state, request).await; + openshell_core::telemetry::emit_lifecycle( + LifecycleResource::Sandbox, + LifecycleOperation::Stop, + if result.is_ok() { + TelemetryOutcome::Success + } else { + TelemetryOutcome::Failure + }, + ); + result +} + +async fn handle_stop_sandbox_inner( + state: &Arc, + request: Request, +) -> Result, Status> { + let principal = super::extract_principal(&request)?; + let req = request.into_inner(); + let resolved = resolve_and_authorize_sandbox_name( + state, + &principal, + &req.name, + crate::auth::workspace_authz::selected_workspace_name(req.workspace_scope.as_ref())?, + MinWorkspaceRole::User, + ) + .await?; + let workspace = resolved.object_workspace(); + let name = resolved.object_name(); + let sandbox = state.compute.stop_sandbox(workspace, name).await?; + info!(sandbox_name = %name, "StopSandbox request completed successfully"); + Ok(Response::new(SandboxResponse { + application_service_urls: HashMap::new(), + gateway_service_urls: HashMap::new(), + sandbox: Some(sandbox), + service_urls: HashMap::new(), + })) +} + +pub(super) async fn handle_start_sandbox( + state: &Arc, + request: Request, +) -> Result, Status> { + let result = handle_start_sandbox_inner(state, request).await; + openshell_core::telemetry::emit_lifecycle( + LifecycleResource::Sandbox, + LifecycleOperation::Start, + if result.is_ok() { + TelemetryOutcome::Success + } else { + TelemetryOutcome::Failure + }, + ); + result +} + +async fn handle_start_sandbox_inner( + state: &Arc, + request: Request, +) -> Result, Status> { + let principal = super::extract_principal(&request)?; + let req = request.into_inner(); + let resolved = resolve_and_authorize_sandbox_name( + state, + &principal, + &req.name, + crate::auth::workspace_authz::selected_workspace_name(req.workspace_scope.as_ref())?, + MinWorkspaceRole::User, + ) + .await?; + if let Some(policy) = resolved.spec.as_ref().and_then(|spec| spec.policy.as_ref()) { + require_gateway_cedar_support(policy)?; + } + let workspace = resolved.object_workspace().to_string(); + let name = resolved.object_name().to_string(); + let mut sandbox = state + .compute + .start_sandbox_authenticated( + &workspace, + &name, + state.sandbox_session_jwt_authority.as_deref(), + ) + .await?; + let remote_authority = + crate::supervisor_session::remote_supervisor_owner(state, sandbox.object_id()) + .await? + .is_some(); + state + .supervisor_sessions + .project_endpoint_status(&mut sandbox, remote_authority); + info!(sandbox_name = %name, "StartSandbox request completed successfully"); + Ok(Response::new(SandboxResponse { + application_service_urls: HashMap::new(), + gateway_service_urls: HashMap::new(), + sandbox: Some(sandbox), + service_urls: HashMap::new(), + })) +} + +pub(super) async fn handle_suspend_sandbox( + state: &Arc, + request: Request, +) -> Result, Status> { + let result = handle_suspend_sandbox_inner(state, request).await; + openshell_core::telemetry::emit_lifecycle( + LifecycleResource::Sandbox, + LifecycleOperation::Suspend, + if result.is_ok() { + TelemetryOutcome::Success + } else { + TelemetryOutcome::Failure + }, + ); + result +} + +async fn handle_suspend_sandbox_inner( + state: &Arc, + request: Request, +) -> Result, Status> { + let principal = super::extract_principal(&request)?; + let req = request.into_inner(); + let resolved = resolve_and_authorize_sandbox_name( + state, + &principal, + &req.name, + crate::auth::workspace_authz::selected_workspace_name(req.workspace_scope.as_ref())?, + MinWorkspaceRole::User, + ) + .await?; + let workspace = resolved.object_workspace(); + let name = resolved.object_name(); + let sandbox = state.compute.suspend_sandbox(workspace, name).await?; + info!(sandbox_name = %name, "SuspendSandbox request completed successfully"); + Ok(Response::new(SandboxResponse { + application_service_urls: HashMap::new(), + gateway_service_urls: HashMap::new(), + sandbox: Some(sandbox), + service_urls: HashMap::new(), + })) +} + +pub(super) async fn handle_resume_sandbox( + state: &Arc, + request: Request, +) -> Result, Status> { + let result = handle_resume_sandbox_inner(state, request).await; + openshell_core::telemetry::emit_lifecycle( + LifecycleResource::Sandbox, + LifecycleOperation::Resume, + if result.is_ok() { + TelemetryOutcome::Success + } else { + TelemetryOutcome::Failure + }, + ); + result +} + +async fn handle_resume_sandbox_inner( + state: &Arc, + request: Request, +) -> Result, Status> { + let principal = super::extract_principal(&request)?; + let req = request.into_inner(); + let resolved = resolve_and_authorize_sandbox_name( + state, + &principal, + &req.name, + crate::auth::workspace_authz::selected_workspace_name(req.workspace_scope.as_ref())?, + MinWorkspaceRole::User, + ) + .await?; + if let Some(policy) = resolved.spec.as_ref().and_then(|spec| spec.policy.as_ref()) { + require_gateway_cedar_support(policy)?; + } + let workspace = resolved.object_workspace().to_string(); + let name = resolved.object_name().to_string(); + let mut sandbox = state + .compute + .resume_sandbox_authenticated( + &workspace, + &name, + req.restart_if_restore_fails, + state.sandbox_session_jwt_authority.as_deref(), + ) + .await?; + let remote_authority = + crate::supervisor_session::remote_supervisor_owner(state, sandbox.object_id()) + .await? + .is_some(); + state + .supervisor_sessions + .project_endpoint_status(&mut sandbox, remote_authority); + info!(sandbox_name = %name, "ResumeSandbox request completed successfully"); + Ok(Response::new(SandboxResponse { + application_service_urls: HashMap::new(), + gateway_service_urls: HashMap::new(), + sandbox: Some(sandbox), + service_urls: HashMap::new(), + })) +} + +pub async fn mint_persisted_authentication( + state: &ServerState, + sandbox: &Sandbox, +) -> Result { + let authority = state + .sandbox_session_jwt_authority + .as_ref() + .ok_or_else(|| Status::failed_precondition("sandbox session authority is unavailable"))?; + let metadata = sandbox + .metadata + .as_ref() + .ok_or_else(|| Status::failed_precondition("sandbox metadata is missing"))?; + let identity = + crate::auth::sandbox_session::PersistedSandboxIdentity::read(&metadata.annotations) + .map_err(|error| Status::failed_precondition(error.to_string()))?; + let mut authentication = authority.mint_persisted_launch(sandbox.object_id(), &identity)?; + let mut with_identity = sandbox.clone(); + state + .compute + .prepare_ssh_identity(&mut with_identity, &mut authentication) + .await?; + Ok(authentication) +} + +async fn providers_for_sandbox( + state: &Arc, + sandbox: &Sandbox, + workspace: &str, +) -> Result, Status> { + let provider_names = sandbox + .spec + .as_ref() + .map(|spec| spec.providers.as_slice()) + .ok_or_else(|| Status::failed_precondition("sandbox spec is missing"))?; + + let mut providers = Vec::with_capacity(provider_names.len()); + for name in provider_names { + let provider = get_provider_record(state.store.as_ref(), workspace, name) + .await + .map_err(|err| { + if err.code() == tonic::Code::NotFound { + Status::failed_precondition(format!("provider '{name}' not found")) + } else { + err + } + })?; + providers.push(provider); + } + Ok(providers) +} + +/// Retry a pure server-owned mutation on a fresh resource version. Explicit +/// client versions still fail on conflict so clients retain their CAS contract. +async fn update_sandbox_cas( + state: &ServerState, + sandbox_id: &str, + expected_resource_version: u64, + mut mutate: F, +) -> PersistenceResult +where + F: FnMut(&mut Sandbox), +{ + for attempt in 1..=SANDBOX_CAS_RETRY_LIMIT { + match state + .store + .update_message_cas::(sandbox_id, expected_resource_version, &mut mutate) + .await + { + Ok(sandbox) => return Ok(sandbox), + Err(crate::persistence::PersistenceError::Conflict { .. }) + if expected_resource_version == 0 && attempt < SANDBOX_CAS_RETRY_LIMIT => {} + Err(error) => return Err(error), + } + } + + unreachable!("sandbox CAS retry loop always returns on its final attempt") +} + +fn dedupe_provider_names(provider_names: &mut Vec) { + let mut index = 0; + while index < provider_names.len() { + if provider_names[..index].contains(&provider_names[index]) { + provider_names.remove(index); + } else { + index += 1; + } + } +} + +// --------------------------------------------------------------------------- +// Watch handler +// --------------------------------------------------------------------------- + +pub(super) async fn handle_watch_sandbox( + state: &Arc, + request: Request, +) -> Result, Status> { + let principal = super::extract_principal(&request)?; + let req = request.into_inner(); + let sandbox = resolve_and_authorize_sandbox_name( + state, + &principal, + &req.sandbox, + crate::auth::workspace_authz::selected_workspace_name(req.workspace_scope.as_ref())?, + MinWorkspaceRole::User, + ) + .await?; + let sandbox_id = sandbox.object_id().to_string(); + + let follow_status = req.follow_status; + let follow_logs = req.follow_logs; + let follow_events = req.follow_events; + let log_tail = if req.log_tail_lines == 0 { + 200 + } else { + req.log_tail_lines + }; + let stop_on_terminal = req.stop_on_terminal; + if let Some(since_time) = req.since_time.as_ref() { + openshell_core::time::validate_timestamp(since_time) + .map_err(|error| Status::invalid_argument(error.to_string()))?; + } + let log_since_time = req.since_time; + let log_sources = req.log_sources; + let log_min_level = req.log_min_level; + let event_tail = req.event_tail; + + // Decode the resume cursor before spawning the producer. A token this + // server could not have issued is pure input validation, in the same class + // as the `id is required` check above, so it fails the RPC rather than + // arriving as the first item of an otherwise-established stream. + let resume_after = if req.resume_after_cursor.is_empty() { + None + } else { + Some( + WatchCursor::parse(&req.resume_after_cursor) + .map_err(|e| Status::invalid_argument(e.to_string()))?, + ) + }; + + let (tx, rx) = mpsc::channel::>(256); + let state = state.clone(); + + // Spawn producer task. `tokio::spawn` detaches from the current span, so + // carry it across to keep the producer's store reads in the request trace. + let request_span = tracing::Span::current(); + let producer = tokio::spawn(tracing::Instrument::instrument( + async move { + // Validate that the sandbox exists BEFORE subscribing to any buses. + match state.store.get_message::(&sandbox_id).await { + Ok(Some(_)) => {} + Ok(None) => { + let _ = tx.send(Err(Status::not_found("sandbox not found"))).await; + return; + } + Err(e) => { + let _ = tx + .send(Err(Status::internal(format!("fetch sandbox failed: {e}")))) + .await; + return; + } + } + + // Subscribe to all buses BEFORE reading the snapshot. + let mut status_rx = if follow_status { + Some(state.sandbox_watch_bus.subscribe(&sandbox_id)) + } else { + None + }; + let mut log_rx = if follow_logs { + Some(state.tracing_log_bus.subscribe(&sandbox_id)) + } else { + None + }; + let mut platform_rx = if follow_events { + Some( + state + .tracing_log_bus + .platform_event_bus + .subscribe(&sandbox_id), + ) + } else { + None + }; + + // Re-read the snapshot now that we have subscriptions active. + match state.store.get_message::(&sandbox_id).await { + Ok(Some(sandbox)) => { + state.sandbox_index.update_from_sandbox(&sandbox); + let _ = tx + .send(Ok(SandboxStreamEvent { + payload: Some( + openshell_core::proto::sandbox_stream_event::Payload::Sandbox( + sandbox.clone(), + ), + ), + // Status snapshots are re-read, not resumed by cursor. + cursor: String::new(), + })) + .await; + + if stop_on_terminal { + let phase = SandboxPhase::try_from(sandbox.phase()) + .unwrap_or(SandboxPhase::Unknown); + if is_watch_terminal(phase) { + return; + } + } + } + Ok(None) => { + let _ = tx.send(Err(Status::not_found("sandbox not found"))).await; + return; + } + Err(e) => { + let _ = tx + .send(Err(Status::internal(format!("fetch sandbox failed: {e}")))) + .await; + return; + } + } + + // Highest seq the tail/replay phase already handled, tracked per + // source. The broadcast receivers were subscribed before replay ran, + // so an event published during initialization can sit in both the + // replay buffer and a live receiver; the live loop suppresses events + // at or below its source's mark so each is delivered exactly once. + // + // The two marks must stay separate. Both buses number from one + // shared cursor space, but they are read at different instants and + // bounded independently (`log_tail_lines` vs `event_tail`, which has + // no default and so replays nothing unless the client asks). A + // single shared mark therefore lets the deeper source censor the + // shallower one: with the default `event_tail` of 0 the mark rises + // to the newest buffered log while no platform event was replayed at + // all, and every platform event published in the initialization + // window is dropped as a duplicate of something never sent. Keyed by + // source, an event is suppressed only if its own source's replay + // actually covered it. + // + // No unit test pins this. The only reachable window is between the + // subscribe above and the log tail read below -- an event published + // earlier is replayed rather than live, and one published later + // outranks the mark -- and the producer crosses that window with no + // await a test can wedge open. Reproducing it needs a seam in the + // producer, which is not worth adding to production code. + let resume_seq = resume_after.map_or(0, |resume| resume.seq); + let mut log_cutoff: u64 = resume_seq; + let mut platform_cutoff: u64 = resume_seq; + + if let Some(resume) = resume_after { + // Resume: replay events strictly after the client's cursor from both + // resumable buses. Either bus reporting a trimmed range is an + // unrecoverable gap -> terminate with a documented status. + use openshell_core::proto::sandbox_stream_event::Payload; + + // A cursor is only a position inside the space that issued it. + // A gateway restart, a bus teardown, or a reconnect landing on + // another replica starts a new space numbered from 1 with no + // record of the cursors the old one handed out. The buses then + // look merely empty, so `tail_after` reports no gap -- treating + // that as "caught up" would pin the cutoff to a stale number + // and silently swallow every live event beneath it. Comparing + // epochs answers "did this cursor come from *this* space?", + // which no numeric bound can. + match state.tracing_log_bus.cursor_space(&sandbox_id) { + None => { + let _ = tx.send(Err(Status::out_of_range(RESUME_SPACE_GONE))).await; + return; + } + Some(space) if space.epoch != resume.epoch => { + let _ = tx.send(Err(Status::out_of_range(RESUME_SPACE_GONE))).await; + return; + } + // Right space, but ahead of anything it issued: only a + // fabricated token gets here. Reject rather than accept a + // cutoff no event can ever exceed. + Some(space) if resume.seq > space.highest_seq => { + let _ = tx + .send(Err(Status::out_of_range(RESUME_CURSOR_AHEAD))) + .await; + return; + } + Some(_) => {} + } + + let log_replay = if follow_logs { + Some(state.tracing_log_bus.tail_after(&sandbox_id, resume.seq)) + } else { + None + }; + + let platform_replay = if follow_events { + Some( + state + .tracing_log_bus + .platform_event_bus + .tail_after(&sandbox_id, resume.seq), + ) + } else { + None + }; + + // Re-check the epoch now that both tails are in hand. The check + // above and each `tail_after` take their locks independently, so + // a teardown plus a republish can retire the validated space and + // install a replacement in between. The reads would then have + // applied the old space's seq to the new space's buffers, and + // `tail_after` -- which only knows numbers -- would report no gap + // while skipping every replacement event at or below it. The + // second look is cheap and runs before anything is emitted, so a + // space that moved under us ends the stream instead of serving a + // truncated replay. + // + // Ordering is unchanged: this takes only the allocator lock and + // releases it, never held across a bus lock. + if !cursor_space_is(&state, &sandbox_id, resume.epoch) { + let _ = tx.send(Err(Status::out_of_range(RESUME_SPACE_GONE))).await; + return; + } + + // Gap check FIRST (borrows), before the merge moves the vecs. + for replay in [&log_replay, &platform_replay] { + if let Some(Err(gap)) = replay { + let _ = tx.send(Err(Status::out_of_range(format!( + "resume cursor {} is no longer available; earliest resumable cursor is {}", + gap.requested_after, gap.oldest_available + )))) + .await; + return; + } + } + + // Merge both buses by shared seq, then emit ascending. Each + // source's mark comes from its own replay -- `tail_after` + // returns ascending, so its last entry is that source's high + // water. Marking every event the phase examined, not only the + // ones that survived the filters, keeps a filtered event's live + // duplicate suppressed: the live loop does not re-apply + // `log_since_time` and would otherwise let it through. + let mut merged: Vec = Vec::new(); + if let Some(Ok(v)) = log_replay { + if let Some(last) = v.last() { + log_cutoff = log_cutoff.max(last.seq); + } + merged.extend(v); + } + if let Some(Ok(v)) = platform_replay { + if let Some(last) = v.last() { + platform_cutoff = platform_cutoff.max(last.seq); + } + merged.extend(v); + } + + merged.sort_by_key(|c| c.seq); + + for cursored in merged { + if let Some(Payload::Log(ref log)) = cursored.event.payload { + if let Some(since_time) = log_since_time.as_ref() { + let Some(event_time) = log.event_time.as_ref() else { + continue; + }; + let Ok(ordering) = + openshell_core::time::compare_timestamps(event_time, since_time) + else { + continue; + }; + if ordering == std::cmp::Ordering::Less { + continue; + } + } + if !log_sources.is_empty() && !source_matches(&log.source, &log_sources) { + continue; + } + if !level_matches(&log.level, &log_min_level) { + continue; + } + } + if tx.send(Ok(cursored.event)).await.is_err() { + return; + } + } + } else { + // Initial tail, best-effort. Both buses draw from one shared + // cursor space, so draining each in its own pass would order the + // tail by source and only incidentally by cursor: every buffered + // log would precede every buffered platform event regardless of + // which was published first. Collect both windows, sort by the + // shared seq, and emit one ascending run -- the same shape the + // resume path above uses, and the order a client comparing + // cursors expects. + // + // The two windows are truncated independently (log_tail vs + // event_tail), so this merges whatever each bus retained; it + // does not align their depths. + let mut tail: Vec = Vec::new(); + if follow_logs { + let logs = state.tracing_log_bus.tail(&sandbox_id, log_tail as usize); + if let Some(last) = logs.last() { + log_cutoff = log_cutoff.max(last.seq); + } + tail.extend(logs); + } + if follow_events { + let events = state + .tracing_log_bus + .platform_event_bus + .tail(&sandbox_id, event_tail as usize); + if let Some(last) = events.last() { + platform_cutoff = platform_cutoff.max(last.seq); + } + tail.extend(events); + } + + tail.sort_by_key(|cursored| cursored.seq); + + for cursored in tail { + // Log filters; platform events carry no log fields and pass. + if let Some(openshell_core::proto::sandbox_stream_event::Payload::Log( + ref log, + )) = cursored.event.payload + { + if let Some(since_time) = log_since_time.as_ref() { + let Some(event_time) = log.event_time.as_ref() else { + continue; + }; + let Ok(ordering) = + openshell_core::time::compare_timestamps(event_time, since_time) + else { + continue; + }; + if ordering == std::cmp::Ordering::Less { + continue; + } + } + if !log_sources.is_empty() && !source_matches(&log.source, &log_sources) { + continue; + } + if !level_matches(&log.level, &log_min_level) { + continue; + } + } + if tx.send(Ok(cursored.event)).await.is_err() { + return; + } + } + } + + // Events drained above the publication watermark. They are held + // back rather than emitted so the client's highest delivered cursor + // is never above an event still queued on the other source. + let mut deferred: Vec> = Vec::new(); + + loop { + // Events withheld by the previous round are already in hand, so + // this round must not block on a new publication: the watermark + // that covers them has already advanced past them, and waiting + // for unrelated traffic would stall their delivery indefinitely. + let first = if deferred.is_empty() { + Some(tokio::select! { + () = tx.closed() => { + return; + } + res = async { + match status_rx.as_mut() { + Some(rx) => rx.recv().await, + None => future::pending().await, + } + } => { + match res { + Ok(()) => { + match state.store.get_message::(&sandbox_id).await { + Ok(Some(sandbox)) => { + state.sandbox_index.update_from_sandbox(&sandbox); + if tx.send(Ok(SandboxStreamEvent { payload: Some(openshell_core::proto::sandbox_stream_event::Payload::Sandbox(sandbox.clone())), cursor: String::new() })).await.is_err() { + return; + } + if stop_on_terminal { + let phase = SandboxPhase::try_from(sandbox.phase()).unwrap_or(SandboxPhase::Unknown); + if is_watch_terminal(phase) { + return; + } + } + } + Ok(None) => { + return; + } + Err(e) => { + let _ = tx.send(Err(Status::internal(format!("fetch sandbox failed: {e}")))).await; + return; + } + } + } + Err(broadcast::error::RecvError::Lagged(n)) => { + // Lag is recoverable: surface a warning and keep streaming. + if tx.send(Ok(crate::sandbox_watch::lag_warning_event(n))).await.is_err() { + return; + } + } + Err(broadcast::error::RecvError::Closed) => { + let _ = tx.send(Err(Status::cancelled("stream closed"))).await; + return; + } + } + // Status snapshots carry cursor 0 and are outside the + // resumable cursor space, so they never join a batch. + continue; + } + // Both resumable sources feed one cursor space, so neither + // can be emitted on its own: `select!` picks an arbitrary + // ready branch, which would emit a higher cursor ahead of a + // lower one waiting on the other source. Take whichever woke + // us as the start of a batch and merge below. + res = async { + match log_rx.as_mut() { + Some(rx) => rx.recv().await, + None => future::pending().await, + } + } => res, + res = async { + match platform_rx.as_mut() { + Some(rx) => rx.recv().await, + None => future::pending().await, + } + } => res, + }) + } else { + None + }; + + let mut batch = std::mem::take(&mut deferred); + match first { + None => {} + Some(Ok(evt)) => batch.push(evt), + Some(Err(broadcast::error::RecvError::Lagged(n))) => { + // Lag is recoverable: surface a warning and keep streaming. + if tx + .send(Ok(crate::sandbox_watch::lag_warning_event(n))) + .await + .is_err() + { + return; + } + // Carry any withheld events into the next round rather + // than dropping them with this batch. + deferred = batch; + continue; + } + Some(Err(broadcast::error::RecvError::Closed)) => { + let _ = tx.send(Err(Status::cancelled("stream closed"))).await; + return; + } + } + + // Read the publication watermark before draining. Publishers + // assign a sequence and push it onto their broadcast channel + // under one allocator lock, so every event at or below the + // sequence observed here has already reached its channel and + // the drain below is guaranteed to see it. Reading after the + // drain would admit a publish into the gap and defeat this. + // + // `None` means the cursor space is gone (teardown). Nothing + // further can be published into it, so nothing is withheld. + let watermark = state + .tracing_log_bus + .cursor_space(&sandbox_id) + .map_or(u64::MAX, |space| space.highest_seq); + + // Drain what is already queued on both sources. Sorting the + // batch restores cursor order across the two sources without + // waiting on either one. + let mut lagged = 0u64; + let mut closed = false; + for rx in [log_rx.as_mut(), platform_rx.as_mut()] + .into_iter() + .flatten() + { + loop { + match rx.try_recv() { + Ok(evt) => batch.push(evt), + Err(broadcast::error::TryRecvError::Empty) => break, + // Keep draining: the receiver is usable after a skip. + Err(broadcast::error::TryRecvError::Lagged(n)) => lagged += n, + Err(broadcast::error::TryRecvError::Closed) => { + closed = true; + break; + } + } + } + } + + batch.sort_by_key(|cursored| cursored.seq); + + // Withhold anything above the watermark. Such an event was + // published after the drain started, so a lower-cursor event + // from the other source may still be queued behind it. Emitting + // it now would let the client checkpoint above an event it has + // not seen, and resume past it after a disconnect. The next + // round re-reads the watermark, which by then covers these. + let held_from = batch.partition_point(|cursored| cursored.seq <= watermark); + deferred = batch.split_off(held_from); + + // Announce the gap before any event from this batch. A warning + // carries no cursor and is never replayed, so emitting it after + // the events lets a disconnect at the wrong moment strand the + // client past the gap: it would resume from a cursor above the + // skipped events having never learned they were dropped. + if lagged > 0 + && tx + .send(Ok(crate::sandbox_watch::lag_warning_event(lagged))) + .await + .is_err() + { + return; + } + + for cursored in batch { + // Skip events the tail/replay phase already handled, judged + // against the mark for this event's own source. Bus events + // always carry seq >= 1, so no sentinel is needed here: + // non-resumable events never reach this batch. + let is_log = matches!( + cursored.event.payload, + Some(openshell_core::proto::sandbox_stream_event::Payload::Log(_)) + ); + let cutoff = if is_log { log_cutoff } else { platform_cutoff }; + if cursored.seq <= cutoff { + continue; + } + if let Some(openshell_core::proto::sandbox_stream_event::Payload::Log( + ref log, + )) = cursored.event.payload + { + if !log_sources.is_empty() && !source_matches(&log.source, &log_sources) { + continue; + } + if !level_matches(&log.level, &log_min_level) { + continue; + } + } + if tx + .send(Ok(Arc::unwrap_or_clone(cursored).event)) + .await + .is_err() + { + return; + } + } + + if closed { + let _ = tx.send(Err(Status::cancelled("stream closed"))).await; + return; + } + } + }, + request_span, + )); + + Ok(Response::new(WatchSandboxStream::new(rx, producer))) +} + +fn is_watch_terminal(phase: SandboxPhase) -> bool { + matches!( + phase, + SandboxPhase::Ready + | SandboxPhase::Completed + | SandboxPhase::Stopped + | SandboxPhase::Suspended + | SandboxPhase::Error + ) +} + +// --------------------------------------------------------------------------- +// Exec handler +// --------------------------------------------------------------------------- + +const DEFAULT_PTY_COLS: u32 = 80; +const DEFAULT_PTY_ROWS: u32 = 24; + +fn pty_dimensions(cols: u32, rows: u32) -> (u32, u32) { + ( + if cols == 0 { DEFAULT_PTY_COLS } else { cols }, + if rows == 0 { DEFAULT_PTY_ROWS } else { rows }, + ) +} + +pub(super) async fn handle_exec_sandbox( + state: &Arc, + request: Request, +) -> Result>>, Status> { + use openshell_core::ObjectId; + + let principal = super::extract_principal(&request)?; + let completion = request + .extensions() + .get::() + .cloned(); + let req = request.into_inner(); + validate_exec_start(&req)?; + + // Only `/mcp` lets a sandbox caller reach this method, and it may act on + // its own children only, never on itself. + let sandbox = if let crate::auth::principal::Principal::Sandbox(caller) = &principal { + refuse_exec_fields_for_sandbox_caller(&req)?; + resolve_caller_child(state, caller, &req.sandbox).await? + } else { + resolve_and_authorize_sandbox_name( + state, + &principal, + &req.sandbox, + crate::auth::workspace_authz::selected_workspace_name(req.workspace_scope.as_ref())?, + MinWorkspaceRole::User, + ) + .await? + }; + + if let Some(completion) = &completion { + completion.ensure_target(sandbox.object_id())?; + } + + require_ready_sandbox(&sandbox)?; + + // Open a relay channel through the supervisor session. Use a 15s + // session-wait timeout, enough to cover a transient supervisor reconnect + // while still failing quickly during normal operation. + let (channel_id, relay_rx) = crate::supervisor_session::open_routed_relay_with_target( + state, + sandbox.object_id(), + relay_open::Target::Ssh(SshRelayTarget {}), + String::new(), + std::time::Duration::from_secs(15), + ) + .await + .map_err(|e| Status::unavailable(format!("supervisor relay failed: {e}")))?; + super::mutation_audit::record_exec_relay(&state.config.audit, &sandbox, &channel_id, &req); + + let command_str = build_remote_exec_command(&req) + .map_err(|e| Status::invalid_argument(format!("command construction failed: {e}")))?; + let stdin_payload = req.stdin; + let execution_timeout = req + .execution_timeout + .as_ref() + .map(openshell_core::time::duration_to_std) + .transpose() + .map_err(|error| Status::invalid_argument(error.to_string()))?; + let request_tty = req.tty; + let (cols, rows) = pty_dimensions(req.cols, req.rows); + + let sandbox_id = sandbox.object_id().to_string(); + + let no_login_shell = req.no_login_shell; + + let (tx, rx) = mpsc::channel::>(256); + tokio::spawn(async move { + // Wait for the supervisor's reverse CONNECT to deliver the relay stream. + let Some(relay_stream) = + await_relay_stream(relay_rx, &tx, &sandbox_id, &channel_id, "ExecSandbox").await + else { + return; + }; + + if let Err(err) = stream_exec_over_relay( + tx.clone(), + &sandbox_id, + &channel_id, + relay_stream, + &command_str, + stdin_payload, + execution_timeout, + request_tty, + no_login_shell, + cols, + rows, + completion, + ) + .await + { + warn!(sandbox_id = %sandbox_id, error = %err, "ExecSandbox failed"); + let _ = tx.send(Err(err)).await; + } + }); + + Ok(Response::new(ReceiverStream::new(rx))) +} + +/// Wait for the supervisor's reverse CONNECT to deliver a relay stream. +/// +/// Returns `Some(stream)` on success. On any failure the error is sent on `tx` +/// and `None` is returned; the caller should then `return` immediately. +async fn await_relay_stream( + relay_rx: oneshot::Receiver>, + tx: &mpsc::Sender>, + sandbox_id: &str, + channel_id: &str, + context: &str, +) -> Option { + match tokio::time::timeout(std::time::Duration::from_secs(10), relay_rx).await { + Ok(Ok(Ok(stream))) => Some(stream), + Ok(Ok(Err(status))) => { + warn!(sandbox_id = %sandbox_id, channel_id = %channel_id, error = %status.message(), "{context}: relay target open failed"); + let _ = tx.send(Err(status)).await; + None + } + Ok(Err(_)) => { + warn!(sandbox_id = %sandbox_id, channel_id = %channel_id, "{context}: relay channel dropped"); + let _ = tx + .send(Err(Status::unavailable("relay channel dropped"))) + .await; + None + } + Err(_) => { + warn!(sandbox_id = %sandbox_id, channel_id = %channel_id, "{context}: relay open timed out"); + let _ = tx + .send(Err(Status::deadline_exceeded("relay open timed out"))) + .await; + None + } + } +} + +pub(super) async fn handle_forward_tcp( + state: &Arc, + request: Request>, +) -> Result< + Response< + Pin> + Send + 'static>>, + >, + Status, +> { + let principal = super::extract_principal(&request)?; + let mut inbound = request.into_inner(); + let first = inbound + .message() + .await? + .ok_or_else(|| Status::invalid_argument("empty ForwardTcp stream"))?; + let Some(openshell_core::proto::tcp_forward_frame::Payload::Init(init)) = first.payload else { + return Err(Status::invalid_argument( + "first TcpForwardFrame must be init", + )); + }; + + super::mutation_audit::record_forward_targets(&init); + let target = validate_tcp_forward_init(&init)?; + + let sandbox = resolve_and_authorize_sandbox_name( + state, + &principal, + &init.sandbox, + &init.workspace, + MinWorkspaceRole::User, + ) + .await?; + + // The main process may finish between minting the SSH token and opening + // its transport. Keep the relay reachable until terminal delivery is + // finalized so fast commands can attach without a readiness race. + if !sandbox_relay_reachable(state, &sandbox).await? { + return Err(Status::failed_precondition("sandbox is not ready")); + } + + let connection_guard = + acquire_forward_connection_guard(state, &principal, &init, &sandbox).await?; + let (channel_id, relay_rx) = crate::supervisor_session::open_routed_relay_with_target( + state, + sandbox.object_id(), + target.clone(), + init.service_id.clone(), + std::time::Duration::from_secs(15), + ) + .await + .map_err(|e| Status::unavailable(format!("supervisor relay failed: {e}")))?; + super::mutation_audit::record_forward_relay( + &sandbox, + &channel_id, + &target, + connection_guard.token.is_none(), + ); + + let (tx, rx) = mpsc::channel::>(256); + let sandbox_id = sandbox.object_id().to_string(); + tokio::spawn(async move { + let _connection_guard = connection_guard; + let Some(relay_stream) = + await_relay_stream(relay_rx, &tx, &sandbox_id, &channel_id, "ForwardTcp").await + else { + return; + }; + + bridge_forward_tcp_stream(inbound, relay_stream, tx, &sandbox_id, &channel_id).await; + }); + + let stream: Pin< + Box> + Send + 'static>, + > = Box::pin(ReceiverStream::new(rx)); + Ok(Response::new(stream)) +} + +/// The per-sandbox relay budget a forward stream draws from. SSH relays and +/// service forwards are counted apart so open forwards cannot starve SSH. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum RelayBudget { + Ssh, + Service, +} + +impl RelayBudget { + fn of(init: &TcpForwardInit) -> Self { + match init.target { + Some(tcp_forward_init::Target::Tcp(_)) => Self::Service, + _ => Self::Ssh, + } + } + + fn counts(self, state: &ServerState) -> &std::sync::Mutex> { + match self { + Self::Ssh => &state.ssh_connections_by_sandbox, + Self::Service => &state.service_connections_by_sandbox, + } + } + + fn limit(self, config: &openshell_core::Config) -> u32 { + match self { + Self::Ssh => config.max_ssh_connections_per_sandbox, + Self::Service => config.max_service_connections_per_sandbox, + } + } + + const fn exhausted_message(self) -> &'static str { + match self { + Self::Ssh => "sandbox SSH connection limit reached", + Self::Service => "sandbox service forward connection limit reached", + } + } +} + +struct ForwardConnectionGuard { + state: Arc, + token: Option, + budget: RelayBudget, + sandbox_id: String, +} + +impl Drop for ForwardConnectionGuard { + fn drop(&mut self) { + if let Some(token) = self.token.as_deref() { + decrement_ssh_connection_count(&self.state.ssh_connections_by_token, token); + } + decrement_ssh_connection_count(self.budget.counts(&self.state), &self.sandbox_id); + } +} + +/// Reserve a relay slot after authorizing the sandbox's workspace. Each SSH +/// transport draws from the same SSH budget. Clients using a session token +/// also draw from its per-token budget, including older TCP forward clients. +async fn acquire_forward_connection_guard( + state: &Arc, + principal: &crate::auth::principal::Principal, + init: &TcpForwardInit, + sandbox: &Sandbox, +) -> Result { + let sandbox_id = sandbox.object_id().to_string(); + let budget = RelayBudget::of(init); + let token = init.authorization_token.trim(); + if let Some(tcp_forward_init::Target::DirectSshSandboxId(expected)) = &init.target { + if !direct_ssh_available(state, principal) { + return Err(crate::auth::audit::deny( + principal, + crate::auth::audit::AuthzDenial::MethodNotPermitted, + "direct SSH admission is unavailable for this request", + )); + } + if *expected != sandbox_id { + return Err(Status::failed_precondition( + "sandbox was replaced before opening the SSH relay", + )); + } + } else if budget == RelayBudget::Ssh && token.is_empty() { + return Err(crate::auth::audit::reject_credential( + Some(principal), + AuthRejection::new( + AuthMechanism::SshSessionToken, + AuthFailureReason::MissingCredential, + Status::unauthenticated("authorization_token is required for SSH targets"), + ), + )); + } + let token = if token.is_empty() { + acquire_sandbox_connection_slot(state, budget, &sandbox_id)?; + None + } else { + let session = validate_ssh_forward_token(state, token, &sandbox_id) + .await + .map_err(|rejection| { + crate::auth::audit::reject_credential(Some(principal), rejection) + })?; + super::mutation_audit::record_ssh_session(session.object_name()); + crate::auth::audit::emit_ssh_session_logon(&state.logons, principal, token); + acquire_ssh_connection_slots(state, budget, token, &sandbox_id)?; + Some(token.to_string()) + }; + + Ok(ForwardConnectionGuard { + state: state.clone(), + token, + budget, + sandbox_id, + }) +} + +#[allow(clippy::result_large_err)] +async fn validate_ssh_forward_token( + state: &Arc, + token: &str, + sandbox_id: &str, +) -> Result { + let reject = + |reason, status| AuthRejection::new(AuthMechanism::SshSessionToken, reason, status); + let session = state + .store + .get_message::(token) + .await + .map_err(|e| { + reject( + AuthFailureReason::IdentityProviderUnavailable, + Status::internal(format!("fetch SSH session failed: {e}")), + ) + })? + .ok_or_else(|| { + reject( + AuthFailureReason::InvalidCredential, + Status::unauthenticated("SSH session token not found"), + ) + })?; + + if session.revoked || session.sandbox_id != sandbox_id { + // A token minted for another sandbox was issued for a different party. + let reason = if session.revoked { + AuthFailureReason::InvalidCredential + } else { + AuthFailureReason::AudienceOrIssuerMismatch + }; + return Err(reject( + reason, + Status::unauthenticated("SSH session token is not valid"), + )); + } + + if let Some(expiration_time) = session.expiration_time.as_ref() { + let now_ms = current_time_ms(); + let expires_at_ms = + openshell_core::time::timestamp_to_millis(expiration_time).map_err(|error| { + reject( + AuthFailureReason::IdentityProviderUnavailable, + Status::internal(error.to_string()), + ) + })?; + if now_ms > expires_at_ms { + return Err(reject( + AuthFailureReason::ExpiredCredential, + Status::unauthenticated("SSH session token expired"), + )); + } + } + + Ok(session) +} + +const MAX_CONNECTIONS_PER_TOKEN: u32 = 3; + +fn acquire_ssh_connection_slots( + state: &ServerState, + budget: RelayBudget, + token: &str, + sandbox_id: &str, +) -> Result<(), Status> { + { + let mut counts = state.ssh_connections_by_token.lock().unwrap(); + let count = counts.entry(token.to_string()).or_insert(0); + if *count >= MAX_CONNECTIONS_PER_TOKEN { + return Err(Status::resource_exhausted( + "SSH session connection limit reached", + )); + } + *count += 1; + } + + if let Err(status) = acquire_sandbox_connection_slot(state, budget, sandbox_id) { + decrement_ssh_connection_count(&state.ssh_connections_by_token, token); + return Err(status); + } + + Ok(()) +} + +/// Reserve one of the sandbox's relay slots in the given budget. +fn acquire_sandbox_connection_slot( + state: &ServerState, + budget: RelayBudget, + sandbox_id: &str, +) -> Result<(), Status> { + let mut counts = budget.counts(state).lock().unwrap(); + let count = counts.entry(sandbox_id.to_string()).or_insert(0); + if *count >= budget.limit(&state.config) { + return Err(Status::resource_exhausted(budget.exhausted_message())); + } + *count += 1; + Ok(()) +} + +fn decrement_ssh_connection_count(counts: &std::sync::Mutex>, key: &str) { + let mut counts = counts.lock().unwrap(); + if let Some(count) = counts.get_mut(key) { + *count = count.saturating_sub(1); + if *count == 0 { + counts.remove(key); + } + } +} + +fn validate_tcp_forward_init(init: &TcpForwardInit) -> Result { + if let Some(target) = init.target.as_ref() { + return match target { + tcp_forward_init::Target::Ssh(_) => { + Ok(relay_open::Target::Ssh(SshRelayTarget::default())) + } + tcp_forward_init::Target::DirectSshSandboxId(id) => { + if validate_ssh_sandbox_id(id).is_err() || !init.authorization_token.is_empty() { + return Err(Status::invalid_argument( + "direct SSH requires a valid sandbox ID and an empty authorization_token", + )); + } + Ok(relay_open::Target::Ssh(SshRelayTarget::default())) + } + tcp_forward_init::Target::Tcp(target) => Ok(relay_open::Target::Tcp( + validate_tcp_forward_target(target)?, + )), + }; + } + + Err(Status::invalid_argument("tcp forward target is required")) +} + +fn validate_tcp_forward_target(target: &TcpRelayTarget) -> Result { + if target.port == 0 || target.port > u32::from(u16::MAX) { + return Err(Status::invalid_argument( + "tcp target port must be between 1 and 65535", + )); + } + + validate_tcp_target_parts(target.host.trim(), target.port).map(|host| TcpRelayTarget { + host, + port: target.port, + }) +} + +fn validate_tcp_target_parts(host: &str, _port: u32) -> Result { + if host.is_empty() { + return Err(Status::invalid_argument("tcp target host is required")); + } + if host.eq_ignore_ascii_case("localhost") { + return Ok("127.0.0.1".to_string()); + } + + let ip: IpAddr = host + .parse() + .map_err(|_| Status::invalid_argument("tcp target host must be loopback"))?; + if ip.is_loopback() { + Ok(ip.to_string()) + } else { + Err(Status::invalid_argument("tcp target host must be loopback")) + } +} + +async fn bridge_forward_tcp_stream( + mut inbound: tonic::Streaming, + relay_stream: S, + tx: mpsc::Sender>, + sandbox_id: &str, + channel_id: &str, +) where + S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Send + 'static, +{ + let (mut relay_read, mut relay_write) = tokio::io::split(relay_stream); + + let sandbox_id_in = sandbox_id.to_string(); + let channel_id_in = channel_id.to_string(); + tokio::spawn(async move { + loop { + match inbound.message().await { + Ok(Some(frame)) => { + let Some(openshell_core::proto::tcp_forward_frame::Payload::Data(data)) = + frame.payload + else { + warn!(sandbox_id = %sandbox_id_in, channel_id = %channel_id_in, "ForwardTcp: received non-data frame after init"); + break; + }; + if data.is_empty() { + continue; + } + if let Err(err) = + tokio::io::AsyncWriteExt::write_all(&mut relay_write, &data).await + { + warn!(sandbox_id = %sandbox_id_in, channel_id = %channel_id_in, error = %err, "ForwardTcp: write to relay failed"); + break; + } + } + Ok(None) => break, + Err(err) => { + debug!(sandbox_id = %sandbox_id_in, channel_id = %channel_id_in, error = %err, "ForwardTcp: inbound stream ended"); + break; + } + } + } + let _ = tokio::io::AsyncWriteExt::shutdown(&mut relay_write).await; + }); + + let mut buf = vec![0u8; TCP_FORWARD_CHUNK_SIZE]; + loop { + match tokio::io::AsyncReadExt::read(&mut relay_read, &mut buf).await { + Ok(0) => break, + Ok(n) => { + let frame = TcpForwardFrame { + payload: Some(openshell_core::proto::tcp_forward_frame::Payload::Data( + buf[..n].to_vec(), + )), + }; + if tx.send(Ok(frame)).await.is_err() { + break; + } + } + Err(err) => { + warn!(sandbox_id = %sandbox_id, channel_id = %channel_id, error = %err, "ForwardTcp: read from relay failed"); + let _ = tx + .send(Err(Status::unavailable(format!( + "relay read failed: {err}" + )))) + .await; + break; + } + } + } +} + +// --------------------------------------------------------------------------- +// Interactive exec handler (bidirectional stdin streaming) +// --------------------------------------------------------------------------- + +pub(super) fn validate_exec_start(req: &ExecSandboxRequest) -> Result<(), Status> { + use openshell_core::rpc_error; + if req.sandbox.is_empty() { + return Err(rpc_error::invalid_argument( + "sandbox", + "sandbox is required", + )); + } + if req.command.is_empty() { + return Err(rpc_error::invalid_argument( + "command", + "command is required", + )); + } + if req.environment.keys().any(|key| !is_valid_env_key(key)) { + return Err(rpc_error::invalid_argument( + "environment", + "environment keys must match ^[A-Za-z_][A-Za-z0-9_]*$", + )); + } + validate_exec_request_fields(req) +} + +fn validate_interactive_exec_start( + msg: Option, +) -> Result { + use openshell_core::proto::exec_sandbox_input::Payload; + + let msg = + msg.ok_or_else(|| Status::invalid_argument("empty stream: expected start message"))?; + + let Some(Payload::Start(req)) = msg.payload else { + return Err(Status::invalid_argument( + "first message must be a start payload", + )); + }; + + validate_exec_start(&req)?; + + Ok(req) +} + +pub(super) async fn handle_exec_sandbox_interactive( + state: &Arc, + request: Request>, +) -> Result>>, Status> { + let (metadata, extensions, mut input_stream) = request.into_parts(); + + let first_msg = input_stream + .message() + .await + .map_err(|e| Status::internal(format!("failed to read first message: {e}")))?; + + let req = validate_interactive_exec_start(first_msg)?; + super::mutation_audit::record_exec_targets(&req); + + let mut request = Request::from_parts( + metadata, + extensions, + ExecSandboxInput { + payload: Some(openshell_core::proto::exec_sandbox_input::Payload::Start( + req, + )), + }, + ); + request + .extensions_mut() + .insert(super::mutation_replay::streaming::InteractiveInput( + Arc::new(tokio::sync::Mutex::new(Some(input_stream))), + )); + super::mutation_replay::run(state, request).await +} + +pub(super) async fn handle_exec_sandbox_interactive_start( + state: &Arc, + request: Request, +) -> Result>>, Status> { + let principal = super::extract_principal(&request)?; + let completion = request + .extensions() + .get::() + .cloned(); + let input = request + .extensions() + .get::() + .ok_or_else(|| Status::internal("interactive input handoff missing"))? + .clone(); + let input_stream = input + .0 + .lock() + .await + .take() + .ok_or_else(|| Status::internal("interactive input already claimed"))?; + let req = super::mutation_replay::streaming::start(request.get_ref())?; + validate_exec_start(req)?; + + let sandbox = resolve_and_authorize_sandbox_name( + state, + &principal, + &req.sandbox, + crate::auth::workspace_authz::selected_workspace_name(req.workspace_scope.as_ref())?, + MinWorkspaceRole::User, + ) + .await?; + + if let Some(completion) = &completion { + completion.ensure_target(sandbox.object_id())?; + } + + require_ready_sandbox(&sandbox)?; + + let (channel_id, relay_rx) = crate::supervisor_session::open_routed_relay_with_target( + state, + sandbox.object_id(), + relay_open::Target::Ssh(SshRelayTarget {}), + String::new(), + std::time::Duration::from_secs(15), + ) + .await + .map_err(|e| Status::unavailable(format!("supervisor relay failed: {e}")))?; + super::mutation_audit::record_exec_relay(&state.config.audit, &sandbox, &channel_id, req); + + let command_str = build_remote_exec_command(req) + .map_err(|e| Status::invalid_argument(format!("command construction failed: {e}")))?; + let request_tty = req.tty; + let no_login_shell = req.no_login_shell; + let execution_timeout = req + .execution_timeout + .as_ref() + .map(openshell_core::time::duration_to_std) + .transpose() + .map_err(|error| Status::invalid_argument(error.to_string()))?; + let (cols, rows) = pty_dimensions(req.cols, req.rows); + + let sandbox_id = sandbox.object_id().to_string(); + + let (tx, rx) = mpsc::channel::>(256); + tokio::spawn(async move { + let Some(relay_stream) = await_relay_stream( + relay_rx, + &tx, + &sandbox_id, + &channel_id, + "ExecSandboxInteractive", + ) + .await + else { + return; + }; + + if let Err(err) = stream_interactive_exec_over_relay( + tx.clone(), + &sandbox_id, + &channel_id, + relay_stream, + &command_str, + input_stream, + request_tty, + no_login_shell, + execution_timeout, + cols, + rows, + completion, + ) + .await + { + warn!(sandbox_id = %sandbox_id, error = %err, "ExecSandboxInteractive failed"); + let _ = tx.send(Err(err)).await; + } + }); + + Ok(Response::new(ReceiverStream::new(rx))) +} + +// --------------------------------------------------------------------------- +// SSH session handlers +// --------------------------------------------------------------------------- + +/// Whether a relay into the sandbox can open: always when `Ready`, and after +/// the main process exits while its supervisor is connected to any replica. +async fn sandbox_relay_reachable( + state: &Arc, + sandbox: &Sandbox, +) -> Result { + match SandboxPhase::try_from(sandbox.phase()).ok() { + Some(SandboxPhase::Ready) => Ok(true), + Some(SandboxPhase::Completed | SandboxPhase::Error) => { + crate::supervisor_session::supervisor_connected(state, sandbox.object_id()).await + } + _ => Ok(false), + } +} + +/// Maximum number of random-name attempts when persisting a new SSH session. +const SSH_SESSION_NAME_ATTEMPTS: usize = 3; +const _: () = assert!(SSH_SESSION_NAME_ATTEMPTS >= 1); + +/// Persist a new SSH session record, retrying with a fresh random name when +/// the insert collides with an existing object name in the workspace. +/// +/// Session names are 6 random lowercase letters and records linger for up to +/// the configured TTL (about two hours with the defaults), so a busy +/// workspace can make a freshly drawn name collide on `objects_name_uq`. A +/// redraw is effectively certain to succeed, so the insert is retried with a +/// regenerated name instead of failing the connection. Any other error, +/// including a primary-key collision on the token, is returned to the caller. +async fn persist_ssh_session( + store: &Store, + session: &mut SshSession, + labels_json: Option<&str>, +) -> PersistenceResult<()> { + // Every caller validates metadata before persisting; the redraw below + // relies on it being present. + debug_assert!(session.metadata.is_some()); + for attempt in 1..=SSH_SESSION_NAME_ATTEMPTS { + let result = store + .create_relaxed( + SshSession::object_type(), + &session.token, + session.object_name(), + session.object_workspace(), + &session.encode_to_vec(), + labels_json, + ) + .await; + match result { + Ok(_) => return Ok(()), + Err(error) + if attempt < SSH_SESSION_NAME_ATTEMPTS + && error.is_unique_violation_on("objects_name_uq") => + { + // A session without metadata cannot be redrawn; surface the + // collision instead of retrying an identical insert. + let Some(metadata) = session.metadata.as_mut() else { + return Err(error); + }; + metadata.name = generate_name(); + } + Err(error) => return Err(error), + } + } + unreachable!("the final attempt returns its error instead of retrying") +} + +pub(super) async fn handle_create_ssh_session( + state: &Arc, + request: Request, +) -> Result, Status> { + let principal = super::extract_principal(&request)?; + let req = request.into_inner(); + let sandbox = resolve_and_authorize_sandbox_name( + state, + &principal, + &req.sandbox, + crate::auth::workspace_authz::selected_workspace_name(req.workspace_scope.as_ref())?, + MinWorkspaceRole::User, + ) + .await?; + let sandbox_id = sandbox.object_id().to_string(); + + if !sandbox_relay_reachable(state, &sandbox).await? { + return Err(Status::failed_precondition("sandbox is not ready")); + } + + let token = uuid::Uuid::new_v4().to_string(); + let now_ms = current_time_ms(); + let expires_at_ms = if state.config.ssh_session_ttl_secs > 0 { + now_ms + (state.config.ssh_session_ttl_secs as i64 * 1000) + } else { + 0 + }; + let mut session = SshSession { + metadata: Some(ObjectMeta { + id: token.clone(), + name: generate_name(), + created_time: openshell_core::time::timestamp_from_millis(now_ms).ok(), + labels: HashMap::new(), + resource_version: 0, + annotations: HashMap::new(), + workspace: sandbox.object_workspace().to_string(), + deletion_time: None, + }), + sandbox_id: sandbox_id.clone(), + token: token.clone(), + revoked: false, + expiration_time: openshell_core::time::optional_timestamp_from_legacy_millis(expires_at_ms) + .map_err(|error| Status::internal(error.to_string()))?, + }; + + // Ensure metadata is valid (defense in depth - should always be true for server-constructed metadata) + super::validation::validate_object_metadata(session.metadata.as_ref(), "ssh_session")?; + + // `create_relaxed` fails if the token already exists, like MustCreate, but + // skips the per-commit fsync on SQLite. Losing a freshly minted token in a + // crash only makes it invalid; revocation stays on the durable `put_if`. + let session_labels = session.object_labels(); + let session_labels_json = if session_labels.as_ref().is_none_or(HashMap::is_empty) { + None + } else { + Some( + serde_json::to_string(&session_labels) + .map_err(|e| Status::internal(format!("failed to serialize labels: {e}")))?, + ) + }; + persist_ssh_session(&state.store, &mut session, session_labels_json.as_deref()) + .await + .map_err(|e| Status::internal(format!("persist ssh session failed: {e}")))?; + super::mutation_audit::record_ssh_session(session.object_name()); + + let (gateway_host, gateway_port) = resolve_gateway(&state.config); + let scheme = if state.config.tls.is_some() { + "https" + } else { + "http" + }; + + Ok(Response::new(CreateSshSessionResponse { + sandbox_id, + token, + gateway_host, + gateway_port: gateway_port.into(), + gateway_scheme: scheme.to_string(), + host_key_fingerprint: sandbox.host_key_fingerprint.clone(), + expiration_time: openshell_core::time::optional_timestamp_from_legacy_millis(expires_at_ms) + .map_err(|error| Status::internal(error.to_string()))?, + })) +} + +pub(super) async fn handle_revoke_ssh_session( + state: &Arc, + request: Request, +) -> Result, Status> { + let principal = super::extract_principal(&request)?; + let req = request.into_inner(); + let token = req.token; + if token.is_empty() { + return Err(Status::invalid_argument("token is required")); + } + + let session = state + .store + .get_message::(&token) + .await + .map_err(|e| Status::internal(format!("fetch ssh session failed: {e}")))?; + + let Some(mut session) = session else { + return Ok(Response::new(RevokeSshSessionResponse { + outcome: super::deletion_outcome(false, req.allow_missing, "ssh session")?, + })); + }; + super::mutation_audit::record_revoked_ssh_session(&session); + authorize_sandbox_workspace( + &state.store, + &state.admin_role, + &principal, + session.object_workspace(), + MinWorkspaceRole::User, + ) + .await + .map_err(|e| { + if e.code() == tonic::Code::PermissionDenied { + Status::not_found("sandbox not found") + } else { + e + } + })?; + + if session.revoked { + super::mutation_audit::record_repeated_revoke(); + return Ok(Response::new(RevokeSshSessionResponse { + outcome: openshell_core::proto::DeletionOutcome::Completed.into(), + })); + } + + let resource_version = session + .metadata + .as_ref() + .map_or(0, |metadata| metadata.resource_version); + + session.revoked = true; + + // Use CAS to prevent lost updates from concurrent revocations + let session_labels = session.object_labels(); + let session_labels_json = if session_labels.as_ref().is_none_or(HashMap::is_empty) { + None + } else { + Some( + serde_json::to_string(&session_labels) + .map_err(|e| Status::internal(format!("failed to serialize labels: {e}")))?, + ) + }; + state + .store + .put_if( + SshSession::object_type(), + session.object_id(), + session.object_name(), + session.object_workspace(), + &session.encode_to_vec(), + session_labels_json.as_deref(), + WriteCondition::MatchResourceVersion(resource_version), + ) + .await + .map_err(|e| super::persistence_error_to_status(e, "revoke ssh session"))?; + + Ok(Response::new(RevokeSshSessionResponse { + outcome: openshell_core::proto::DeletionOutcome::Completed.into(), + })) +} + +// --------------------------------------------------------------------------- +// Exec transport helpers +// --------------------------------------------------------------------------- + +fn resolve_gateway(config: &openshell_core::Config) -> (String, u16) { + ( + config.bind_address.ip().to_string(), + config.bind_address.port(), + ) +} + +/// Shell-escape a value for embedding in a POSIX shell command. +/// +/// Wraps unsafe values in single quotes with the standard `'\''` idiom for +/// embedded single-quote characters. Rejects null bytes which can truncate +/// shell parsing at the C level. +fn shell_escape(value: &str) -> Result { + if value.bytes().any(|b| b == 0) { + return Err("value contains null bytes".to_string()); + } + if value.is_empty() { + return Ok("''".to_string()); + } + let safe = value + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'/' | b'-' | b'_')); + if safe { + return Ok(value.to_string()); + } + let escaped = value.replace('\'', "'\"'\"'"); + Ok(format!("'{escaped}'")) +} + +/// Maximum total length of the assembled shell command string. +const MAX_COMMAND_STRING_LEN: usize = 256 * 1024; // 256 KiB + +/// SSH keepalive for silent exec relays; stdout idle is not a timeout signal. +const EXEC_KEEPALIVE_INTERVAL: std::time::Duration = std::time::Duration::from_secs(15); + +/// Allow this many missed keepalive responses before russh fails the relay. +const EXEC_KEEPALIVE_MAX: usize = 4; + +/// Max wait for a trailing `Close` after `ExitStatus`. +const EXEC_POST_EXIT_CLOSE_TIMEOUT: std::time::Duration = std::time::Duration::from_millis(500); + +/// Supervisor SSH banner software token that signals no-login-shell support. +const OPENSHELL_SSHID_PREFIX: &[u8] = b"SSH-2.0-OpenShell_"; + +/// A supervisor honors `OPENSHELL_NO_LOGIN_SHELL` only if it identifies as +/// `OpenShell`. Older sandboxes present russh's default banner and silently +/// ignore the env request, so gate the opt-out on the `OpenShell` identity. +fn supervisor_supports_no_login_shell(remote_sshid: &[u8]) -> bool { + remote_sshid.starts_with(OPENSHELL_SSHID_PREFIX) +} + +/// russh client config for exec relays. +fn exec_ssh_client_config() -> russh::client::Config { + russh::client::Config { + keepalive_interval: Some(EXEC_KEEPALIVE_INTERVAL), + keepalive_max: EXEC_KEEPALIVE_MAX, + ..Default::default() + } +} + +/// Require both the command status and channel close before reporting success. +fn exec_loop_result(exit_code: Option, close_seen: bool) -> Result { + match (exit_code, close_seen) { + (Some(code), true) => Ok(code), + (None, _) => Err(Status::unavailable( + "exec relay closed before the command reported an exit status", + )), + (Some(_), false) => Err(Status::unavailable( + "exec relay closed before the SSH channel finished", + )), + } +} + +fn build_remote_exec_command(req: &ExecSandboxRequest) -> Result { + let mut parts = Vec::new(); + let mut env_entries = req.environment.iter().collect::>(); + env_entries.sort_by_key(|(a, _)| *a); + for (key, value) in env_entries { + parts.push(format!("{key}={}", shell_escape(value)?)); + } + for arg in &req.command { + parts.push(shell_escape(arg)?); + } + let command = parts.join(" "); + let result = if req.workdir.is_empty() { + command + } else { + format!("cd {} && {command}", shell_escape(&req.workdir)?) + }; + if result.len() > MAX_COMMAND_STRING_LEN { + return Err(format!( + "assembled command string exceeds {MAX_COMMAND_STRING_LEN} byte limit" + )); + } + Ok(result) +} + +/// Execute a command over an SSH transport relayed through a supervisor session. +/// +/// This is the relay equivalent of `stream_exec_over_ssh`. Instead of dialing a +/// sandbox endpoint directly, the SSH transport runs over a `DuplexStream` that +/// is bridged to the supervisor's local SSH daemon via `RelayStream`. +#[allow(clippy::too_many_arguments)] +async fn stream_exec_over_relay( + tx: mpsc::Sender>, + sandbox_id: &str, + channel_id: &str, + relay_stream: tokio::io::DuplexStream, + command: &str, + stdin_payload: Vec, + execution_timeout: Option, + request_tty: bool, + no_login_shell: bool, + cols: u32, + rows: u32, + completion: Option, +) -> Result<(), Status> { + let command_preview: String = command + .chars() + .take(120) + .flat_map(char::escape_default) + .collect(); + info!( + sandbox_id = %sandbox_id, + channel_id = %channel_id, + command_len = command.len(), + stdin_len = stdin_payload.len(), + command_preview = %command_preview, + "ExecSandbox (relay): command started" + ); + + let (local_proxy_port, proxy_task) = start_single_use_ssh_proxy_over_relay(relay_stream) + .await + .map_err(|e| Status::internal(format!("failed to start relay proxy: {e}")))?; + + let exec = run_exec_with_russh( + local_proxy_port, + command, + stdin_payload, + request_tty, + no_login_shell, + (cols, rows), + tx.clone(), + ); + + let exec_result = wait_for_exec_terminal(exec, execution_timeout, completion).await; + if matches!(exec_result, Ok(None)) { + let _ = tx + .send(Ok(ExecSandboxEvent { + payload: Some(openshell_core::proto::exec_sandbox_event::Payload::Exit( + ExecSandboxExit { exit_code: 124 }, + )), + })) + .await; + finish_interactive_exec_proxy(proxy_task).await; + return Ok(()); + } + + let exit_code = match exec_result { + Ok(Some(code)) => code, + Ok(None) => unreachable!("timeout returned above"), + Err(status) => { + finish_interactive_exec_proxy(proxy_task).await; + return Err(status); + } + }; + + finish_interactive_exec_proxy(proxy_task).await; + + let _ = tx + .send(Ok(ExecSandboxEvent { + payload: Some(openshell_core::proto::exec_sandbox_event::Payload::Exit( + ExecSandboxExit { exit_code }, + )), + })) + .await; + + Ok(()) +} + +#[allow(clippy::too_many_arguments)] +async fn stream_interactive_exec_over_relay( + tx: mpsc::Sender>, + sandbox_id: &str, + channel_id: &str, + relay_stream: tokio::io::DuplexStream, + command: &str, + input_stream: tonic::Streaming, + request_tty: bool, + no_login_shell: bool, + execution_timeout: Option, + cols: u32, + rows: u32, + completion: Option, +) -> Result<(), Status> { + let command_preview: String = command + .chars() + .take(120) + .flat_map(char::escape_default) + .collect(); + info!( + sandbox_id = %sandbox_id, + channel_id = %channel_id, + command_len = command.len(), + command_preview = %command_preview, + "ExecSandboxInteractive (relay): command started" + ); + + let (local_proxy_port, proxy_task) = start_single_use_ssh_proxy_over_relay(relay_stream) + .await + .map_err(|e| Status::internal(format!("failed to start relay proxy: {e}")))?; + + let exec = run_interactive_exec_with_russh( + local_proxy_port, + command, + input_stream, + request_tty, + no_login_shell, + cols, + rows, + tx.clone(), + ); + + let exec_result = wait_for_exec_terminal(exec, execution_timeout, completion).await; + if matches!(exec_result, Ok(None)) { + let _ = tx + .send(Ok(ExecSandboxEvent { + payload: Some(openshell_core::proto::exec_sandbox_event::Payload::Exit( + ExecSandboxExit { exit_code: 124 }, + )), + })) + .await; + finish_interactive_exec_proxy(proxy_task).await; + return Ok(()); + } + + let exit_code = match exec_result { + Ok(Some(code)) => code, + Ok(None) => unreachable!("timeout returned above"), + Err(status) => { + finish_interactive_exec_proxy(proxy_task).await; + return Err(status); + } + }; + + finish_interactive_exec_proxy(proxy_task).await; + + let _ = tx + .send(Ok(ExecSandboxEvent { + payload: Some(openshell_core::proto::exec_sandbox_event::Payload::Exit( + ExecSandboxExit { exit_code }, + )), + })) + .await; + + Ok(()) +} + +/// `Ok(Some(code))` requires a real SSH `ExitStatus`, including nonzero codes. +/// Synthetic gateway timeouts, lost status, and dropped futures leave the claim +/// unresolved. Finalization precedes terminal delivery to the client. +pub(super) async fn wait_for_exec_terminal( + exec: impl Future>, + execution_timeout: Option, + completion: Option, +) -> Result, Status> { + let result = if let Some(execution_timeout) = execution_timeout { + match tokio::time::timeout(execution_timeout, exec).await { + Ok(result) => result, + Err(_) => return Ok(None), + } + } else { + exec.await + }; + let exit_code = result?; + if let Some(completion) = completion { + completion.stream_terminal().await?; + } + Ok(Some(exit_code)) +} + +async fn finish_interactive_exec_proxy(mut task: tokio::task::JoinHandle<()>) { + if tokio::time::timeout(EXEC_POST_EXIT_CLOSE_TIMEOUT, &mut task) + .await + .is_err() + { + task.abort(); + let _ = task.await; + } +} + +#[allow(clippy::too_many_arguments)] +async fn run_interactive_exec_with_russh( + local_proxy_port: u16, + command: &str, + mut input_stream: impl futures::Stream> + Unpin, + request_tty: bool, + no_login_shell: bool, + cols: u32, + rows: u32, + tx: mpsc::Sender>, +) -> Result { + use futures::StreamExt; + use openshell_core::proto::exec_sandbox_input::Payload; + use russh::ChannelMsg; + + if command.as_bytes().contains(&0) { + return Err(Status::invalid_argument( + "command contains null bytes at transport boundary", + )); + } + if command.len() > MAX_COMMAND_STRING_LEN { + return Err(Status::invalid_argument(format!( + "command exceeds {MAX_COMMAND_STRING_LEN} byte limit at transport boundary" + ))); + } - if let Some(resume) = resume_after { - // Resume: replay events strictly after the client's cursor from both - // resumable buses. Either bus reporting a trimmed range is an - // unrecoverable gap -> terminate with a documented status. - use openshell_core::proto::sandbox_stream_event::Payload; + let stream = + openshell_core::net::connect_tcp_nodelay_best_effort(("127.0.0.1", local_proxy_port)) + .await + .map_err(|e| Status::internal(format!("failed to connect to ssh proxy: {e}")))?; - // A cursor is only a position inside the space that issued it. - // A gateway restart, a bus teardown, or a reconnect landing on - // another replica starts a new space numbered from 1 with no - // record of the cursors the old one handed out. The buses then - // look merely empty, so `tail_after` reports no gap -- treating - // that as "caught up" would pin the cutoff to a stale number - // and silently swallow every live event beneath it. Comparing - // epochs answers "did this cursor come from *this* space?", - // which no numeric bound can. - match state.tracing_log_bus.cursor_space(&sandbox_id) { - None => { - let _ = tx.send(Err(Status::out_of_range(RESUME_SPACE_GONE))).await; - return; - } - Some(space) if space.epoch != resume.epoch => { - let _ = tx.send(Err(Status::out_of_range(RESUME_SPACE_GONE))).await; - return; - } - // Right space, but ahead of anything it issued: only a - // fabricated token gets here. Reject rather than accept a - // cutoff no event can ever exceed. - Some(space) if resume.seq > space.highest_seq => { - let _ = tx - .send(Err(Status::out_of_range(RESUME_CURSOR_AHEAD))) - .await; - return; - } - Some(_) => {} - } + let config = Arc::new(exec_ssh_client_config()); + let remote_sshid = Arc::new(std::sync::Mutex::new(None)); + let handler = SandboxSshClientHandler { + remote_sshid: remote_sshid.clone(), + }; + let mut client = russh::client::connect_stream(config, stream, handler) + .await + .map_err(|e| Status::internal(format!("failed to establish ssh transport: {e}")))?; - let log_replay = if follow_logs { - Some(state.tracing_log_bus.tail_after(&sandbox_id, resume.seq)) - } else { - None - }; + match client + .authenticate_none("sandbox") + .await + .map_err(|e| Status::internal(format!("failed to authenticate ssh session: {e}")))? + { + AuthResult::Success => {} + AuthResult::Failure { .. } => { + return Err(Status::permission_denied( + "ssh authentication rejected by sandbox", + )); + } + } - let platform_replay = if follow_events { - Some( - state - .tracing_log_bus - .platform_event_bus - .tail_after(&sandbox_id, resume.seq), - ) - } else { - None - }; + let channel = client + .channel_open_session() + .await + .map_err(|e| Status::internal(format!("failed to open ssh channel: {e}")))?; - // Re-check the epoch now that both tails are in hand. The check - // above and each `tail_after` take their locks independently, so - // a teardown plus a republish can retire the validated space and - // install a replacement in between. The reads would then have - // applied the old space's seq to the new space's buffers, and - // `tail_after` -- which only knows numbers -- would report no gap - // while skipping every replacement event at or below it. The - // second look is cheap and runs before anything is emitted, so a - // space that moved under us ends the stream instead of serving a - // truncated replay. - // - // Ordering is unchanged: this takes only the allocator lock and - // releases it, never held across a bus lock. - if !cursor_space_is(&state, &sandbox_id, resume.epoch) { - let _ = tx.send(Err(Status::out_of_range(RESUME_SPACE_GONE))).await; - return; - } + if request_tty { + channel + .request_pty(false, "xterm-256color", cols, rows, 0, 0, &[]) + .await + .map_err(|e| Status::internal(format!("failed to allocate PTY: {e}")))?; + } - // Gap check FIRST (borrows), before the merge moves the vecs. - for replay in [&log_replay, &platform_replay] { - if let Some(Err(gap)) = replay { - let _ = tx.send(Err(Status::out_of_range(format!( - "resume cursor {} is no longer available; earliest resumable cursor is {}", - gap.requested_after, gap.oldest_available - )))) - .await; - return; - } - } + if no_login_shell { + let banner = remote_sshid.lock().unwrap().clone().unwrap_or_default(); + if !supervisor_supports_no_login_shell(&banner) { + return Err(Status::failed_precondition( + "sandbox supervisor is too old to honor --no-login-shell; recreate the sandbox on a current gateway", + )); + } + channel + .set_env(false, NO_LOGIN_SHELL_ENV.0, NO_LOGIN_SHELL_ENV.1) + .await + .map_err(|e| Status::internal(format!("failed to set login-shell env: {e}")))?; + } - // Merge both buses by shared seq, then emit ascending. Each - // source's mark comes from its own replay -- `tail_after` - // returns ascending, so its last entry is that source's high - // water. Marking every event the phase examined, not only the - // ones that survived the filters, keeps a filtered event's live - // duplicate suppressed: the live loop does not re-apply - // `log_since_time` and would otherwise let it through. - let mut merged: Vec = Vec::new(); - if let Some(Ok(v)) = log_replay { - if let Some(last) = v.last() { - log_cutoff = log_cutoff.max(last.seq); - } - merged.extend(v); + channel + .exec(true, command.as_bytes()) + .await + .map_err(|e| Status::internal(format!("failed to execute command over ssh: {e}")))?; + + let (mut read_half, write_half) = channel.split(); + + // Keep both directions independently polled, but owned by this operation. + // A detached stdin task would survive operation timeout and retain the SSH + // channel. Normal request EOF closes stdin only, never the output channel. + let input = async { + while let Some(msg) = input_stream.next().await { + // Even ignored non-PTY resize frames must cooperate with output + // and cancellation when the request stream stays continuously ready. + tokio::task::consume_budget().await; + let msg = msg?; + match msg.payload { + Some(Payload::Stdin(data)) => { + write_half + .data(std::io::Cursor::new(data)) + .await + .map_err(|_| { + Status::unavailable("exec relay failed while writing stdin") + })?; } - if let Some(Ok(v)) = platform_replay { - if let Some(last) = v.last() { - platform_cutoff = platform_cutoff.max(last.seq); + Some(Payload::Resize(resize)) => { + if request_tty { + write_half + .window_change(resize.cols, resize.rows, 0, 0) + .await + .map_err(|_| Status::unavailable("exec relay failed while resizing"))?; } - merged.extend(v); } + Some(Payload::Start(_)) | None => { + return Err(Status::invalid_argument( + "expected stdin or resize after exec start", + )); + } + } + } + write_half + .eof() + .await + .map_err(|_| Status::unavailable("exec relay failed while closing stdin")) + }; - merged.sort_by_key(|c| c.seq); - - for cursored in merged { - if let Some(Payload::Log(ref log)) = cursored.event.payload { - if let Some(since_time) = log_since_time.as_ref() { - let Some(event_time) = log.event_time.as_ref() else { - continue; - }; - let Ok(ordering) = - openshell_core::time::compare_timestamps(event_time, since_time) - else { - continue; - }; - if ordering == std::cmp::Ordering::Less { - continue; - } - } - if !log_sources.is_empty() && !source_matches(&log.source, &log_sources) { - continue; - } - if !level_matches(&log.level, &log_min_level) { - continue; - } - } - if tx.send(Ok(cursored.event)).await.is_err() { - return; - } + let output = async { + let mut exit_code: Option = None; + let mut close_seen = false; + loop { + // Bound the post-ExitStatus wait against a lost Close. + let msg = if exit_code.is_some() { + match tokio::time::timeout(EXEC_POST_EXIT_CLOSE_TIMEOUT, read_half.wait()).await { + Ok(Some(msg)) => msg, + Ok(None) | Err(_) => break, } } else { - // Initial tail, best-effort. Both buses draw from one shared - // cursor space, so draining each in its own pass would order the - // tail by source and only incidentally by cursor: every buffered - // log would precede every buffered platform event regardless of - // which was published first. Collect both windows, sort by the - // shared seq, and emit one ascending run -- the same shape the - // resume path above uses, and the order a client comparing - // cursors expects. - // - // The two windows are truncated independently (log_tail vs - // event_tail), so this merges whatever each bus retained; it - // does not align their depths. - let mut tail: Vec = Vec::new(); - if follow_logs { - let logs = state.tracing_log_bus.tail(&sandbox_id, log_tail as usize); - if let Some(last) = logs.last() { - log_cutoff = log_cutoff.max(last.seq); + match read_half.wait().await { + Some(msg) => msg, + None => break, + } + }; + match msg { + ChannelMsg::Data { data } => { + let event = Ok(ExecSandboxEvent { + payload: Some(openshell_core::proto::exec_sandbox_event::Payload::Stdout( + ExecSandboxStdout { + data: data.to_vec(), + }, + )), + }); + if tx.send(event).await.is_err() { + break; } - tail.extend(logs); } - if follow_events { - let events = state - .tracing_log_bus - .platform_event_bus - .tail(&sandbox_id, event_tail as usize); - if let Some(last) = events.last() { - platform_cutoff = platform_cutoff.max(last.seq); + ChannelMsg::ExtendedData { data, .. } => { + let event = Ok(ExecSandboxEvent { + payload: Some(openshell_core::proto::exec_sandbox_event::Payload::Stderr( + ExecSandboxStderr { + data: data.to_vec(), + }, + )), + }); + if tx.send(event).await.is_err() { + break; } - tail.extend(events); } + ChannelMsg::ExitStatus { exit_status } => { + let converted = i32::try_from(exit_status).unwrap_or(i32::MAX); + exit_code = Some(converted); + } + ChannelMsg::Close => { + close_seen = true; + break; + } + _ => {} + } + } - tail.sort_by_key(|cursored| cursored.seq); + exec_loop_result(exit_code, close_seen) + }; - for cursored in tail { - // Log filters; platform events carry no log fields and pass. - if let Some(openshell_core::proto::sandbox_stream_event::Payload::Log( - ref log, - )) = cursored.event.payload - { - if let Some(since_time) = log_since_time.as_ref() { - let Some(event_time) = log.event_time.as_ref() else { - continue; - }; - let Ok(ordering) = - openshell_core::time::compare_timestamps(event_time, since_time) - else { - continue; - }; - if ordering == std::cmp::Ordering::Less { - continue; - } - } - if !log_sources.is_empty() && !source_matches(&log.source, &log_sources) { - continue; - } - if !level_matches(&log.level, &log_min_level) { - continue; - } - } - if tx.send(Ok(cursored.event)).await.is_err() { - return; - } + let result = { + tokio::pin!(input, output); + let exchange = async { + tokio::select! { + result = &mut input => { + result?; + output.await } + result = &mut output => result, } + }; + tokio::select! { + biased; + () = tx.closed() => Err(Status::cancelled("exec response stream closed")), + result = exchange => result, + } + }; - // Events drained above the publication watermark. They are held - // back rather than emitted so the client's highest delivered cursor - // is never above an event still queued on the other source. - let mut deferred: Vec> = Vec::new(); + // EOF above deliberately leaves this channel open until output completes. + // Bound cleanup even if the SSH peer is no longer making progress. + let _ = tokio::time::timeout(EXEC_POST_EXIT_CLOSE_TIMEOUT, write_half.close()).await; + let _ = tokio::time::timeout( + EXEC_POST_EXIT_CLOSE_TIMEOUT, + client.disconnect(russh::Disconnect::ByApplication, "exec complete", "en"), + ) + .await; - loop { - // Events withheld by the previous round are already in hand, so - // this round must not block on a new publication: the watermark - // that covers them has already advanced past them, and waiting - // for unrelated traffic would stall their delivery indefinitely. - let first = if deferred.is_empty() { - Some(tokio::select! { - () = tx.closed() => { - return; - } - res = async { - match status_rx.as_mut() { - Some(rx) => rx.recv().await, - None => future::pending().await, - } - } => { - match res { - Ok(()) => { - match state.store.get_message::(&sandbox_id).await { - Ok(Some(sandbox)) => { - state.sandbox_index.update_from_sandbox(&sandbox); - if tx.send(Ok(SandboxStreamEvent { payload: Some(openshell_core::proto::sandbox_stream_event::Payload::Sandbox(sandbox.clone())), cursor: String::new() })).await.is_err() { - return; - } - if stop_on_terminal { - let phase = SandboxPhase::try_from(sandbox.phase()).unwrap_or(SandboxPhase::Unknown); - if is_watch_terminal(phase) { - return; - } - } - } - Ok(None) => { - return; - } - Err(e) => { - let _ = tx.send(Err(Status::internal(format!("fetch sandbox failed: {e}")))).await; - return; - } - } - } - Err(broadcast::error::RecvError::Lagged(n)) => { - // Lag is recoverable: surface a warning and keep streaming. - if tx.send(Ok(crate::sandbox_watch::lag_warning_event(n))).await.is_err() { - return; - } - } - Err(broadcast::error::RecvError::Closed) => { - let _ = tx.send(Err(Status::cancelled("stream closed"))).await; - return; - } - } - // Status snapshots carry cursor 0 and are outside the - // resumable cursor space, so they never join a batch. - continue; - } - // Both resumable sources feed one cursor space, so neither - // can be emitted on its own: `select!` picks an arbitrary - // ready branch, which would emit a higher cursor ahead of a - // lower one waiting on the other source. Take whichever woke - // us as the start of a batch and merge below. - res = async { - match log_rx.as_mut() { - Some(rx) => rx.recv().await, - None => future::pending().await, - } - } => res, - res = async { - match platform_rx.as_mut() { - Some(rx) => rx.recv().await, - None => future::pending().await, - } - } => res, - }) - } else { - None - }; + result +} + +/// Create a localhost SSH proxy that bridges to a relay `DuplexStream`. +/// +/// The proxy forwards raw SSH bytes between the `russh` client and the relay. +/// The supervisor bridges the relay to its Unix-socket SSH daemon; filesystem +/// permissions on that socket are the only access-control boundary. +async fn start_single_use_ssh_proxy_over_relay( + mut relay_stream: tokio::io::DuplexStream, +) -> Result<(u16, tokio::task::JoinHandle<()>), Box> { + let listener = TcpListener::bind(("127.0.0.1", 0)).await?; + let port = listener.local_addr()?.port(); + + let task = tokio::spawn(async move { + let Ok((mut client_conn, _)) = listener.accept().await else { + warn!("SSH relay proxy: failed to accept local connection"); + return; + }; + // Loopback bridge for interactive SSH exec (keystrokes, line-buffered + // PTY output) — disable Nagle so tinygrams don't stall on delayed ACKs. + set_tcp_nodelay_best_effort(&client_conn); + let _ = tokio::io::copy_bidirectional(&mut client_conn, &mut relay_stream).await; + }); + + Ok((port, task)) +} + +#[derive(Debug, Clone)] +struct SandboxSshClientHandler { + remote_sshid: Arc>>>, +} + +impl russh::client::Handler for SandboxSshClientHandler { + type Error = russh::Error; + + async fn check_server_key( + &mut self, + _server_public_key: &russh::keys::PublicKeyOrCertificate, + ) -> Result { + Ok(true) + } + + async fn kex_done( + &mut self, + _shared_secret: Option<&[u8]>, + _names: &russh::Names, + session: &mut russh::client::Session, + ) -> Result<(), Self::Error> { + *self.remote_sshid.lock().unwrap() = Some(session.remote_sshid().to_vec()); + Ok(()) + } +} + +async fn run_exec_with_russh( + local_proxy_port: u16, + command: &str, + stdin_payload: Vec, + request_tty: bool, + no_shell_login: bool, + pty_size: (u32, u32), + tx: mpsc::Sender>, +) -> Result { + let (cols, rows) = pty_size; + + // Defense-in-depth: validate command at the transport boundary. + if command.as_bytes().contains(&0) { + return Err(Status::invalid_argument( + "command contains null bytes at transport boundary", + )); + } + if command.len() > MAX_COMMAND_STRING_LEN { + return Err(Status::invalid_argument(format!( + "command exceeds {MAX_COMMAND_STRING_LEN} byte limit at transport boundary" + ))); + } + + let stream = + openshell_core::net::connect_tcp_nodelay_best_effort(("127.0.0.1", local_proxy_port)) + .await + .map_err(|e| Status::internal(format!("failed to connect to ssh proxy: {e}")))?; + + let config = Arc::new(exec_ssh_client_config()); + let remote_sshid = Arc::new(std::sync::Mutex::new(None)); + let handler = SandboxSshClientHandler { + remote_sshid: remote_sshid.clone(), + }; + let mut client = russh::client::connect_stream(config, stream, handler) + .await + .map_err(|e| Status::internal(format!("failed to establish ssh transport: {e}")))?; - let mut batch = std::mem::take(&mut deferred); - match first { - None => {} - Some(Ok(evt)) => batch.push(evt), - Some(Err(broadcast::error::RecvError::Lagged(n))) => { - // Lag is recoverable: surface a warning and keep streaming. - if tx - .send(Ok(crate::sandbox_watch::lag_warning_event(n))) - .await - .is_err() - { - return; - } - // Carry any withheld events into the next round rather - // than dropping them with this batch. - deferred = batch; - continue; - } - Some(Err(broadcast::error::RecvError::Closed)) => { - let _ = tx.send(Err(Status::cancelled("stream closed"))).await; - return; - } - } + match client + .authenticate_none("sandbox") + .await + .map_err(|e| Status::internal(format!("failed to authenticate ssh session: {e}")))? + { + AuthResult::Success => {} + AuthResult::Failure { .. } => { + return Err(Status::permission_denied( + "ssh authentication rejected by sandbox", + )); + } + } - // Read the publication watermark before draining. Publishers - // assign a sequence and push it onto their broadcast channel - // under one allocator lock, so every event at or below the - // sequence observed here has already reached its channel and - // the drain below is guaranteed to see it. Reading after the - // drain would admit a publish into the gap and defeat this. - // - // `None` means the cursor space is gone (teardown). Nothing - // further can be published into it, so nothing is withheld. - let watermark = state - .tracing_log_bus - .cursor_space(&sandbox_id) - .map_or(u64::MAX, |space| space.highest_seq); + let mut channel = client + .channel_open_session() + .await + .map_err(|e| Status::internal(format!("failed to open ssh channel: {e}")))?; - // Drain what is already queued on both sources. Sorting the - // batch restores cursor order across the two sources without - // waiting on either one. - let mut lagged = 0u64; - let mut closed = false; - for rx in [log_rx.as_mut(), platform_rx.as_mut()] - .into_iter() - .flatten() - { - loop { - match rx.try_recv() { - Ok(evt) => batch.push(evt), - Err(broadcast::error::TryRecvError::Empty) => break, - // Keep draining: the receiver is usable after a skip. - Err(broadcast::error::TryRecvError::Lagged(n)) => lagged += n, - Err(broadcast::error::TryRecvError::Closed) => { - closed = true; - break; - } - } - } - } + if request_tty { + channel + .request_pty(false, "xterm-256color", cols, rows, 0, 0, &[]) + .await + .map_err(|e| Status::internal(format!("failed to allocate PTY: {e}")))?; + } - batch.sort_by_key(|cursored| cursored.seq); + if no_shell_login { + let banner = remote_sshid.lock().unwrap().clone().unwrap_or_default(); + if !supervisor_supports_no_login_shell(&banner) { + return Err(Status::failed_precondition( + "sandbox supervisor is too old to honor --no-login-shell; recreate the sandbox on a current gateway", + )); + } + channel + .set_env(false, NO_LOGIN_SHELL_ENV.0, NO_LOGIN_SHELL_ENV.1) + .await + .map_err(|e| Status::internal(format!("failed to set login-shell env: {e}")))?; + } - // Withhold anything above the watermark. Such an event was - // published after the drain started, so a lower-cursor event - // from the other source may still be queued behind it. Emitting - // it now would let the client checkpoint above an event it has - // not seen, and resume past it after a disconnect. The next - // round re-reads the watermark, which by then covers these. - let held_from = batch.partition_point(|cursored| cursored.seq <= watermark); - deferred = batch.split_off(held_from); + channel + .exec(true, command.as_bytes()) + .await + .map_err(|e| Status::internal(format!("failed to execute command over ssh: {e}")))?; - // Announce the gap before any event from this batch. A warning - // carries no cursor and is never replayed, so emitting it after - // the events lets a disconnect at the wrong moment strand the - // client past the gap: it would resume from a cursor above the - // skipped events having never learned they were dropped. - if lagged > 0 - && tx - .send(Ok(crate::sandbox_watch::lag_warning_event(lagged))) - .await - .is_err() - { - return; - } + if !stdin_payload.is_empty() { + channel + .data(std::io::Cursor::new(stdin_payload)) + .await + .map_err(|e| Status::internal(format!("failed to send ssh stdin payload: {e}")))?; + } - for cursored in batch { - // Skip events the tail/replay phase already handled, judged - // against the mark for this event's own source. Bus events - // always carry seq >= 1, so no sentinel is needed here: - // non-resumable events never reach this batch. - let is_log = matches!( - cursored.event.payload, - Some(openshell_core::proto::sandbox_stream_event::Payload::Log(_)) - ); - let cutoff = if is_log { log_cutoff } else { platform_cutoff }; - if cursored.seq <= cutoff { - continue; - } - if let Some(openshell_core::proto::sandbox_stream_event::Payload::Log( - ref log, - )) = cursored.event.payload - { - if !log_sources.is_empty() && !source_matches(&log.source, &log_sources) { - continue; - } - if !level_matches(&log.level, &log_min_level) { - continue; - } - } - if tx - .send(Ok(Arc::unwrap_or_clone(cursored).event)) - .await - .is_err() - { - return; - } - } + channel + .eof() + .await + .map_err(|e| Status::internal(format!("failed to close ssh stdin: {e}")))?; - if closed { - let _ = tx.send(Err(Status::cancelled("stream closed"))).await; - return; - } + let mut exit_code: Option = None; + let mut close_seen = false; + loop { + // Bound the post-ExitStatus wait against a lost Close. + let msg = if exit_code.is_some() { + match tokio::time::timeout(EXEC_POST_EXIT_CLOSE_TIMEOUT, channel.wait()).await { + Ok(Some(msg)) => msg, + Ok(None) | Err(_) => break, } - }, - request_span, - )); + } else { + match channel.wait().await { + Some(msg) => msg, + None => break, + } + }; + match msg { + ChannelMsg::Data { data } => { + let _ = tx + .send(Ok(ExecSandboxEvent { + payload: Some(openshell_core::proto::exec_sandbox_event::Payload::Stdout( + ExecSandboxStdout { + data: data.to_vec(), + }, + )), + })) + .await; + } + ChannelMsg::ExtendedData { data, .. } => { + let _ = tx + .send(Ok(ExecSandboxEvent { + payload: Some(openshell_core::proto::exec_sandbox_event::Payload::Stderr( + ExecSandboxStderr { + data: data.to_vec(), + }, + )), + })) + .await; + } + ChannelMsg::ExitStatus { exit_status } => { + let converted = i32::try_from(exit_status).unwrap_or(i32::MAX); + exit_code = Some(converted); + } + ChannelMsg::Close => { + close_seen = true; + break; + } + _ => {} + } + } - Ok(Response::new(WatchSandboxStream::new(rx, producer))) -} + let _ = channel.close().await; + let _ = client + .disconnect(russh::Disconnect::ByApplication, "exec complete", "en") + .await; -fn is_watch_terminal(phase: SandboxPhase) -> bool { - matches!( - phase, - SandboxPhase::Ready - | SandboxPhase::Completed - | SandboxPhase::Stopped - | SandboxPhase::Suspended - | SandboxPhase::Error - ) + exec_loop_result(exit_code, close_seen) } // --------------------------------------------------------------------------- -// Exec handler +// Tests // --------------------------------------------------------------------------- -const DEFAULT_PTY_COLS: u32 = 80; -const DEFAULT_PTY_ROWS: u32 = 24; +#[cfg(test)] +mod tests { + use super::*; + use crate::auth::audit::test_support::{ + assert_authentication_failure, assert_boundary_finding, assert_logon, assert_origin, + assert_redacted, audited, + }; + use crate::compute::NoopTestDriver; -fn pty_dimensions(cols: u32, rows: u32) -> (u32, u32) { - ( - if cols == 0 { DEFAULT_PTY_COLS } else { cols }, - if rows == 0 { DEFAULT_PTY_ROWS } else { rows }, - ) -} + #[test] + fn exec_requires_ssh_channel_close_after_exit_status() { + assert_eq!(exec_loop_result(Some(0), true).unwrap(), 0); + assert!(exec_loop_result(Some(0), false).is_err()); + assert!(exec_loop_result(None, true).is_err()); + } + use crate::grpc::test_support::{ + authed_request, test_server_state, test_server_state_with_compute_driver, + test_server_state_with_driver, + }; + use openshell_core::proto::datamodel::v1::ObjectMeta; + use openshell_core::proto::{ + GpuResourceRequirements, SandboxServiceExposure, ServiceAuthorizationMode, ServiceEndpoint, + }; -pub(super) async fn handle_exec_sandbox( - state: &Arc, - request: Request, -) -> Result>>, Status> { - use openshell_core::ObjectId; + #[cfg(not(feature = "experimental"))] + /// A test state whose compute driver records provisioning calls. + async fn test_server_state_with_fake_driver() -> ( + Arc, + Arc, + ) { + let mut state = test_server_state().await; + let driver = Arc::new( + crate::test_support::FakeComputeDriver::new().with_capabilities( + openshell_core::proto::compute::v1::GetCapabilitiesResponse { + driver_name: "test".to_string(), + default_image: "test/image:latest".to_string(), + resource_admission_policy: + openshell_core::resource_admission::DriverAdmissionConfig::default() + .acknowledgement(), + extension: Some(openshell_core::extension_protocol::extension_metadata( + openshell_core::extension_protocol::ExtensionFamily::Compute, + "test/fake", + "test", + [], + )), + ..Default::default() + }, + ), + ); + let compute = crate::compute::ComputeRuntime::from_driver( + "test".to_string(), + driver.clone(), + None, + state.store.clone(), + crate::sandbox_index::SandboxIndex::new(), + crate::sandbox_watch::SandboxWatchBus::new(), + crate::tracing_bus::TracingLogBus::new(), + Arc::new(crate::supervisor_session::SupervisorSessionRegistry::new()), + ) + .await + .unwrap(); + Arc::get_mut(&mut state).unwrap().compute = compute; + driver.clear_calls(); + (state, driver) + } - let principal = super::extract_principal(&request)?; - let completion = request - .extensions() - .get::() - .cloned(); - let req = request.into_inner(); - validate_exec_start(&req)?; + #[cfg(not(feature = "experimental"))] + fn create_request_with_policy( + name: &str, + policy: openshell_core::proto::SandboxPolicy, + ) -> Request { + authed_request(CreateSandboxRequest { + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), + name: name.to_string(), + spec: Some(SandboxSpec { + policy: Some(policy), + ..Default::default() + }), + ..Default::default() + }) + } - let sandbox = resolve_and_authorize_sandbox_name( - state, - &principal, - &req.sandbox, - crate::auth::workspace_authz::selected_workspace_name(req.workspace_scope.as_ref())?, - MinWorkspaceRole::User, - ) - .await?; + /// Stores a stopped sandbox whose spec holds a Cedar policy, as a + /// Cedar-enabled gateway with a supervisor-enforced driver created it. + #[cfg(not(feature = "experimental"))] + async fn put_stopped_cedar_sandbox(state: &ServerState, name: &str) { + let mut sandbox = test_sandbox(name, Vec::new()); + sandbox.spec.as_mut().unwrap().policy = Some(crate::grpc::test_support::cedar_policy()); + sandbox.set_phase(SandboxPhase::Stopped as i32); + state.store.put_message(&sandbox).await.unwrap(); + } - if let Some(completion) = &completion { - completion.ensure_target(sandbox.object_id())?; + #[cfg(not(feature = "experimental"))] + fn start_request(name: &str) -> Request { + authed_request(StartSandboxRequest { + name: name.to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), + ..Default::default() + }) } - require_ready_sandbox(&sandbox)?; + #[cfg(not(feature = "experimental"))] + #[tokio::test] + async fn create_rejects_cedar_without_cedar_support() { + let (state, driver) = test_server_state_with_fake_driver().await; + let error = handle_create_sandbox( + &state, + create_request_with_policy("cedar", crate::grpc::test_support::cedar_policy()), + ) + .await + .expect_err("Cedar is unsupported"); + assert_eq!(error.code(), tonic::Code::FailedPrecondition, "{error:?}"); + assert!(error.message().contains("without Cedar"), "{error:?}"); + assert!(driver.calls().is_empty(), "{:?}", driver.calls()); + } - // Open a relay channel through the supervisor session. Use a 15s - // session-wait timeout, enough to cover a transient supervisor reconnect - // while still failing quickly during normal operation. - let (channel_id, relay_rx) = crate::supervisor_session::open_routed_relay_with_target( - state, - sandbox.object_id(), - relay_open::Target::Ssh(SshRelayTarget {}), - String::new(), - std::time::Duration::from_secs(15), - ) - .await - .map_err(|e| Status::unavailable(format!("supervisor relay failed: {e}")))?; - super::mutation_audit::record_exec_relay(&state.config.audit, &sandbox, &channel_id, &req); + #[cfg(not(feature = "experimental"))] + #[tokio::test] + async fn start_rejects_a_stored_cedar_sandbox_without_cedar_support() { + let (state, driver) = test_server_state_with_fake_driver().await; + put_stopped_cedar_sandbox(&state, "stored-cedar").await; - let command_str = build_remote_exec_command(&req) - .map_err(|e| Status::invalid_argument(format!("command construction failed: {e}")))?; - let stdin_payload = req.stdin; - let execution_timeout = req - .execution_timeout - .as_ref() - .map(openshell_core::time::duration_to_std) - .transpose() - .map_err(|error| Status::invalid_argument(error.to_string()))?; - let request_tty = req.tty; - let (cols, rows) = pty_dimensions(req.cols, req.rows); + let error = handle_start_sandbox(&state, start_request("stored-cedar")) + .await + .expect_err("Cedar is unsupported"); + assert_eq!(error.code(), tonic::Code::FailedPrecondition, "{error:?}"); + assert!(error.message().contains("without Cedar"), "{error:?}"); + assert!(driver.calls().is_empty(), "{:?}", driver.calls()); + } - let sandbox_id = sandbox.object_id().to_string(); + /// Resuming starts the workload again, so it applies the start checks. + #[cfg(not(feature = "experimental"))] + #[tokio::test] + async fn resume_rejects_a_stored_cedar_sandbox_without_cedar_support() { + let (state, driver) = test_server_state_with_fake_driver().await; + put_stopped_cedar_sandbox(&state, "stored-cedar").await; - let no_login_shell = req.no_login_shell; + let error = handle_resume_sandbox( + &state, + authed_request(ResumeSandboxRequest { + name: "stored-cedar".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), + ..Default::default() + }), + ) + .await + .expect_err("Cedar is unsupported"); + assert_eq!(error.code(), tonic::Code::FailedPrecondition, "{error:?}"); + assert!(error.message().contains("without Cedar"), "{error:?}"); + assert!(driver.calls().is_empty(), "{:?}", driver.calls()); + } - let (tx, rx) = mpsc::channel::>(256); - tokio::spawn(async move { - // Wait for the supervisor's reverse CONNECT to deliver the relay stream. - let Some(relay_stream) = - await_relay_stream(relay_rx, &tx, &sandbox_id, &channel_id, "ExecSandbox").await - else { - return; + #[tokio::test] + async fn missing_launch_signer_precedes_driver_validation_and_preserves_staged_archive() { + let directory = tempfile::tempdir().unwrap(); + let mut state = test_server_state().await; + let mut metadata = openshell_core::extension_protocol::extension_metadata( + openshell_core::extension_protocol::ExtensionFamily::Compute, + "test/launch-authentication", + "test", + [], + ); + metadata + .required_capabilities + .push(openshell_core::extension_protocol::COMPUTE_LAUNCH_AUTHENTICATION.to_string()); + let admission = openshell_core::resource_admission::DriverAdmissionConfig { + allow_driver_config: true, + ..Default::default() }; - - if let Err(err) = stream_exec_over_relay( - tx.clone(), - &sandbox_id, - &channel_id, - relay_stream, - &command_str, - stdin_payload, - execution_timeout, - request_tty, - no_login_shell, - cols, - rows, - completion, + let driver = Arc::new( + crate::test_support::FakeComputeDriver::new().with_capabilities( + openshell_core::proto::compute::v1::GetCapabilitiesResponse { + driver_name: "test".to_string(), + default_image: "test/image:latest".to_string(), + rootfs_tar_staging_dir: directory.path().to_string_lossy().into_owned(), + rootfs_tar_max_bytes: 1024, + resource_admission_policy: admission.acknowledgement(), + extension: Some(metadata), + ..Default::default() + }, + ), + ); + let compute = crate::compute::ComputeRuntime::from_driver( + "test".to_string(), + driver.clone(), + None, + state.store.clone(), + crate::sandbox_index::SandboxIndex::new(), + crate::sandbox_watch::SandboxWatchBus::new(), + crate::tracing_bus::TracingLogBus::new(), + Arc::new(crate::supervisor_session::SupervisorSessionRegistry::new()), + ) + .await + .unwrap() + .with_admission_policy(admission) + .unwrap(); + Arc::get_mut(&mut state).unwrap().compute = compute; + let staging = state.compute.rootfs_tar_staging(); + let slot = staging + .begin("default", "dev-user", "rootfs.tar", 7) + .unwrap(); + std::fs::write(&slot.upload_path, b"archive").unwrap(); + let driver_config = Struct { + fields: std::iter::once(( + "test".to_string(), + Value { + kind: Some(Kind::StructValue(Struct { + fields: std::iter::once(( + crate::compute::rootfs_tar::STAGING_TOKEN_FIELD.to_string(), + Value { + kind: Some(Kind::StringValue(slot.token.clone())), + }, + )) + .collect(), + })), + }, + )) + .collect(), + }; + driver.clear_calls(); + let error = handle_create_sandbox( + &state, + authed_request(CreateSandboxRequest { + name: "missing-signer".to_string(), + spec: Some(SandboxSpec { + template: Some(SandboxTemplate { + driver_config: Some(driver_config), + ..Default::default() + }), + ..Default::default() + }), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), + ..Default::default() + }), ) .await - { - warn!(sandbox_id = %sandbox_id, error = %err, "ExecSandbox failed"); - let _ = tx.send(Err(err)).await; - } - }); + .unwrap_err(); + assert_eq!(error.code(), tonic::Code::FailedPrecondition); + assert!(error.message().contains("sandbox launch signing")); + assert!( + driver.calls().is_empty(), + "driver validation must not precede signing preflight" + ); + assert_eq!( + staging.peek(&slot.token).unwrap(), + std::path::PathBuf::from(&slot.upload_path) + ); + assert_eq!(std::fs::read(&slot.upload_path).unwrap(), b"archive"); + assert!( + state + .store + .get_message_by_name::("default", "missing-signer") + .await + .unwrap() + .is_none() + ); + } - Ok(Response::new(ReceiverStream::new(rx))) -} + // ---- shell_escape ---- -/// Wait for the supervisor's reverse CONNECT to deliver a relay stream. -/// -/// Returns `Some(stream)` on success. On any failure the error is sent on `tx` -/// and `None` is returned; the caller should then `return` immediately. -async fn await_relay_stream( - relay_rx: oneshot::Receiver>, - tx: &mpsc::Sender>, - sandbox_id: &str, - channel_id: &str, - context: &str, -) -> Option { - match tokio::time::timeout(std::time::Duration::from_secs(10), relay_rx).await { - Ok(Ok(Ok(stream))) => Some(stream), - Ok(Ok(Err(status))) => { - warn!(sandbox_id = %sandbox_id, channel_id = %channel_id, error = %status.message(), "{context}: relay target open failed"); - let _ = tx.send(Err(status)).await; - None - } - Ok(Err(_)) => { - warn!(sandbox_id = %sandbox_id, channel_id = %channel_id, "{context}: relay channel dropped"); - let _ = tx - .send(Err(Status::unavailable("relay channel dropped"))) - .await; - None + #[test] + fn pty_dimensions_default_zero_values_without_overwriting_explicit_values() { + assert_eq!(pty_dimensions(0, 0), (80, 24)); + assert_eq!(pty_dimensions(120, 40), (120, 40)); + assert_eq!(pty_dimensions(0, 40), (80, 40)); + } + + #[test] + fn watch_terminal_phases_include_command_results_and_errors() { + for phase in [ + SandboxPhase::Ready, + SandboxPhase::Completed, + SandboxPhase::Stopped, + SandboxPhase::Suspended, + SandboxPhase::Error, + ] { + assert!(is_watch_terminal(phase), "{phase:?} should stop the watch"); } - Err(_) => { - warn!(sandbox_id = %sandbox_id, channel_id = %channel_id, "{context}: relay open timed out"); - let _ = tx - .send(Err(Status::deadline_exceeded("relay open timed out"))) - .await; - None + for phase in [ + SandboxPhase::Provisioning, + SandboxPhase::Starting, + SandboxPhase::Stopping, + SandboxPhase::Suspending, + SandboxPhase::Deleting, + SandboxPhase::Unknown, + ] { + assert!( + !is_watch_terminal(phase), + "{phase:?} should keep the watch open" + ); } } -} - -pub(super) async fn handle_forward_tcp( - state: &Arc, - request: Request>, -) -> Result< - Response< - Pin> + Send + 'static>>, - >, - Status, -> { - let principal = super::extract_principal(&request)?; - let mut inbound = request.into_inner(); - let first = inbound - .message() - .await? - .ok_or_else(|| Status::invalid_argument("empty ForwardTcp stream"))?; - let Some(openshell_core::proto::tcp_forward_frame::Payload::Init(init)) = first.payload else { - return Err(Status::invalid_argument( - "first TcpForwardFrame must be init", - )); - }; - - super::mutation_audit::record_forward_targets(&init); - let target = validate_tcp_forward_init(&init)?; - let sandbox = resolve_and_authorize_sandbox_name( - state, - &principal, - &init.sandbox, - &init.workspace, - MinWorkspaceRole::User, - ) - .await?; + #[test] + fn sandbox_create_telemetry_uses_resolved_template_gpu_request() { + let request = CreateSandboxRequest { + request_id: String::new(), + spec: Some(SandboxSpec { + providers: vec!["github".to_string()], + policy: Some(openshell_core::proto::SandboxPolicy::default()), + ..SandboxSpec::default() + }), + workload_template: "gpu-kata".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), + ..CreateSandboxRequest::default() + }; + let created = Sandbox { + spec: Some(SandboxSpec { + providers: vec!["github".to_string()], + policy: Some(openshell_core::proto::SandboxPolicy::default()), + resource_requirements: Some(ResourceRequirements { + gpu: Some(GpuResourceRequirements { count: Some(1) }), + }), + ..SandboxSpec::default() + }), + created_from_workload_template: Some(SandboxWorkloadTemplateProvenance { + name: "gpu-kata".to_string(), + resource_version: "7".to_string(), + }), + ..Sandbox::default() + }; - // The main process may finish between minting the SSH token and opening - // its transport. Keep the relay reachable until terminal delivery is - // finalized so fast commands can attach without a readiness race. - if !sandbox_relay_reachable(state, &sandbox).await? { - return Err(Status::failed_precondition("sandbox is not ready")); + assert_eq!( + sandbox_create_telemetry_attrs(&request, Some(&created)), + SandboxCreateTelemetryAttrs { + requested_gpu: true, + provider_count: 1, + has_custom_policy: true, + template_source: SandboxTemplateSource::WorkloadTemplate, + } + ); } - let connection_guard = - acquire_forward_connection_guard(state, &principal, &init, &sandbox).await?; - let (channel_id, relay_rx) = crate::supervisor_session::open_routed_relay_with_target( - state, - sandbox.object_id(), - target.clone(), - init.service_id.clone(), - std::time::Duration::from_secs(15), - ) - .await - .map_err(|e| Status::unavailable(format!("supervisor relay failed: {e}")))?; - super::mutation_audit::record_forward_relay( - &sandbox, - &channel_id, - &target, - connection_guard.token.is_none(), - ); - - let (tx, rx) = mpsc::channel::>(256); - let sandbox_id = sandbox.object_id().to_string(); - tokio::spawn(async move { - let _connection_guard = connection_guard; - let Some(relay_stream) = - await_relay_stream(relay_rx, &tx, &sandbox_id, &channel_id, "ForwardTcp").await - else { - return; + #[test] + fn sandbox_create_telemetry_falls_back_to_request_for_unresolved_template() { + let request = CreateSandboxRequest { + request_id: String::new(), + spec: Some(SandboxSpec { + providers: vec!["github".to_string()], + ..SandboxSpec::default() + }), + workload_template: "missing-template".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), + ..CreateSandboxRequest::default() }; - bridge_forward_tcp_stream(inbound, relay_stream, tx, &sandbox_id, &channel_id).await; - }); - - let stream: Pin< - Box> + Send + 'static>, - > = Box::pin(ReceiverStream::new(rx)); - Ok(Response::new(stream)) -} - -/// The per-sandbox relay budget a forward stream draws from. SSH relays and -/// service forwards are counted apart so open forwards cannot starve SSH. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum RelayBudget { - Ssh, - Service, -} - -impl RelayBudget { - fn of(init: &TcpForwardInit) -> Self { - match init.target { - Some(tcp_forward_init::Target::Tcp(_)) => Self::Service, - _ => Self::Ssh, - } + assert_eq!( + sandbox_create_telemetry_attrs(&request, None), + SandboxCreateTelemetryAttrs { + requested_gpu: false, + provider_count: 1, + has_custom_policy: false, + template_source: SandboxTemplateSource::WorkloadTemplate, + } + ); } - fn counts(self, state: &ServerState) -> &std::sync::Mutex> { - match self { - Self::Ssh => &state.ssh_connections_by_sandbox, - Self::Service => &state.service_connections_by_sandbox, - } + #[test] + fn shell_escape_safe_chars_pass_through() { + assert_eq!(shell_escape("ls").unwrap(), "ls"); + assert_eq!(shell_escape("/usr/bin/python").unwrap(), "/usr/bin/python"); + assert_eq!(shell_escape("file.txt").unwrap(), "file.txt"); + assert_eq!(shell_escape("my-cmd_v2").unwrap(), "my-cmd_v2"); } - fn limit(self, config: &openshell_core::Config) -> u32 { - match self { - Self::Ssh => config.max_ssh_connections_per_sandbox, - Self::Service => config.max_service_connections_per_sandbox, - } + #[test] + fn shell_escape_empty_string() { + assert_eq!(shell_escape("").unwrap(), "''"); } - const fn exhausted_message(self) -> &'static str { - match self { - Self::Ssh => "sandbox SSH connection limit reached", - Self::Service => "sandbox service forward connection limit reached", - } + #[test] + fn shell_escape_wraps_unsafe_chars() { + assert_eq!(shell_escape("hello world").unwrap(), "'hello world'"); + assert_eq!(shell_escape("$(id)").unwrap(), "'$(id)'"); + assert_eq!(shell_escape("; rm -rf /").unwrap(), "'; rm -rf /'"); } -} -struct ForwardConnectionGuard { - state: Arc, - token: Option, - budget: RelayBudget, - sandbox_id: String, -} + #[test] + fn shell_escape_handles_single_quotes() { + assert_eq!(shell_escape("it's").unwrap(), "'it'\"'\"'s'"); + } -impl Drop for ForwardConnectionGuard { - fn drop(&mut self) { - if let Some(token) = self.token.as_deref() { - decrement_ssh_connection_count(&self.state.ssh_connections_by_token, token); - } - decrement_ssh_connection_count(self.budget.counts(&self.state), &self.sandbox_id); + #[test] + fn shell_escape_rejects_null_bytes() { + assert!(shell_escape("hello\x00world").is_err()); } -} -/// Reserve a relay slot after authorizing the sandbox's workspace. Each SSH -/// transport draws from the same SSH budget. Clients using a session token -/// also draw from its per-token budget, including older TCP forward clients. -async fn acquire_forward_connection_guard( - state: &Arc, - principal: &crate::auth::principal::Principal, - init: &TcpForwardInit, - sandbox: &Sandbox, -) -> Result { - let sandbox_id = sandbox.object_id().to_string(); - let budget = RelayBudget::of(init); - let token = init.authorization_token.trim(); - if let Some(tcp_forward_init::Target::DirectSshSandboxId(expected)) = &init.target { - if !direct_ssh_available(state, principal) { - return Err(crate::auth::audit::deny( - principal, - crate::auth::audit::AuthzDenial::MethodNotPermitted, - "direct SSH admission is unavailable for this request", - )); - } - if *expected != sandbox_id { - return Err(Status::failed_precondition( - "sandbox was replaced before opening the SSH relay", - )); - } - } else if budget == RelayBudget::Ssh && token.is_empty() { - return Err(crate::auth::audit::reject_credential( - Some(principal), - AuthRejection::new( - AuthMechanism::SshSessionToken, - AuthFailureReason::MissingCredential, - Status::unauthenticated("authorization_token is required for SSH targets"), - ), - )); + #[test] + fn shell_escape_allows_newlines() { + assert!(shell_escape("line1\nline2").is_ok()); + assert!(shell_escape("line1\rline2").is_ok()); + assert!(shell_escape("line1\r\nline2").is_ok()); } - let token = if token.is_empty() { - acquire_sandbox_connection_slot(state, budget, &sandbox_id)?; - None - } else { - let session = validate_ssh_forward_token(state, token, &sandbox_id) - .await - .map_err(|rejection| { - crate::auth::audit::reject_credential(Some(principal), rejection) - })?; - super::mutation_audit::record_ssh_session(session.object_name()); - crate::auth::audit::emit_ssh_session_logon(&state.logons, principal, token); - acquire_ssh_connection_slots(state, budget, token, &sandbox_id)?; - Some(token.to_string()) - }; - Ok(ForwardConnectionGuard { - state: state.clone(), - token, - budget, - sandbox_id, - }) -} + #[test] + fn shell_escape_preserves_newlines_in_single_quotes() { + assert_eq!(shell_escape("line1\nline2").unwrap(), "'line1\nline2'"); + assert_eq!( + shell_escape("def f():\n return 1").unwrap(), + "'def f():\n return 1'" + ); + assert_eq!(shell_escape("line1\r\nline2").unwrap(), "'line1\r\nline2'"); + } -#[allow(clippy::result_large_err)] -async fn validate_ssh_forward_token( - state: &Arc, - token: &str, - sandbox_id: &str, -) -> Result { - let reject = - |reason, status| AuthRejection::new(AuthMechanism::SshSessionToken, reason, status); - let session = state - .store - .get_message::(token) - .await - .map_err(|e| { - reject( - AuthFailureReason::IdentityProviderUnavailable, - Status::internal(format!("fetch SSH session failed: {e}")), - ) - })? - .ok_or_else(|| { - reject( - AuthFailureReason::InvalidCredential, - Status::unauthenticated("SSH session token not found"), - ) - })?; + // ---- build_remote_exec_command ---- - if session.revoked || session.sandbox_id != sandbox_id { - // A token minted for another sandbox was issued for a different party. - let reason = if session.revoked { - AuthFailureReason::InvalidCredential - } else { - AuthFailureReason::AudienceOrIssuerMismatch + #[test] + fn build_remote_exec_command_basic() { + use openshell_core::proto::ExecSandboxRequest; + let req = ExecSandboxRequest { + sandbox: "test".to_string(), + workspace_scope: None, + command: vec!["ls".to_string(), "-la".to_string()], + ..Default::default() }; - return Err(reject( - reason, - Status::unauthenticated("SSH session token is not valid"), - )); + assert_eq!(build_remote_exec_command(&req).unwrap(), "ls -la"); } - if let Some(expiration_time) = session.expiration_time.as_ref() { - let now_ms = current_time_ms(); - let expires_at_ms = - openshell_core::time::timestamp_to_millis(expiration_time).map_err(|error| { - reject( - AuthFailureReason::IdentityProviderUnavailable, - Status::internal(error.to_string()), - ) - })?; - if now_ms > expires_at_ms { - return Err(reject( - AuthFailureReason::ExpiredCredential, - Status::unauthenticated("SSH session token expired"), - )); - } + #[test] + fn build_remote_exec_command_with_env_and_workdir() { + use openshell_core::proto::ExecSandboxRequest; + let req = ExecSandboxRequest { + sandbox: "test".to_string(), + workspace_scope: None, + command: vec![ + "python".to_string(), + "-c".to_string(), + "print('ok')".to_string(), + ], + environment: std::iter::once(("HOME".to_string(), "/home/user".to_string())).collect(), + workdir: "/workspace".to_string(), + ..Default::default() + }; + let cmd = build_remote_exec_command(&req).unwrap(); + assert!(cmd.starts_with("cd /workspace && ")); + assert!(cmd.contains("HOME=/home/user")); + assert!(cmd.contains("'print('\"'\"'ok'\"'\"')'")); } - Ok(session) -} - -const MAX_CONNECTIONS_PER_TOKEN: u32 = 3; + #[test] + fn build_remote_exec_command_rejects_null_bytes_in_args() { + use openshell_core::proto::ExecSandboxRequest; + let req = ExecSandboxRequest { + sandbox: "test".to_string(), + workspace_scope: None, + command: vec!["echo".to_string(), "hello\x00world".to_string()], + ..Default::default() + }; + assert!(build_remote_exec_command(&req).is_err()); + } -fn acquire_ssh_connection_slots( - state: &ServerState, - budget: RelayBudget, - token: &str, - sandbox_id: &str, -) -> Result<(), Status> { - { - let mut counts = state.ssh_connections_by_token.lock().unwrap(); - let count = counts.entry(token.to_string()).or_insert(0); - if *count >= MAX_CONNECTIONS_PER_TOKEN { - return Err(Status::resource_exhausted( - "SSH session connection limit reached", - )); - } - *count += 1; + #[test] + fn build_remote_exec_command_rejects_newlines_in_workdir() { + use openshell_core::proto::ExecSandboxRequest; + let req = ExecSandboxRequest { + sandbox: "test".to_string(), + workspace_scope: None, + command: vec!["ls".to_string()], + workdir: "/tmp\nmalicious".to_string(), + ..Default::default() + }; + // Validation layer rejects newlines in workdir + assert!(validate_exec_request_fields(&req).is_err()); } - if let Err(status) = acquire_sandbox_connection_slot(state, budget, sandbox_id) { - decrement_ssh_connection_count(&state.ssh_connections_by_token, token); - return Err(status); + #[test] + fn build_remote_exec_command_accepts_multiline_script() { + use openshell_core::proto::ExecSandboxRequest; + let req = ExecSandboxRequest { + sandbox: "test".to_string(), + workspace_scope: None, + command: vec![ + "python3".to_string(), + "-c".to_string(), + "def f():\n return 1\nprint(f())".to_string(), + ], + ..Default::default() + }; + let cmd = build_remote_exec_command(&req).unwrap(); + assert!(cmd.starts_with("python3 -c ")); + assert!(cmd.contains("'def f():\n return 1\nprint(f())'")); } - Ok(()) -} - -/// Reserve one of the sandbox's relay slots in the given budget. -fn acquire_sandbox_connection_slot( - state: &ServerState, - budget: RelayBudget, - sandbox_id: &str, -) -> Result<(), Status> { - let mut counts = budget.counts(state).lock().unwrap(); - let count = counts.entry(sandbox_id.to_string()).or_insert(0); - if *count >= budget.limit(&state.config) { - return Err(Status::resource_exhausted(budget.exhausted_message())); + #[test] + fn build_remote_exec_command_multiline_with_single_quotes() { + use openshell_core::proto::ExecSandboxRequest; + let req = ExecSandboxRequest { + sandbox: "test".to_string(), + workspace_scope: None, + command: vec![ + "python3".to_string(), + "-c".to_string(), + "print('one')\r\nprint('two')".to_string(), + ], + ..Default::default() + }; + let cmd = build_remote_exec_command(&req).unwrap(); + assert!(cmd.starts_with("python3 -c ")); + assert!( + cmd.contains("'print('\"'\"'one'\"'\"')\r\nprint('\"'\"'two'\"'\"')'"), + "CR/LF with embedded single quotes must compose correctly: {cmd}" + ); } - *count += 1; - Ok(()) -} -fn decrement_ssh_connection_count(counts: &std::sync::Mutex>, key: &str) { - let mut counts = counts.lock().unwrap(); - if let Some(count) = counts.get_mut(key) { - *count = count.saturating_sub(1); - if *count == 0 { - counts.remove(key); + fn forward_init(target: tcp_forward_init::Target, token: &str) -> TcpForwardInit { + TcpForwardInit { + sandbox: "sbx".to_string(), + workspace: String::new(), + service_id: String::new(), + target: Some(target), + authorization_token: token.to_string(), } } -} -fn validate_tcp_forward_init(init: &TcpForwardInit) -> Result { - if let Some(target) = init.target.as_ref() { - return match target { - tcp_forward_init::Target::Ssh(_) => { - Ok(relay_open::Target::Ssh(SshRelayTarget::default())) - } - tcp_forward_init::Target::DirectSshSandboxId(id) => { - if validate_ssh_sandbox_id(id).is_err() || !init.authorization_token.is_empty() { - return Err(Status::invalid_argument( - "direct SSH requires a valid sandbox ID and an empty authorization_token", - )); - } - Ok(relay_open::Target::Ssh(SshRelayTarget::default())) - } - tcp_forward_init::Target::Tcp(target) => Ok(relay_open::Target::Tcp( - validate_tcp_forward_target(target)?, - )), - }; + fn loopback_tcp_target() -> tcp_forward_init::Target { + tcp_forward_init::Target::Tcp(TcpRelayTarget { + host: "127.0.0.1".to_string(), + port: 8080, + }) } - Err(Status::invalid_argument("tcp forward target is required")) -} - -fn validate_tcp_forward_target(target: &TcpRelayTarget) -> Result { - if target.port == 0 || target.port > u32::from(u16::MAX) { - return Err(Status::invalid_argument( - "tcp target port must be between 1 and 65535", + #[tokio::test] + async fn direct_ssh_requires_a_verified_user_with_ssh_scope() { + use crate::auth::principal::Principal; + let mut state = test_server_state().await; + Arc::get_mut(&mut state).unwrap().config.oidc = Some(serde_json::from_value( + serde_json::json!({ "issuer": "https://issuer.example", "audience": "test", "scopes_claim": "scope" }) + ).unwrap()); + let Principal::User(mut user) = forward_caller() else { + panic!("expected user") + }; + user.identity.scopes = vec!["sandbox:read".into()]; + assert!(!direct_ssh_available( + &state, + &Principal::User(user.clone()) + )); + user.identity.scopes.push("sandbox:write".into()); + for provider in [ + IdentityProvider::Oidc, + IdentityProvider::Mtls, + IdentityProvider::LocalDev, + ] { + user.identity.provider = provider; + assert_eq!( + direct_ssh_available(&state, &Principal::User(user.clone())), + provider != IdentityProvider::LocalDev + ); + } + assert!(!direct_ssh_available(&state, &Principal::Anonymous)); + assert!(!direct_ssh_available( + &state, + &crate::auth::principal::test_support::sandbox("sandbox-fwd") )); } - validate_tcp_target_parts(target.host.trim(), target.port).map(|host| TcpRelayTarget { - host, - port: target.port, - }) -} - -fn validate_tcp_target_parts(host: &str, _port: u32) -> Result { - if host.is_empty() { - return Err(Status::invalid_argument("tcp target host is required")); - } - if host.eq_ignore_ascii_case("localhost") { - return Ok("127.0.0.1".to_string()); + #[test] + fn direct_ssh_rejects_missing_identity_and_any_session_token() { + for (id, token) in [ + ("", ""), + (" ", ""), + (" sandbox-fwd", ""), + ("sandbox-fwd", " "), + ("sandbox-fwd", "legacy-token"), + ] { + let init = forward_init( + tcp_forward_init::Target::DirectSshSandboxId(id.into()), + token, + ); + assert_eq!( + validate_tcp_forward_init(&init).unwrap_err().code(), + tonic::Code::InvalidArgument + ); + } } - let ip: IpAddr = host - .parse() - .map_err(|_| Status::invalid_argument("tcp target host must be loopback"))?; - if ip.is_loopback() { - Ok(ip.to_string()) - } else { - Err(Status::invalid_argument("tcp target host must be loopback")) + fn sandbox_connection_count(state: &ServerState, budget: RelayBudget, sandbox_id: &str) -> u32 { + budget + .counts(state) + .lock() + .unwrap() + .get(sandbox_id) + .copied() + .unwrap_or(0) } -} -async fn bridge_forward_tcp_stream( - mut inbound: tonic::Streaming, - relay_stream: S, - tx: mpsc::Sender>, - sandbox_id: &str, - channel_id: &str, -) where - S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Send + 'static, -{ - let (mut relay_read, mut relay_write) = tokio::io::split(relay_stream); + #[tokio::test] + async fn tcp_forward_without_token_is_admitted_on_the_principal_alone() { + let state = test_server_state().await; + let sandbox = test_sandbox("fwd", Vec::new()); - let sandbox_id_in = sandbox_id.to_string(); - let channel_id_in = channel_id.to_string(); - tokio::spawn(async move { - loop { - match inbound.message().await { - Ok(Some(frame)) => { - let Some(openshell_core::proto::tcp_forward_frame::Payload::Data(data)) = - frame.payload - else { - warn!(sandbox_id = %sandbox_id_in, channel_id = %channel_id_in, "ForwardTcp: received non-data frame after init"); - break; - }; - if data.is_empty() { - continue; - } - if let Err(err) = - tokio::io::AsyncWriteExt::write_all(&mut relay_write, &data).await - { - warn!(sandbox_id = %sandbox_id_in, channel_id = %channel_id_in, error = %err, "ForwardTcp: write to relay failed"); - break; - } - } - Ok(None) => break, - Err(err) => { - debug!(sandbox_id = %sandbox_id_in, channel_id = %channel_id_in, error = %err, "ForwardTcp: inbound stream ended"); - break; - } - } - } - let _ = tokio::io::AsyncWriteExt::shutdown(&mut relay_write).await; - }); + let guard = acquire_forward_connection_guard( + &state, + &forward_caller(), + &forward_init(loopback_tcp_target(), ""), + &sandbox, + ) + .await + .expect("tcp forward without a session token"); - let mut buf = vec![0u8; TCP_FORWARD_CHUNK_SIZE]; - loop { - match tokio::io::AsyncReadExt::read(&mut relay_read, &mut buf).await { - Ok(0) => break, - Ok(n) => { - let frame = TcpForwardFrame { - payload: Some(openshell_core::proto::tcp_forward_frame::Payload::Data( - buf[..n].to_vec(), - )), - }; - if tx.send(Ok(frame)).await.is_err() { - break; - } - } - Err(err) => { - warn!(sandbox_id = %sandbox_id, channel_id = %channel_id, error = %err, "ForwardTcp: read from relay failed"); - let _ = tx - .send(Err(Status::unavailable(format!( - "relay read failed: {err}" - )))) - .await; - break; - } - } + assert!( + guard.token.is_none(), + "no per-token accounting without a token" + ); + assert!(state.ssh_connections_by_token.lock().unwrap().is_empty()); + assert_eq!( + sandbox_connection_count(&state, RelayBudget::Service, sandbox.object_id()), + 1 + ); + drop(guard); + assert_eq!( + sandbox_connection_count(&state, RelayBudget::Service, sandbox.object_id()), + 0, + "dropping the guard releases the sandbox slot" + ); } -} -// --------------------------------------------------------------------------- -// Interactive exec handler (bidirectional stdin streaming) -// --------------------------------------------------------------------------- + const FORWARD_TCP_PATH: &str = "/openshell.v1.OpenShell/ForwardTcp"; + + fn forward_caller() -> crate::auth::principal::Principal { + authed_request(()) + .extensions_mut() + .remove::() + .expect("dev principal") + } -pub(super) fn validate_exec_start(req: &ExecSandboxRequest) -> Result<(), Status> { - use openshell_core::rpc_error; - if req.sandbox.is_empty() { - return Err(rpc_error::invalid_argument( - "sandbox", - "sandbox is required", - )); + /// Acquire a forward slot inside a routed `ForwardTcp` request, returning + /// the result and the OCSF events it emitted. + async fn acquire_audited( + state: &Arc, + init: &TcpForwardInit, + sandbox: &Sandbox, + ) -> ( + Result, + Vec, + ) { + audited( + FORWARD_TCP_PATH, + acquire_forward_connection_guard(state, &forward_caller(), init, sandbox), + ) + .await } - if req.command.is_empty() { - return Err(rpc_error::invalid_argument( - "command", - "command is required", - )); + + async fn store_ssh_session( + state: &ServerState, + token: &str, + sandbox_id: &str, + revoked: bool, + expires_at_ms: i64, + ) { + let session = SshSession { + metadata: Some(ObjectMeta { + id: token.to_string(), + name: format!("session-{token}"), + created_time: None, + labels: HashMap::new(), + resource_version: 0, + annotations: HashMap::new(), + workspace: "default".to_string(), + deletion_time: None, + }), + sandbox_id: sandbox_id.to_string(), + token: token.to_string(), + revoked, + expiration_time: openshell_core::time::optional_timestamp_from_legacy_millis( + expires_at_ms, + ) + .unwrap(), + }; + state.store.put_message(&session).await.unwrap(); } - if req.environment.keys().any(|key| !is_valid_env_key(key)) { - return Err(rpc_error::invalid_argument( - "environment", - "environment keys must match ^[A-Za-z_][A-Za-z0-9_]*$", - )); + + /// Assert `events` is one SSH session token failure for `reason` that + /// never mentions `token`. + fn assert_ssh_token_failure(events: &[serde_json::Value], reason: &str, token: &str) { + assert_eq!(events.len(), 1, "{events:?}"); + let event = &events[0]; + assert_authentication_failure(event, FORWARD_TCP_PATH, reason); + assert_eq!(event["auth_protocol"], "ssh_session_token"); + assert_eq!(event["user"]["uid"], "dev-user"); + assert_origin(event); + if !token.is_empty() { + assert_redacted(event, token); + } } - validate_exec_request_fields(req) -} -fn validate_interactive_exec_start( - msg: Option, -) -> Result { - use openshell_core::proto::exec_sandbox_input::Payload; + #[tokio::test] + async fn ssh_forward_without_token_is_rejected() { + let state = test_server_state().await; + let sandbox = test_sandbox("fwd", Vec::new()); - let msg = - msg.ok_or_else(|| Status::invalid_argument("empty stream: expected start message"))?; + let (result, events) = acquire_audited( + &state, + &forward_init(tcp_forward_init::Target::Ssh(SshRelayTarget::default()), ""), + &sandbox, + ) + .await; + let err = result + .err() + .expect("ssh targets keep requiring the session token"); - let Some(Payload::Start(req)) = msg.payload else { - return Err(Status::invalid_argument( - "first message must be a start payload", - )); - }; + assert_eq!(err.code(), tonic::Code::Unauthenticated); + assert_eq!( + err.message(), + "authorization_token is required for SSH targets" + ); + assert_eq!( + sandbox_connection_count(&state, RelayBudget::Ssh, sandbox.object_id()), + 0 + ); + assert_ssh_token_failure(&events, "missing_credential", ""); + } - validate_exec_start(&req)?; + #[tokio::test] + async fn tcp_forward_with_unknown_token_is_still_rejected() { + let state = test_server_state().await; + let sandbox = test_sandbox("fwd", Vec::new()); - Ok(req) -} + let (result, events) = acquire_audited( + &state, + &forward_init(loopback_tcp_target(), "canary-ssh-token-unknown"), + &sandbox, + ) + .await; + let err = result.err().expect("a supplied token is always validated"); -pub(super) async fn handle_exec_sandbox_interactive( - state: &Arc, - request: Request>, -) -> Result>>, Status> { - let (metadata, extensions, mut input_stream) = request.into_parts(); + assert_eq!(err.code(), tonic::Code::Unauthenticated); + assert_eq!(err.message(), "SSH session token not found"); + assert_eq!( + sandbox_connection_count(&state, RelayBudget::Service, sandbox.object_id()), + 0 + ); + assert_ssh_token_failure(&events, "invalid_credential", "canary-ssh-token-unknown"); + } - let first_msg = input_stream - .message() - .await - .map_err(|e| Status::internal(format!("failed to read first message: {e}")))?; + #[tokio::test] + async fn rejected_ssh_session_tokens_name_their_reason() { + let state = test_server_state().await; + let sandbox = test_sandbox("fwd", Vec::new()); + let future_ms = current_time_ms() + 60_000; + store_ssh_session( + &state, + "canary-ssh-token-revoked", + "sandbox-fwd", + true, + future_ms, + ) + .await; + store_ssh_session( + &state, + "canary-ssh-token-other", + "sandbox-other", + false, + future_ms, + ) + .await; + store_ssh_session( + &state, + "canary-ssh-token-expired", + "sandbox-fwd", + false, + 1_000, + ) + .await; - let req = validate_interactive_exec_start(first_msg)?; - super::mutation_audit::record_exec_targets(&req); + for (token, message, reason) in [ + ( + "canary-ssh-token-revoked", + "SSH session token is not valid", + "invalid_credential", + ), + ( + "canary-ssh-token-other", + "SSH session token is not valid", + "audience_or_issuer_mismatch", + ), + ( + "canary-ssh-token-expired", + "SSH session token expired", + "expired_credential", + ), + ] { + let (result, events) = acquire_audited( + &state, + &forward_init( + tcp_forward_init::Target::Ssh(SshRelayTarget::default()), + token, + ), + &sandbox, + ) + .await; + let err = result.err().expect(token); - let mut request = Request::from_parts( - metadata, - extensions, - ExecSandboxInput { - payload: Some(openshell_core::proto::exec_sandbox_input::Payload::Start( - req, - )), - }, - ); - request - .extensions_mut() - .insert(super::mutation_replay::streaming::InteractiveInput( - Arc::new(tokio::sync::Mutex::new(Some(input_stream))), - )); - super::mutation_replay::run(state, request).await -} + assert_eq!(err.code(), tonic::Code::Unauthenticated, "{token}"); + assert_eq!(err.message(), message, "{token}"); + assert_ssh_token_failure(&events, reason, token); + } + } -pub(super) async fn handle_exec_sandbox_interactive_start( - state: &Arc, - request: Request, -) -> Result>>, Status> { - let principal = super::extract_principal(&request)?; - let completion = request - .extensions() - .get::() - .cloned(); - let input = request - .extensions() - .get::() - .ok_or_else(|| Status::internal("interactive input handoff missing"))? - .clone(); - let input_stream = input - .0 - .lock() - .await - .take() - .ok_or_else(|| Status::internal("interactive input already claimed"))?; - let req = super::mutation_replay::streaming::start(request.get_ref())?; - validate_exec_start(req)?; + #[tokio::test] + async fn session_token_on_a_tcp_target_logs_on() { + let state = test_server_state().await; + let sandbox = test_sandbox("fwd", Vec::new()); + store_ssh_session(&state, "canary-ssh-token-tcp", "sandbox-fwd", false, 0).await; - let sandbox = resolve_and_authorize_sandbox_name( - state, - &principal, - &req.sandbox, - crate::auth::workspace_authz::selected_workspace_name(req.workspace_scope.as_ref())?, - MinWorkspaceRole::User, - ) - .await?; + let (result, events) = acquire_audited( + &state, + &forward_init(loopback_tcp_target(), "canary-ssh-token-tcp"), + &sandbox, + ) + .await; + result.expect("older clients still send a session token"); - if let Some(completion) = &completion { - completion.ensure_target(sandbox.object_id())?; + assert_eq!(events.len(), 1, "{events:?}"); + assert_logon(&events[0], FORWARD_TCP_PATH); + assert_eq!(events[0]["auth_protocol"], "ssh_session_token"); + assert_redacted(&events[0], "canary-ssh-token"); } - require_ready_sandbox(&sandbox)?; + #[tokio::test] + async fn ssh_session_token_logs_on_once() { + let state = test_server_state().await; + let sandbox = test_sandbox("fwd", Vec::new()); + store_ssh_session(&state, "canary-ssh-token-valid", "sandbox-fwd", false, 0).await; + let init = forward_init( + tcp_forward_init::Target::Ssh(SshRelayTarget::default()), + "canary-ssh-token-valid", + ); - let (channel_id, relay_rx) = crate::supervisor_session::open_routed_relay_with_target( - state, - sandbox.object_id(), - relay_open::Target::Ssh(SshRelayTarget {}), - String::new(), - std::time::Duration::from_secs(15), - ) - .await - .map_err(|e| Status::unavailable(format!("supervisor relay failed: {e}")))?; - super::mutation_audit::record_exec_relay(&state.config.audit, &sandbox, &channel_id, req); + let (first, events) = acquire_audited(&state, &init, &sandbox).await; + let (second, repeated) = acquire_audited(&state, &init, &sandbox).await; + first.expect("valid session token"); + second.expect("valid session token"); - let command_str = build_remote_exec_command(req) - .map_err(|e| Status::invalid_argument(format!("command construction failed: {e}")))?; - let request_tty = req.tty; - let no_login_shell = req.no_login_shell; - let execution_timeout = req - .execution_timeout - .as_ref() - .map(openshell_core::time::duration_to_std) - .transpose() - .map_err(|error| Status::invalid_argument(error.to_string()))?; - let (cols, rows) = pty_dimensions(req.cols, req.rows); + assert!(repeated.is_empty(), "{repeated:?}"); + assert_eq!(events.len(), 1, "{events:?}"); + let event = &events[0]; + assert_logon(event, FORWARD_TCP_PATH); + assert_eq!(event["auth_protocol"], "ssh_session_token"); + assert_eq!(event["user"]["uid"], "dev-user"); + assert_origin(event); + assert_redacted(event, "canary-ssh-token"); + } - let sandbox_id = sandbox.object_id().to_string(); + #[tokio::test] + async fn tcp_forwards_are_capped_per_sandbox() { + let state = test_server_state().await; + let sandbox = test_sandbox("fwd", Vec::new()); + let init = forward_init(loopback_tcp_target(), ""); + let cap = openshell_core::config::DEFAULT_MAX_CONNECTIONS_PER_SANDBOX; - let (tx, rx) = mpsc::channel::>(256); - tokio::spawn(async move { - let Some(relay_stream) = await_relay_stream( - relay_rx, - &tx, - &sandbox_id, - &channel_id, - "ExecSandboxInteractive", - ) - .await - else { - return; - }; + let mut guards = Vec::new(); + for _ in 0..cap { + guards.push( + acquire_forward_connection_guard(&state, &forward_caller(), &init, &sandbox) + .await + .expect("within the per-sandbox cap"), + ); + } + let err = acquire_forward_connection_guard(&state, &forward_caller(), &init, &sandbox) + .await + .err() + .expect("cap reached"); + assert_eq!(err.code(), tonic::Code::ResourceExhausted); + assert_eq!( + err.message(), + "sandbox service forward connection limit reached" + ); + assert_eq!( + sandbox_connection_count(&state, RelayBudget::Service, sandbox.object_id()), + cap + ); - if let Err(err) = stream_interactive_exec_over_relay( - tx.clone(), - &sandbox_id, - &channel_id, - relay_stream, - &command_str, - input_stream, - request_tty, - no_login_shell, - execution_timeout, - cols, - rows, - completion, - ) - .await + guards.pop(); + let guard = acquire_forward_connection_guard(&state, &forward_caller(), &init, &sandbox) + .await + .expect("slot freed by a closed connection"); + drop(guard); + drop(guards); + assert_eq!( + sandbox_connection_count(&state, RelayBudget::Service, sandbox.object_id()), + 0 + ); + } + + #[tokio::test] + async fn ssh_and_service_budgets_are_independent() { + let mut state = test_server_state().await; { - warn!(sandbox_id = %sandbox_id, error = %err, "ExecSandboxInteractive failed"); - let _ = tx.send(Err(err)).await; + let config = &mut Arc::get_mut(&mut state).expect("sole state owner").config; + config.max_ssh_connections_per_sandbox = 1; + config.max_service_connections_per_sandbox = 2; } - }); + let sandbox = test_sandbox("fwd", Vec::new()); + store_ssh_session(&state, "canary-ssh-token-a", "sandbox-fwd", false, 0).await; + store_ssh_session(&state, "canary-ssh-token-b", "sandbox-fwd", false, 0).await; + let tcp = forward_init(loopback_tcp_target(), ""); + let ssh = |token: &str| { + forward_init( + tcp_forward_init::Target::Ssh(SshRelayTarget::default()), + token, + ) + }; + let acquire = |init: TcpForwardInit| { + let state = state.clone(); + let sandbox = sandbox.clone(); + async move { + acquire_forward_connection_guard(&state, &forward_caller(), &init, &sandbox).await + } + }; - Ok(Response::new(ReceiverStream::new(rx))) -} + let _forwards = [ + acquire(tcp.clone()).await.expect("first forward"), + acquire(tcp.clone()).await.expect("second forward"), + ]; + let err = acquire(tcp).await.err().expect("forward budget spent"); + assert_eq!( + err.message(), + "sandbox service forward connection limit reached" + ); + + let ssh_guard = acquire(ssh("canary-ssh-token-a")) + .await + .expect("open forwards leave the SSH budget alone"); + let err = acquire(ssh("canary-ssh-token-b")) + .await + .err() + .expect("SSH budget spent"); + assert_eq!(err.code(), tonic::Code::ResourceExhausted); + assert_eq!(err.message(), "sandbox SSH connection limit reached"); + let direct = forward_init( + tcp_forward_init::Target::DirectSshSandboxId(sandbox.object_id().into()), + "", + ); + assert_eq!( + acquire(direct.clone()).await.err().unwrap().code(), + tonic::Code::ResourceExhausted + ); + drop(ssh_guard); + let direct_guard = acquire(direct).await.unwrap(); + assert!(direct_guard.token.is_none()); + assert_eq!( + acquire(ssh("canary-ssh-token-a")) + .await + .err() + .unwrap() + .code(), + tonic::Code::ResourceExhausted + ); + assert_eq!( + sandbox_connection_count(&state, RelayBudget::Ssh, sandbox.object_id()), + 1 + ); + assert_eq!( + sandbox_connection_count(&state, RelayBudget::Service, sandbox.object_id()), + 2 + ); + drop(direct_guard); + assert!(acquire(ssh("canary-ssh-token-a")).await.is_ok()); + } + + #[test] + fn tcp_forward_init_allows_loopback_targets() { + for host in ["127.0.0.1", "::1", "localhost"] { + let init = TcpForwardInit { + sandbox: "sbx".to_string(), + workspace: String::new(), + service_id: String::new(), + target: Some(tcp_forward_init::Target::Tcp(TcpRelayTarget { + host: host.to_string(), + port: 8080, + })), + authorization_token: String::new(), + }; + validate_tcp_forward_init(&init).expect("loopback target should pass"); + } + } + + #[test] + fn tcp_forward_init_allows_ssh_target() { + let init = TcpForwardInit { + sandbox: "sbx".to_string(), + workspace: String::new(), + target: Some(tcp_forward_init::Target::Ssh(SshRelayTarget::default())), + ..Default::default() + }; + match validate_tcp_forward_init(&init).expect("ssh target should pass") { + relay_open::Target::Ssh(_) => {} + other @ relay_open::Target::Tcp(_) => panic!("expected SSH target, got {other:?}"), + } + } + + #[test] + fn tcp_forward_init_rejects_non_loopback_targets() { + let init = TcpForwardInit { + sandbox: "sbx".to_string(), + workspace: String::new(), + service_id: String::new(), + target: Some(tcp_forward_init::Target::Tcp(TcpRelayTarget { + host: "example.com".to_string(), + port: 8080, + })), + authorization_token: String::new(), + }; + assert_eq!( + validate_tcp_forward_init(&init) + .expect_err("hostname rejected") + .message(), + "tcp target host must be loopback" + ); + } -// --------------------------------------------------------------------------- -// SSH session handlers -// --------------------------------------------------------------------------- + #[test] + fn tcp_forward_init_rejects_invalid_port() { + let init = TcpForwardInit { + sandbox: "sbx".to_string(), + workspace: String::new(), + service_id: String::new(), + target: Some(tcp_forward_init::Target::Tcp(TcpRelayTarget { + host: "127.0.0.1".to_string(), + port: 0, + })), + authorization_token: String::new(), + }; + assert_eq!( + validate_tcp_forward_init(&init) + .expect_err("zero port rejected") + .message(), + "tcp target port must be between 1 and 65535" + ); + } -/// Whether a relay into the sandbox can open: always when `Ready`, and after -/// the main process exits while its supervisor is connected to any replica. -async fn sandbox_relay_reachable( - state: &Arc, - sandbox: &Sandbox, -) -> Result { - match SandboxPhase::try_from(sandbox.phase()).ok() { - Some(SandboxPhase::Ready) => Ok(true), - Some(SandboxPhase::Completed | SandboxPhase::Error) => { - crate::supervisor_session::supervisor_connected(state, sandbox.object_id()).await - } - _ => Ok(false), + #[test] + fn tcp_forward_init_requires_target() { + let init = TcpForwardInit { + sandbox: "sbx".to_string(), + workspace: String::new(), + ..Default::default() + }; + assert_eq!( + validate_tcp_forward_init(&init) + .expect_err("missing target rejected") + .message(), + "tcp forward target is required" + ); } -} -/// Maximum number of random-name attempts when persisting a new SSH session. -const SSH_SESSION_NAME_ATTEMPTS: usize = 3; -const _: () = assert!(SSH_SESSION_NAME_ATTEMPTS >= 1); + // ---- petname / generate_name ---- -/// Persist a new SSH session record, retrying with a fresh random name when -/// the insert collides with an existing object name in the workspace. -/// -/// Session names are 6 random lowercase letters and records linger for up to -/// the configured TTL (about two hours with the defaults), so a busy -/// workspace can make a freshly drawn name collide on `objects_name_uq`. A -/// redraw is effectively certain to succeed, so the insert is retried with a -/// regenerated name instead of failing the connection. Any other error, -/// including a primary-key collision on the token, is returned to the caller. -async fn persist_ssh_session( - store: &Store, - session: &mut SshSession, - labels_json: Option<&str>, -) -> PersistenceResult<()> { - // Every caller validates metadata before persisting; the redraw below - // relies on it being present. - debug_assert!(session.metadata.is_some()); - for attempt in 1..=SSH_SESSION_NAME_ATTEMPTS { - let result = store - .create_relaxed( - SshSession::object_type(), - &session.token, - session.object_name(), - session.object_workspace(), - &session.encode_to_vec(), - labels_json, - ) - .await; - match result { - Ok(_) => return Ok(()), - Err(error) - if attempt < SSH_SESSION_NAME_ATTEMPTS - && error.is_unique_violation_on("objects_name_uq") => - { - // A session without metadata cannot be redrawn; surface the - // collision instead of retrying an identical insert. - let Some(metadata) = session.metadata.as_mut() else { - return Err(error); - }; - metadata.name = generate_name(); + #[test] + fn sandbox_name_defaults_to_petname_format() { + for _ in 0..50 { + let name = petname::petname(2, "-").expect("petname should produce a name"); + let parts: Vec<&str> = name.split('-').collect(); + assert_eq!( + parts.len(), + 2, + "expected two hyphen-separated words, got: {name}" + ); + for part in &parts { + assert!( + !part.is_empty() && part.chars().all(|c| c.is_ascii_lowercase()), + "each word should be non-empty lowercase ascii: {name}" + ); } - Err(error) => return Err(error), } } - unreachable!("the final attempt returns its error instead of retrying") -} - -pub(super) async fn handle_create_ssh_session( - state: &Arc, - request: Request, -) -> Result, Status> { - let principal = super::extract_principal(&request)?; - let req = request.into_inner(); - let sandbox = resolve_and_authorize_sandbox_name( - state, - &principal, - &req.sandbox, - crate::auth::workspace_authz::selected_workspace_name(req.workspace_scope.as_ref())?, - MinWorkspaceRole::User, - ) - .await?; - let sandbox_id = sandbox.object_id().to_string(); - if !sandbox_relay_reachable(state, &sandbox).await? { - return Err(Status::failed_precondition("sandbox is not ready")); + #[test] + fn generate_routable_name_respects_length_limit() { + for _ in 0..200 { + let name = generate_routable_name(); + assert!( + name.len() <= MAX_ROUTABLE_NAME_LEN, + "generated name '{name}' exceeds {MAX_ROUTABLE_NAME_LEN} chars" + ); + assert!(!name.is_empty(), "generated name should not be empty"); + } } - let token = uuid::Uuid::new_v4().to_string(); - let now_ms = current_time_ms(); - let expires_at_ms = if state.config.ssh_session_ttl_secs > 0 { - now_ms + (state.config.ssh_session_ttl_secs as i64 * 1000) - } else { - 0 - }; - let mut session = SshSession { - metadata: Some(ObjectMeta { - id: token.clone(), - name: generate_name(), - created_time: openshell_core::time::timestamp_from_millis(now_ms).ok(), - labels: HashMap::new(), - resource_version: 0, - annotations: HashMap::new(), - workspace: sandbox.object_workspace().to_string(), - deletion_time: None, - }), - sandbox_id: sandbox_id.clone(), - token: token.clone(), - revoked: false, - expiration_time: openshell_core::time::optional_timestamp_from_legacy_millis(expires_at_ms) - .map_err(|error| Status::internal(error.to_string()))?, - }; - - // Ensure metadata is valid (defense in depth - should always be true for server-constructed metadata) - super::validation::validate_object_metadata(session.metadata.as_ref(), "ssh_session")?; - - // `create_relaxed` fails if the token already exists, like MustCreate, but - // skips the per-commit fsync on SQLite. Losing a freshly minted token in a - // crash only makes it invalid; revocation stays on the durable `put_if`. - let session_labels = session.object_labels(); - let session_labels_json = if session_labels.as_ref().is_none_or(HashMap::is_empty) { - None - } else { - Some( - serde_json::to_string(&session_labels) - .map_err(|e| Status::internal(format!("failed to serialize labels: {e}")))?, - ) - }; - persist_ssh_session(&state.store, &mut session, session_labels_json.as_deref()) - .await - .map_err(|e| Status::internal(format!("persist ssh session failed: {e}")))?; - super::mutation_audit::record_ssh_session(session.object_name()); + #[test] + fn generate_name_fallback_is_valid() { + for _ in 0..50 { + let name = generate_name(); + assert_eq!(name.len(), 6, "unexpected length for fallback name: {name}"); + assert!( + name.chars().all(|c| c.is_ascii_lowercase()), + "fallback name should be all lowercase: {name}" + ); + } + } - let (gateway_host, gateway_port) = resolve_gateway(&state.config); - let scheme = if state.config.tls.is_some() { - "https" - } else { - "http" - }; + /// Import a minimal profile so a synthetic provider type resolves. + /// + /// Provider profiles are import-only: a provider whose type no profile + /// declares cannot compose a sandbox. Tests about limits, CAS or credential + /// collisions still need their placeholder types to exist. + async fn import_test_profile(state: &ServerState, id: &str) { + state + .store + .put_message(&crate::provider_profile_sources::stored_provider_profile( + openshell_core::proto::ProviderProfile { + id: id.to_string(), + display_name: id.to_string(), + category: openshell_core::proto::ProviderProfileCategory::Other as i32, + ..Default::default() + }, + )) + .await + .expect("store test provider profile"); + } - Ok(Response::new(CreateSshSessionResponse { - sandbox_id, - token, - gateway_host, - gateway_port: gateway_port.into(), - gateway_scheme: scheme.to_string(), - host_key_fingerprint: sandbox.host_key_fingerprint.clone(), - expiration_time: openshell_core::time::optional_timestamp_from_legacy_millis(expires_at_ms) - .map_err(|error| Status::internal(error.to_string()))?, - })) -} + fn test_provider(name: &str, provider_type: &str) -> Provider { + test_provider_with_credential_key(name, provider_type, "TOKEN") + } -pub(super) async fn handle_revoke_ssh_session( - state: &Arc, - request: Request, -) -> Result, Status> { - let principal = super::extract_principal(&request)?; - let req = request.into_inner(); - let token = req.token; - if token.is_empty() { - return Err(Status::invalid_argument("token is required")); + fn test_provider_with_credential_key( + name: &str, + provider_type: &str, + credential_key: &str, + ) -> Provider { + Provider { + metadata: Some(ObjectMeta { + id: format!("provider-{name}"), + name: name.to_string(), + created_time: openshell_core::time::timestamp_from_millis(1_000_000).ok(), + labels: HashMap::new(), + resource_version: 0, + annotations: HashMap::new(), + workspace: "default".to_string(), + deletion_time: None, + }), + r#type: provider_type.to_string(), + credentials: std::iter::once((credential_key.to_string(), "secret".to_string())) + .collect(), + config: HashMap::new(), + credential_expiration_times: HashMap::new(), + profile_workspace: "default".to_string(), + credential_handles: HashMap::new(), + } } - let session = state - .store - .get_message::(&token) - .await - .map_err(|e| Status::internal(format!("fetch ssh session failed: {e}")))?; + fn test_sandbox(name: &str, providers: Vec) -> Sandbox { + let mut sandbox = Sandbox { + metadata: Some(ObjectMeta { + id: format!("sandbox-{name}"), + name: name.to_string(), + created_time: openshell_core::time::timestamp_from_millis(1_000_000).ok(), + labels: std::iter::once(("team".to_string(), "agents".to_string())).collect(), + resource_version: 0, + annotations: HashMap::new(), + workspace: "default".to_string(), + deletion_time: None, + }), + spec: Some(SandboxSpec { + log_level: "debug".to_string(), + policy: Some(openshell_core::proto::SandboxPolicy::default()), + providers, + ..Default::default() + }), + ..Default::default() + }; + sandbox.set_phase(SandboxPhase::Ready as i32); + sandbox.set_current_policy_version(7); + sandbox + } - let Some(mut session) = session else { - return Ok(Response::new(RevokeSshSessionResponse { - outcome: super::deletion_outcome(false, req.allow_missing, "ssh session")?, - })); - }; - super::mutation_audit::record_revoked_ssh_session(&session); - authorize_sandbox_workspace( - &state.store, - &state.admin_role, - &principal, - session.object_workspace(), - MinWorkspaceRole::User, - ) - .await - .map_err(|e| { - if e.code() == tonic::Code::PermissionDenied { - Status::not_found("sandbox not found") - } else { - e + fn test_workload_template(name: &str) -> SandboxWorkloadTemplate { + SandboxWorkloadTemplate { + metadata: Some(ObjectMeta { + id: String::new(), + name: name.to_string(), + created_time: openshell_core::time::timestamp_from_millis(0).ok(), + labels: HashMap::from([("team".to_string(), "runtime".to_string())]), + resource_version: 0, + annotations: HashMap::new(), + workspace: String::new(), + deletion_time: None, + }), + spec: Some(openshell_core::proto::SandboxWorkloadTemplateSpec { + workload: Some(openshell_core::proto::SandboxWorkloadConfig { + image: "registry.example.com/agent:latest".to_string(), + environment: HashMap::from([("FEATURE_FLAG".to_string(), "on".to_string())]), + resources: Some(SandboxResources { + cpu: "2".to_string(), + memory: "4Gi".to_string(), + gpu: Some(GpuResourceRequirements { count: Some(1) }), + }), + }), + driver_config: None, + desired_service_level: None, + }), } - })?; - - if session.revoked { - super::mutation_audit::record_repeated_revoke(); - return Ok(Response::new(RevokeSshSessionResponse { - outcome: openshell_core::proto::DeletionOutcome::Completed.into(), - })); } - let resource_version = session - .metadata - .as_ref() - .map_or(0, |metadata| metadata.resource_version); - - session.revoked = true; + fn proto_string_value(value: &Value) -> Option<&str> { + match value.kind.as_ref() { + Some(Kind::StringValue(value)) => Some(value.as_str()), + _ => None, + } + } - // Use CAS to prevent lost updates from concurrent revocations - let session_labels = session.object_labels(); - let session_labels_json = if session_labels.as_ref().is_none_or(HashMap::is_empty) { - None - } else { - Some( - serde_json::to_string(&session_labels) - .map_err(|e| Status::internal(format!("failed to serialize labels: {e}")))?, - ) - }; - state - .store - .put_if( - SshSession::object_type(), - session.object_id(), - session.object_name(), - session.object_workspace(), - &session.encode_to_vec(), - session_labels_json.as_deref(), - WriteCondition::MatchResourceVersion(resource_version), - ) - .await - .map_err(|e| super::persistence_error_to_status(e, "revoke ssh session"))?; + #[tokio::test] + async fn watch_producer_releases_request_span_when_client_disconnects() { + use crate::otel_tracing::test_exporter; + use tokio_stream::StreamExt as _; + use tracing::Instrument as _; - Ok(Response::new(RevokeSshSessionResponse { - outcome: openshell_core::proto::DeletionOutcome::Completed.into(), - })) -} + let state = test_server_state().await; + let sandbox = test_sandbox("watched", Vec::new()); + state.store.put_message(&sandbox).await.unwrap(); -// --------------------------------------------------------------------------- -// Exec transport helpers -// --------------------------------------------------------------------------- + let traced = test_exporter::install_traced(); + let request_span = tracing::info_span!("disconnected_watch_request"); + let mut handler = Box::pin( + handle_watch_sandbox( + &state, + authed_request(WatchSandboxRequest { + sandbox: "watched".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), + ..Default::default() + }), + ) + .instrument(request_span.clone()), + ); + let response = handler.as_mut().await.unwrap(); + // A completed instrumented future can retain its span until the future + // itself is dropped. Release the handler's clone so this test isolates + // whether the spawned watch producer retains the request span. + drop(handler); + let mut stream = response.into_inner(); + stream + .next() + .await + .expect("watch producer should send the initial snapshot") + .unwrap(); -fn resolve_gateway(config: &openshell_core::Config) -> (String, u16) { - ( - config.bind_address.ip().to_string(), - config.bind_address.port(), - ) -} + drop(request_span); + stream.disconnect_and_wait().await; + traced.wait_for_span("disconnected_watch_request").await; -/// Shell-escape a value for embedding in a POSIX shell command. -/// -/// Wraps unsafe values in single quotes with the standard `'\''` idiom for -/// embedded single-quote characters. Rejects null bytes which can truncate -/// shell parsing at the C level. -fn shell_escape(value: &str) -> Result { - if value.bytes().any(|b| b == 0) { - return Err("value contains null bytes".to_string()); - } - if value.is_empty() { - return Ok("''".to_string()); - } - let safe = value - .bytes() - .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'/' | b'-' | b'_')); - if safe { - return Ok(value.to_string()); + assert_eq!( + traced.spans_named("disconnected_watch_request").len(), + 1, + "watch producer should release the request span after client disconnect" + ); } - let escaped = value.replace('\'', "'\"'\"'"); - Ok(format!("'{escaped}'")) -} -/// Maximum total length of the assembled shell command string. -const MAX_COMMAND_STRING_LEN: usize = 256 * 1024; // 256 KiB + #[tokio::test] + async fn logs_only_watch_ends_when_sweeper_frees_sandbox_deleted_elsewhere() { + use tokio_stream::StreamExt as _; -/// SSH keepalive for silent exec relays; stdout idle is not a timeout signal. -const EXEC_KEEPALIVE_INTERVAL: std::time::Duration = std::time::Duration::from_secs(15); + let state = test_server_state().await; + let sandbox = test_sandbox("swept", Vec::new()); + state.store.put_message(&sandbox).await.unwrap(); + let id = sandbox.object_id().to_string(); -/// Allow this many missed keepalive responses before russh fails the relay. -const EXEC_KEEPALIVE_MAX: usize = 4; + let response = handle_watch_sandbox( + &state, + authed_request(WatchSandboxRequest { + sandbox: sandbox.object_name().to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), + follow_logs: true, + ..Default::default() + }), + ) + .await + .unwrap(); + let mut stream = response.into_inner(); -/// Max wait for a trailing `Close` after `ExitStatus`. -const EXEC_POST_EXIT_CLOSE_TIMEOUT: std::time::Duration = std::time::Duration::from_millis(500); + // A delivered log line proves the watch has subscribed. + seed_log_lines(&state, &id, 1); + loop { + let event = stream.next().await.unwrap().unwrap(); + if !event.cursor.is_empty() { + break; + } + } -/// Supervisor SSH banner software token that signals no-login-shell support. -const OPENSHELL_SSHID_PREFIX: &[u8] = b"SSH-2.0-OpenShell_"; + // Another replica deletes the record; this one never runs delete cleanup. + state + .store + .delete(Sandbox::object_type(), &id) + .await + .unwrap(); + let mut suspects = HashSet::new(); + for expected in [0, 1] { + let closed = crate::bus_sweeper::sweep_once( + &state.store, + &state.tracing_log_bus, + std::time::Duration::ZERO, + &mut suspects, + ) + .await + .unwrap(); + assert_eq!(closed, expected); + } -/// A supervisor honors `OPENSHELL_NO_LOGIN_SHELL` only if it identifies as -/// `OpenShell`. Older sandboxes present russh's default banner and silently -/// ignore the env request, so gate the opt-out on the `OpenShell` identity. -fn supervisor_supports_no_login_shell(remote_sshid: &[u8]) -> bool { - remote_sshid.starts_with(OPENSHELL_SSHID_PREFIX) -} + let ended = tokio::time::timeout(std::time::Duration::from_secs(5), async { + while let Some(item) = stream.next().await { + if item.is_err() { + break; + } + } + }) + .await; + assert!( + ended.is_ok(), + "logs-only watch should end once its buffers are freed" + ); + } -/// russh client config for exec relays. -fn exec_ssh_client_config() -> russh::client::Config { - russh::client::Config { - keepalive_interval: Some(EXEC_KEEPALIVE_INTERVAL), - keepalive_max: EXEC_KEEPALIVE_MAX, - ..Default::default() + /// Seed `n` log lines onto the log bus; cursors run 1..=n. + fn seed_log_lines(state: &ServerState, sandbox_id: &str, n: usize) { + for i in 0..n { + state + .tracing_log_bus + .publish_external(openshell_core::proto::SandboxLogLine { + sandbox_id: sandbox_id.to_string(), + event_time: openshell_core::time::timestamp_from_millis(i as i64).ok(), + level: "INFO".to_string(), + target: "test".to_string(), + message: format!("line {i}"), + source: "gateway".to_string(), + ..Default::default() + }); + } } -} -/// Require both the command status and channel close before reporting success. -fn exec_loop_result(exit_code: Option, close_seen: bool) -> Result { - match (exit_code, close_seen) { - (Some(code), true) => Ok(code), - (None, _) => Err(Status::unavailable( - "exec relay closed before the command reported an exit status", - )), - (Some(_), false) => Err(Status::unavailable( - "exec relay closed before the SSH channel finished", - )), + fn seed_platform_event(state: &ServerState, sandbox_id: &str, reason: &str) { + state.tracing_log_bus.platform_event_bus.publish( + sandbox_id, + SandboxStreamEvent { + payload: Some(openshell_core::proto::sandbox_stream_event::Payload::Event( + openshell_core::proto::PlatformEvent { + event_time: openshell_core::time::timestamp_from_millis(0).ok(), + source: "test".to_string(), + r#type: "Normal".to_string(), + reason: reason.to_string(), + message: reason.to_string(), + metadata: HashMap::new(), + }, + )), + cursor: String::new(), + }, + ); } -} -fn build_remote_exec_command(req: &ExecSandboxRequest) -> Result { - let mut parts = Vec::new(); - let mut env_entries = req.environment.iter().collect::>(); - env_entries.sort_by_key(|(a, _)| *a); - for (key, value) in env_entries { - parts.push(format!("{key}={}", shell_escape(value)?)); + /// Build the token a client would hold for `seq` in this sandbox's *current* + /// cursor space. Capture it before any teardown to model a real reconnect. + fn cursor_token(state: &ServerState, sandbox_id: &str, seq: u64) -> String { + let space = state + .tracing_log_bus + .cursor_space(sandbox_id) + .expect("cursor space exists; publish before taking a token"); + WatchCursor::new(space.epoch, seq).encode() } - for arg in &req.command { - parts.push(shell_escape(arg)?); + + /// A well-formed token from an epoch this server never issued. + fn foreign_cursor(seq: u64) -> String { + WatchCursor::new(uuid::Uuid::new_v4(), seq).encode() } - let command = parts.join(" "); - let result = if req.workdir.is_empty() { - command - } else { - format!("cd {} && {command}", shell_escape(&req.workdir)?) - }; - if result.len() > MAX_COMMAND_STRING_LEN { - return Err(format!( - "assembled command string exceeds {MAX_COMMAND_STRING_LEN} byte limit" - )); + + /// Sequence number carried by a delivered event. Panics on non-resumable + /// events, so a test that expects a log line cannot silently pass on a + /// snapshot. + fn seq_of(evt: &SandboxStreamEvent) -> u64 { + WatchCursor::parse(&evt.cursor) + .expect("resumable event must carry a valid cursor") + .seq } - Ok(result) -} -/// Execute a command over an SSH transport relayed through a supervisor session. -/// -/// This is the relay equivalent of `stream_exec_over_ssh`. Instead of dialing a -/// sandbox endpoint directly, the SSH transport runs over a `DuplexStream` that -/// is bridged to the supervisor's local SSH daemon via `RelayStream`. -#[allow(clippy::too_many_arguments)] -async fn stream_exec_over_relay( - tx: mpsc::Sender>, - sandbox_id: &str, - channel_id: &str, - relay_stream: tokio::io::DuplexStream, - command: &str, - stdin_payload: Vec, - execution_timeout: Option, - request_tty: bool, - no_login_shell: bool, - cols: u32, - rows: u32, - completion: Option, -) -> Result<(), Status> { - let command_preview: String = command - .chars() - .take(120) - .flat_map(char::escape_default) - .collect(); - info!( - sandbox_id = %sandbox_id, - channel_id = %channel_id, - command_len = command.len(), - stdin_len = stdin_payload.len(), - command_preview = %command_preview, - "ExecSandbox (relay): command started" - ); + #[tokio::test] + async fn resume_replays_only_events_after_cursor() { + use tokio_stream::StreamExt as _; - let (local_proxy_port, proxy_task) = start_single_use_ssh_proxy_over_relay(relay_stream) - .await - .map_err(|e| Status::internal(format!("failed to start relay proxy: {e}")))?; + let state = test_server_state().await; + let sandbox = test_sandbox("resumed", Vec::new()); + state.store.put_message(&sandbox).await.unwrap(); + let id = sandbox.object_id().to_string(); - let exec = run_exec_with_russh( - local_proxy_port, - command, - stdin_payload, - request_tty, - no_login_shell, - (cols, rows), - tx.clone(), - ); + // Cursors 1,2,3. + seed_log_lines(&state, &id, 3); - let exec_result = wait_for_exec_terminal(exec, execution_timeout, completion).await; - if matches!(exec_result, Ok(None)) { - let _ = tx - .send(Ok(ExecSandboxEvent { - payload: Some(openshell_core::proto::exec_sandbox_event::Payload::Exit( - ExecSandboxExit { exit_code: 124 }, - )), - })) - .await; - finish_interactive_exec_proxy(proxy_task).await; - return Ok(()); - } + let response = handle_watch_sandbox( + &state, + authed_request(WatchSandboxRequest { + sandbox: sandbox.object_name().to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), + follow_logs: true, + resume_after_cursor: cursor_token(&state, &id, 1), + ..Default::default() + }), + ) + .await + .unwrap(); - let exit_code = match exec_result { - Ok(Some(code)) => code, - Ok(None) => unreachable!("timeout returned above"), - Err(status) => { - finish_interactive_exec_proxy(proxy_task).await; - return Err(status); - } - }; + let mut stream = response.into_inner(); + // Snapshot first (status re-read, no cursor). + let snap = stream.next().await.unwrap().unwrap(); + assert!( + snap.cursor.is_empty(), + "first event should be the status snapshot" + ); - finish_interactive_exec_proxy(proxy_task).await; + // Then only seqs 2 and 3; seq 1 already seen by the client. + let a = stream.next().await.unwrap().unwrap(); + let b = stream.next().await.unwrap().unwrap(); + assert_eq!(seq_of(&a), 2); + assert_eq!(seq_of(&b), 3); + } - let _ = tx - .send(Ok(ExecSandboxEvent { - payload: Some(openshell_core::proto::exec_sandbox_event::Payload::Exit( - ExecSandboxExit { exit_code }, - )), - })) - .await; + #[tokio::test] + async fn resume_merges_log_and_platform_events_in_cursor_order() { + use tokio_stream::StreamExt as _; - Ok(()) -} + let state = test_server_state().await; + let sandbox = test_sandbox("merged", Vec::new()); + state.store.put_message(&sandbox).await.unwrap(); + let id = sandbox.object_id().to_string(); -#[allow(clippy::too_many_arguments)] -async fn stream_interactive_exec_over_relay( - tx: mpsc::Sender>, - sandbox_id: &str, - channel_id: &str, - relay_stream: tokio::io::DuplexStream, - command: &str, - input_stream: tonic::Streaming, - request_tty: bool, - no_login_shell: bool, - execution_timeout: Option, - cols: u32, - rows: u32, - completion: Option, -) -> Result<(), Status> { - let command_preview: String = command - .chars() - .take(120) - .flat_map(char::escape_default) - .collect(); - info!( - sandbox_id = %sandbox_id, - channel_id = %channel_id, - command_len = command.len(), - command_preview = %command_preview, - "ExecSandboxInteractive (relay): command started" - ); + // Interleave across the shared allocator: log=1, platform=2, log=3, platform=4. + seed_log_lines(&state, &id, 1); // cursor 1 + seed_platform_event(&state, &id, "e2"); // cursor 2 + state + .tracing_log_bus + .publish_external(openshell_core::proto::SandboxLogLine { + sandbox_id: id.clone(), + event_time: openshell_core::time::timestamp_from_millis(3).ok(), + level: "INFO".to_string(), + target: "test".to_string(), + message: "line 3".to_string(), + source: "gateway".to_string(), + ..Default::default() + }); // cursor 3 + seed_platform_event(&state, &id, "e4"); // cursor 4 - let (local_proxy_port, proxy_task) = start_single_use_ssh_proxy_over_relay(relay_stream) + let response = handle_watch_sandbox( + &state, + authed_request(WatchSandboxRequest { + sandbox: sandbox.object_name().to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), + follow_logs: true, + follow_events: true, + resume_after_cursor: cursor_token(&state, &id, 1), + ..Default::default() + }), + ) .await - .map_err(|e| Status::internal(format!("failed to start relay proxy: {e}")))?; + .unwrap(); - let exec = run_interactive_exec_with_russh( - local_proxy_port, - command, - input_stream, - request_tty, - no_login_shell, - cols, - rows, - tx.clone(), - ); + let mut stream = response.into_inner(); + let snap = stream.next().await.unwrap().unwrap(); + assert!(snap.cursor.is_empty()); - let exec_result = wait_for_exec_terminal(exec, execution_timeout, completion).await; - if matches!(exec_result, Ok(None)) { - let _ = tx - .send(Ok(ExecSandboxEvent { - payload: Some(openshell_core::proto::exec_sandbox_event::Payload::Exit( - ExecSandboxExit { exit_code: 124 }, - )), - })) - .await; - finish_interactive_exec_proxy(proxy_task).await; - return Ok(()); + // Merged from both buses, ascending by shared seq: 2,3,4. + let mut got = Vec::new(); + for _ in 0..3 { + got.push(seq_of(&stream.next().await.unwrap().unwrap())); + } + assert_eq!(got, vec![2, 3, 4]); } - let exit_code = match exec_result { - Ok(Some(code)) => code, - Ok(None) => unreachable!("timeout returned above"), - Err(status) => { - finish_interactive_exec_proxy(proxy_task).await; - return Err(status); - } - }; + /// The initial tail is the resume path's twin: it draws from the same two + /// buses over the same shared cursor space, so it owes the client the same + /// ascending order. + /// + /// Before the merge, each bus was drained in its own pass and the tail came + /// out grouped by source -- logs 1,3 then platform 2,4 -- so a client + /// tracking the highest cursor saw it go backwards mid-tail. + #[tokio::test] + async fn initial_tail_merges_log_and_platform_events_in_cursor_order() { + use tokio_stream::StreamExt as _; - finish_interactive_exec_proxy(proxy_task).await; + let state = test_server_state().await; + let sandbox = test_sandbox("tailmerged", Vec::new()); + state.store.put_message(&sandbox).await.unwrap(); + let id = sandbox.object_id().to_string(); - let _ = tx - .send(Ok(ExecSandboxEvent { - payload: Some(openshell_core::proto::exec_sandbox_event::Payload::Exit( - ExecSandboxExit { exit_code }, - )), - })) - .await; + // Interleave across the shared allocator: log=1, platform=2, log=3, platform=4. + seed_log_lines(&state, &id, 1); // cursor 1 + seed_platform_event(&state, &id, "e2"); // cursor 2 + state + .tracing_log_bus + .publish_external(openshell_core::proto::SandboxLogLine { + sandbox_id: id.clone(), + event_time: openshell_core::time::timestamp_from_millis(3).ok(), + level: "INFO".to_string(), + target: "test".to_string(), + message: "line 3".to_string(), + source: "gateway".to_string(), + ..Default::default() + }); // cursor 3 + seed_platform_event(&state, &id, "e4"); // cursor 4 - Ok(()) -} + let response = handle_watch_sandbox( + &state, + authed_request(WatchSandboxRequest { + sandbox: sandbox.object_name().to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), + follow_logs: true, + follow_events: true, + // event_tail has no default; 0 would replay no platform events. + event_tail: 10, + ..Default::default() + }), + ) + .await + .unwrap(); -/// `Ok(Some(code))` requires a real SSH `ExitStatus`, including nonzero codes. -/// Synthetic gateway timeouts, lost status, and dropped futures leave the claim -/// unresolved. Finalization precedes terminal delivery to the client. -pub(super) async fn wait_for_exec_terminal( - exec: impl Future>, - execution_timeout: Option, - completion: Option, -) -> Result, Status> { - let result = if let Some(execution_timeout) = execution_timeout { - match tokio::time::timeout(execution_timeout, exec).await { - Ok(result) => result, - Err(_) => return Ok(None), + let mut stream = response.into_inner(); + let snap = stream.next().await.unwrap().unwrap(); + assert!(snap.cursor.is_empty()); + + let mut got = Vec::new(); + for _ in 0..4 { + got.push(seq_of(&stream.next().await.unwrap().unwrap())); } - } else { - exec.await - }; - let exit_code = result?; - if let Some(completion) = completion { - completion.stream_terminal().await?; + assert_eq!(got, vec![1, 2, 3, 4]); } - Ok(Some(exit_code)) -} -async fn finish_interactive_exec_proxy(mut task: tokio::task::JoinHandle<()>) { - if tokio::time::timeout(EXEC_POST_EXIT_CLOSE_TIMEOUT, &mut task) - .await - .is_err() - { - task.abort(); - let _ = task.await; - } -} + #[tokio::test] + async fn live_delivery_orders_events_across_sources_by_cursor() { + use tokio_stream::StreamExt as _; -#[allow(clippy::too_many_arguments)] -async fn run_interactive_exec_with_russh( - local_proxy_port: u16, - command: &str, - mut input_stream: impl futures::Stream> + Unpin, - request_tty: bool, - no_login_shell: bool, - cols: u32, - rows: u32, - tx: mpsc::Sender>, -) -> Result { - use futures::StreamExt; - use openshell_core::proto::exec_sandbox_input::Payload; - use russh::ChannelMsg; + let state = test_server_state().await; + let sandbox = test_sandbox("liveorder", Vec::new()); + state.store.put_message(&sandbox).await.unwrap(); + let id = sandbox.object_id().to_string(); - if command.as_bytes().contains(&0) { - return Err(Status::invalid_argument( - "command contains null bytes at transport boundary", - )); - } - if command.len() > MAX_COMMAND_STRING_LEN { - return Err(Status::invalid_argument(format!( - "command exceeds {MAX_COMMAND_STRING_LEN} byte limit at transport boundary" - ))); - } + let response = handle_watch_sandbox( + &state, + authed_request(WatchSandboxRequest { + sandbox: sandbox.object_name().to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), + follow_logs: true, + follow_events: true, + ..Default::default() + }), + ) + .await + .unwrap(); - let stream = - openshell_core::net::connect_tcp_nodelay_best_effort(("127.0.0.1", local_proxy_port)) - .await - .map_err(|e| Status::internal(format!("failed to connect to ssh proxy: {e}")))?; + let mut stream = response.into_inner(); + // The snapshot itself only proves both subscriptions are live -- the + // replay reads come after it. But on this current-thread runtime the + // producer cannot yield between the two, so by the time the test task + // is scheduled again the producer has run through to the live loop. + let snap = stream.next().await.unwrap().unwrap(); + assert!(snap.cursor.is_empty()); - let config = Arc::new(exec_ssh_client_config()); - let remote_sshid = Arc::new(std::sync::Mutex::new(None)); - let handler = SandboxSshClientHandler { - remote_sshid: remote_sshid.clone(), - }; - let mut client = russh::client::connect_stream(config, stream, handler) - .await - .map_err(|e| Status::internal(format!("failed to establish ssh transport: {e}")))?; + // Publish without awaiting in between. On the current-thread runtime + // the producer cannot interleave, so both channels hold ready events + // when it next polls -- the state where `select!` picks arbitrarily and + // would otherwise emit a log cursor ahead of a lower platform cursor. + for i in 0..5 { + seed_log_lines(&state, &id, 1); // odd cursors + seed_platform_event(&state, &id, &format!("e{i}")); // even cursors + } - match client - .authenticate_none("sandbox") - .await - .map_err(|e| Status::internal(format!("failed to authenticate ssh session: {e}")))? - { - AuthResult::Success => {} - AuthResult::Failure { .. } => { - return Err(Status::permission_denied( - "ssh authentication rejected by sandbox", - )); + let mut got = Vec::new(); + for _ in 0..10 { + got.push(seq_of(&stream.next().await.unwrap().unwrap())); } + assert_eq!(got, (1..=10).collect::>()); } - let channel = client - .channel_open_session() - .await - .map_err(|e| Status::internal(format!("failed to open ssh channel: {e}")))?; + /// A reconnect resumes from the highest cursor the client saw, so live + /// delivery may never emit a cursor while a lower one is still undelivered. + /// The producer drains the log receiver before the platform one: a log line + /// published after that first drain but before the platform drain finishes + /// misses the batch, and its seq is below platform cursors the same batch + /// carries. Emitting them strands the log line -- a disconnect there resumes + /// above it, and no replay ever returns it. The publication watermark holds + /// back anything the drain cannot prove it saw in full. + /// + /// Reaching that interleaving takes a wide drain: the producer is first + /// parked on a full stream channel so a platform backlog accumulates, then + /// both sources are hammered from other worker threads while it walks that + /// backlog. Serialized against the test task the window does not exist -- + /// the drain holds no await a single-threaded test could wedge open. + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn live_delivery_never_emits_a_cursor_above_an_undrained_event() { + use tokio_stream::StreamExt as _; - if request_tty { - channel - .request_pty(false, "xterm-256color", cols, rows, 0, 0, &[]) - .await - .map_err(|e| Status::internal(format!("failed to allocate PTY: {e}")))?; - } + /// Enough to overrun the 256-slot stream channel and park the producer. + const PARK: usize = 400; + /// Platform events queued while it is parked. The next drain walks all + /// of them, and that walk is the window the hammers below publish into. + /// Kept under the 1024-slot broadcast capacity so nothing is dropped. + const BACKLOG: usize = 600; + const HAMMER: usize = 300; + /// Hitting the window is a race, so repeat it. One round reproduced the + /// unfixed behavior in two runs of three; four caught it in ten of ten. + const ROUNDS: u64 = 4; + /// The single line published to confirm the producer finished + /// initialization before the rounds below start publishing. + const HANDSHAKE: u64 = 1; + const PER_ROUND: u64 = (PARK + BACKLOG + HAMMER * 2) as u64; + const TOTAL: u64 = PER_ROUND * ROUNDS + HANDSHAKE; - if no_login_shell { - let banner = remote_sshid.lock().unwrap().clone().unwrap_or_default(); - if !supervisor_supports_no_login_shell(&banner) { - return Err(Status::failed_precondition( - "sandbox supervisor is too old to honor --no-login-shell; recreate the sandbox on a current gateway", - )); - } - channel - .set_env(false, NO_LOGIN_SHELL_ENV.0, NO_LOGIN_SHELL_ENV.1) - .await - .map_err(|e| Status::internal(format!("failed to set login-shell env: {e}")))?; - } + let state = test_server_state().await; + let sandbox = test_sandbox("watermark", Vec::new()); + state.store.put_message(&sandbox).await.unwrap(); + let id = sandbox.object_id().to_string(); - channel - .exec(true, command.as_bytes()) + let response = handle_watch_sandbox( + &state, + authed_request(WatchSandboxRequest { + sandbox: sandbox.object_name().to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), + follow_logs: true, + follow_events: true, + ..Default::default() + }), + ) .await - .map_err(|e| Status::internal(format!("failed to execute command over ssh: {e}")))?; + .unwrap(); + let mut stream = response.into_inner(); + // The snapshot only proves both subscriptions are live; the producer + // sends it before reading either replay window. Publishing the rest of + // this test against that state is unsound: the log tail is capped at + // 200 by default, so a burst landing before the read is truncated, the + // rest is suppressed as already replayed, and the test stalls. + // + // One line is the handshake. Receiving it with a cursor -- replayed or + // live, either way -- proves the producer is past both tail reads, and + // one line cannot overflow any tail. Everything below is published into + // a producer known to be in the live loop. + let snap = stream.next().await.unwrap().unwrap(); + assert!(snap.cursor.is_empty()); + seed_log_lines(&state, &id, 1); + let handshake = stream.next().await.unwrap().unwrap(); + assert_eq!( + seq_of(&handshake), + HANDSHAKE, + "handshake line should be seq 1" + ); - let (mut read_half, write_half) = channel.split(); + let mut highest = HANDSHAKE; + let mut seen = HANDSHAKE; + let mut last_cursor = handshake.cursor; - // Keep both directions independently polled, but owned by this operation. - // A detached stdin task would survive operation timeout and retain the SSH - // channel. Normal request EOF closes stdin only, never the output channel. - let input = async { - while let Some(msg) = input_stream.next().await { - // Even ignored non-PTY resize frames must cooperate with output - // and cancellation when the request stream stays continuously ready. - tokio::task::consume_budget().await; - let msg = msg?; - match msg.payload { - Some(Payload::Stdin(data)) => { - write_half - .data(std::io::Cursor::new(data)) - .await - .map_err(|_| { - Status::unavailable("exec relay failed while writing stdin") - })?; - } - Some(Payload::Resize(resize)) => { - if request_tty { - write_half - .window_change(resize.cols, resize.rows, 0, 0) - .await - .map_err(|_| Status::unavailable("exec relay failed while resizing"))?; - } - } - Some(Payload::Start(_)) | None => { - return Err(Status::invalid_argument( - "expected stdin or resize after exec start", - )); - } + for round in 0..ROUNDS { + // Nothing reads during this round's setup, so the producer fills + // the stream channel and blocks part-way through this batch. + seed_log_lines(&state, &id, PARK); + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + + for i in 0..BACKLOG { + seed_platform_event(&state, &id, &format!("b{round}-{i}")); } - } - write_half - .eof() - .await - .map_err(|_| Status::unavailable("exec relay failed while closing stdin")) - }; - let output = async { - let mut exit_code: Option = None; - let mut close_seen = false; - loop { - // Bound the post-ExitStatus wait against a lost Close. - let msg = if exit_code.is_some() { - match tokio::time::timeout(EXEC_POST_EXIT_CLOSE_TIMEOUT, read_half.wait()).await { - Ok(Some(msg)) => msg, - Ok(None) | Err(_) => break, - } - } else { - match read_half.wait().await { - Some(msg) => msg, - None => break, - } - }; - match msg { - ChannelMsg::Data { data } => { - let event = Ok(ExecSandboxEvent { - payload: Some(openshell_core::proto::exec_sandbox_event::Payload::Stdout( - ExecSandboxStdout { - data: data.to_vec(), - }, - )), - }); - if tx.send(event).await.is_err() { - break; + let log_hammer = { + let state = Arc::clone(&state); + let id = id.clone(); + tokio::spawn(async move { + for _ in 0..HAMMER { + seed_log_lines(&state, &id, 1); } - } - ChannelMsg::ExtendedData { data, .. } => { - let event = Ok(ExecSandboxEvent { - payload: Some(openshell_core::proto::exec_sandbox_event::Payload::Stderr( - ExecSandboxStderr { - data: data.to_vec(), - }, - )), - }); - if tx.send(event).await.is_err() { - break; + }) + }; + let platform_hammer = { + let state = Arc::clone(&state); + let id = id.clone(); + tokio::spawn(async move { + for i in 0..HAMMER { + seed_platform_event(&state, &id, &format!("h{round}-{i}")); } - } - ChannelMsg::ExitStatus { exit_status } => { - let converted = i32::try_from(exit_status).unwrap_or(i32::MAX); - exit_code = Some(converted); - } - ChannelMsg::Close => { - close_seen = true; - break; - } - _ => {} + }) + }; + + while seen < PER_ROUND * (round + 1) + HANDSHAKE { + let evt = tokio::time::timeout(std::time::Duration::from_secs(30), stream.next()) + .await + .unwrap_or_else(|_| { + panic!( + "live delivery stalled after {seen}/{TOTAL} events, highest {highest}" + ) + }) + .unwrap() + .unwrap(); + let seq = seq_of(&evt); + // Ascending delivery is what makes a highest-cursor resume safe. + // Without the watermark this trips: a log line published during + // the platform walk follows platform cursors emitted above it. + assert!(seq > highest, "cursor {seq} emitted after {highest}"); + highest = seq; + last_cursor = evt.cursor; + seen += 1; } + + log_hammer.await.unwrap(); + platform_hammer.await.unwrap(); } - exec_loop_result(exit_code, close_seen) - }; + // Every seq in the space belongs to one of the two buses, so `TOTAL` + // ascending events ending at `TOTAL` means none was skipped. + assert_eq!(highest, TOTAL, "live delivery skipped a cursor"); - let result = { - tokio::pin!(input, output); - let exchange = async { - tokio::select! { - result = &mut input => { - result?; - output.await - } - result = &mut output => result, - } - }; - tokio::select! { - biased; - () = tx.closed() => Err(Status::cancelled("exec response stream closed")), - result = exchange => result, - } - }; + // Reconnecting from that cursor is consistent with what was delivered: + // the replay resumes at the next event rather than past one. + seed_log_lines(&state, &id, 1); + seed_platform_event(&state, &id, "after-resume"); + drop(stream); - // EOF above deliberately leaves this channel open until output completes. - // Bound cleanup even if the SSH peer is no longer making progress. - let _ = tokio::time::timeout(EXEC_POST_EXIT_CLOSE_TIMEOUT, write_half.close()).await; - let _ = tokio::time::timeout( - EXEC_POST_EXIT_CLOSE_TIMEOUT, - client.disconnect(russh::Disconnect::ByApplication, "exec complete", "en"), - ) - .await; + let response = handle_watch_sandbox( + &state, + authed_request(WatchSandboxRequest { + sandbox: sandbox.object_name().to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), + follow_logs: true, + follow_events: true, + resume_after_cursor: last_cursor, + ..Default::default() + }), + ) + .await + .unwrap(); + let mut stream = response.into_inner(); + let snap = stream.next().await.unwrap().unwrap(); + assert!(snap.cursor.is_empty()); - result -} + let a = stream.next().await.unwrap().unwrap(); + let b = stream.next().await.unwrap().unwrap(); + assert_eq!(seq_of(&a), TOTAL + 1); + assert_eq!(seq_of(&b), TOTAL + 2); + } -/// Create a localhost SSH proxy that bridges to a relay `DuplexStream`. -/// -/// The proxy forwards raw SSH bytes between the `russh` client and the relay. -/// The supervisor bridges the relay to its Unix-socket SSH daemon; filesystem -/// permissions on that socket are the only access-control boundary. -async fn start_single_use_ssh_proxy_over_relay( - mut relay_stream: tokio::io::DuplexStream, -) -> Result<(u16, tokio::task::JoinHandle<()>), Box> { - let listener = TcpListener::bind(("127.0.0.1", 0)).await?; - let port = listener.local_addr()?.port(); + /// A lag warning carries no cursor, so it is never replayed on resume. Sent + /// after the surviving events of its own batch, a disconnect in between + /// leaves the client checkpointed past the dropped range having never been + /// told anything was dropped. The warning must lead the batch. + /// + /// Which branch `select!` takes is arbitrary, so the run is repeated: the + /// assertion holds on both paths, but only the platform-first path reaches + /// the drain's lag counter, which is where the ordering used to be wrong. + /// Eight attempts caught the unfixed ordering in three runs of five; forty + /// caught it in six of six. + #[tokio::test] + async fn lag_warning_precedes_the_events_of_its_batch() { + use openshell_core::proto::sandbox_stream_event::Payload; + use tokio_stream::StreamExt as _; - let task = tokio::spawn(async move { - let Ok((mut client_conn, _)) = listener.accept().await else { - warn!("SSH relay proxy: failed to accept local connection"); - return; - }; - // Loopback bridge for interactive SSH exec (keystrokes, line-buffered - // PTY output) — disable Nagle so tinygrams don't stall on delayed ACKs. - set_tcp_nodelay_best_effort(&client_conn); - let _ = tokio::io::copy_bidirectional(&mut client_conn, &mut relay_stream).await; - }); + /// `select!` polls the log receiver before the platform one in three of + /// its four rotations, and only the platform-first path reaches the + /// drain's lag counter. Repeat enough that missing it is negligible. + const ATTEMPTS: usize = 40; - Ok((port, task)) -} + let state = test_server_state().await; -#[derive(Debug, Clone)] -struct SandboxSshClientHandler { - remote_sshid: Arc>>>, -} + for attempt in 0..ATTEMPTS { + let sandbox = test_sandbox(&format!("lagorder{attempt}"), Vec::new()); + state.store.put_message(&sandbox).await.unwrap(); + let id = sandbox.object_id().to_string(); -impl russh::client::Handler for SandboxSshClientHandler { - type Error = russh::Error; + let response = handle_watch_sandbox( + &state, + authed_request(WatchSandboxRequest { + sandbox: sandbox.object_name().to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), + follow_logs: true, + follow_events: true, + ..Default::default() + }), + ) + .await + .unwrap(); + let mut stream = response.into_inner(); + let snap = stream.next().await.unwrap().unwrap(); + assert!(snap.cursor.is_empty()); - async fn check_server_key( - &mut self, - _server_public_key: &russh::keys::PublicKeyOrCertificate, - ) -> Result { - Ok(true) - } + // One platform event plus a log burst past the 1024-slot broadcast + // capacity, published without an await in between so the producer + // sees both on a single wake-up: a deliverable event and a drop. + seed_platform_event(&state, &id, "e1"); + seed_log_lines(&state, &id, 1100); - async fn kex_done( - &mut self, - _shared_secret: Option<&[u8]>, - _names: &russh::Names, - session: &mut russh::client::Session, - ) -> Result<(), Self::Error> { - *self.remote_sshid.lock().unwrap() = Some(session.remote_sshid().to_vec()); - Ok(()) + let first = stream.next().await.unwrap().unwrap(); + assert!( + matches!(first.payload, Some(Payload::Warning(_))), + "the lag warning must arrive before any event of the lagged batch, got {:?}", + first.payload + ); + } } -} -async fn run_exec_with_russh( - local_proxy_port: u16, - command: &str, - stdin_payload: Vec, - request_tty: bool, - no_shell_login: bool, - pty_size: (u32, u32), - tx: mpsc::Sender>, -) -> Result { - let (cols, rows) = pty_size; + #[tokio::test] + async fn resume_at_latest_cursor_suppresses_duplicates() { + use tokio_stream::StreamExt as _; - // Defense-in-depth: validate command at the transport boundary. - if command.as_bytes().contains(&0) { - return Err(Status::invalid_argument( - "command contains null bytes at transport boundary", - )); - } - if command.len() > MAX_COMMAND_STRING_LEN { - return Err(Status::invalid_argument(format!( - "command exceeds {MAX_COMMAND_STRING_LEN} byte limit at transport boundary" - ))); - } + let state = test_server_state().await; + let sandbox = test_sandbox("nodup", Vec::new()); + state.store.put_message(&sandbox).await.unwrap(); + let id = sandbox.object_id().to_string(); - let stream = - openshell_core::net::connect_tcp_nodelay_best_effort(("127.0.0.1", local_proxy_port)) - .await - .map_err(|e| Status::internal(format!("failed to connect to ssh proxy: {e}")))?; + // Cursors 1,2,3; client already saw through 3. + seed_log_lines(&state, &id, 3); - let config = Arc::new(exec_ssh_client_config()); - let remote_sshid = Arc::new(std::sync::Mutex::new(None)); - let handler = SandboxSshClientHandler { - remote_sshid: remote_sshid.clone(), - }; - let mut client = russh::client::connect_stream(config, stream, handler) + let response = handle_watch_sandbox( + &state, + authed_request(WatchSandboxRequest { + sandbox: sandbox.object_name().to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), + follow_logs: true, + resume_after_cursor: cursor_token(&state, &id, 3), + ..Default::default() + }), + ) .await - .map_err(|e| Status::internal(format!("failed to establish ssh transport: {e}")))?; + .unwrap(); - match client - .authenticate_none("sandbox") - .await - .map_err(|e| Status::internal(format!("failed to authenticate ssh session: {e}")))? - { - AuthResult::Success => {} - AuthResult::Failure { .. } => { - return Err(Status::permission_denied( - "ssh authentication rejected by sandbox", - )); - } + let mut stream = response.into_inner(); + let snap = stream.next().await.unwrap().unwrap(); + assert!(snap.cursor.is_empty()); + + // No resumable events remain; the live loop yields nothing promptly. + let next = tokio::time::timeout(std::time::Duration::from_millis(200), stream.next()).await; + assert!( + next.is_err(), + "expected no further events after resume at latest cursor, got {next:?}" + ); } - let mut channel = client - .channel_open_session() + #[tokio::test] + async fn resume_from_trimmed_cursor_terminates_out_of_range() { + use tokio_stream::StreamExt as _; + + let state = test_server_state().await; + let sandbox = test_sandbox("gap", Vec::new()); + state.store.put_message(&sandbox).await.unwrap(); + let id = sandbox.object_id().to_string(); + + // Exceed the 2000-line tail so the earliest cursors are trimmed. + seed_log_lines(&state, &id, 2005); + + let response = handle_watch_sandbox( + &state, + authed_request(WatchSandboxRequest { + sandbox: sandbox.object_name().to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), + follow_logs: true, + // Seq 2 was trimmed; this is an unrecoverable gap. + resume_after_cursor: cursor_token(&state, &id, 2), + ..Default::default() + }), + ) .await - .map_err(|e| Status::internal(format!("failed to open ssh channel: {e}")))?; + .unwrap(); - if request_tty { - channel - .request_pty(false, "xterm-256color", cols, rows, 0, 0, &[]) - .await - .map_err(|e| Status::internal(format!("failed to allocate PTY: {e}")))?; - } + let mut stream = response.into_inner(); + // Snapshot still arrives first (fresh state), then the terminal gap status. + let snap = stream.next().await.unwrap().unwrap(); + assert!(snap.cursor.is_empty()); - if no_shell_login { - let banner = remote_sshid.lock().unwrap().clone().unwrap_or_default(); - if !supervisor_supports_no_login_shell(&banner) { - return Err(Status::failed_precondition( - "sandbox supervisor is too old to honor --no-login-shell; recreate the sandbox on a current gateway", - )); - } - channel - .set_env(false, NO_LOGIN_SHELL_ENV.0, NO_LOGIN_SHELL_ENV.1) + let err = stream + .next() .await - .map_err(|e| Status::internal(format!("failed to set login-shell env: {e}")))?; + .unwrap() + .expect_err("trimmed cursor must terminate the stream"); + assert_eq!(err.code(), tonic::Code::OutOfRange, "{err:?}"); + assert!( + err.message().contains('2'), + "gap status should report the requested cursor: {}", + err.message() + ); + + // Stream ends after the terminal status. + assert!(stream.next().await.is_none()); } - channel - .exec(true, command.as_bytes()) - .await - .map_err(|e| Status::internal(format!("failed to execute command over ssh: {e}")))?; + /// The guard behind the producer's post-replay epoch re-check. + /// + /// Validation and the two `tail_after` reads take their locks separately, so + /// a teardown plus a republish can swap the space in between and leave the + /// reads applying an old seq to a replacement's buffers -- `tail_after` only + /// compares numbers, so it reports no gap while skipping every replacement + /// event at or below that seq. The producer re-checks the epoch once both + /// tails are in hand and before emitting anything; this pins what that check + /// must answer. + /// + /// The interleaving itself is not reachable from a test: the producer runs + /// validation, both reads, and the re-check with no await in between, so + /// there is nothing to suspend it on. + #[tokio::test] + async fn cursor_space_is_rejects_a_replacement_space() { + let state = test_server_state().await; + let sandbox = test_sandbox("respace", Vec::new()); + state.store.put_message(&sandbox).await.unwrap(); + let id = sandbox.object_id().to_string(); - if !stdin_payload.is_empty() { - channel - .data(std::io::Cursor::new(stdin_payload)) - .await - .map_err(|e| Status::internal(format!("failed to send ssh stdin payload: {e}")))?; - } + seed_log_lines(&state, &id, 1); + let original = state.tracing_log_bus.cursor_space(&id).unwrap().epoch; + assert!(cursor_space_is(&state, &id, original)); - channel - .eof() - .await - .map_err(|e| Status::internal(format!("failed to close ssh stdin: {e}")))?; + // Teardown alone leaves no space to point into. + state.tracing_log_bus.remove(&id); + assert!(state.tracing_log_bus.cursor_space(&id).is_none()); + assert!(!cursor_space_is(&state, &id, original)); - let mut exit_code: Option = None; - let mut close_seen = false; - loop { - // Bound the post-ExitStatus wait against a lost Close. - let msg = if exit_code.is_some() { - match tokio::time::timeout(EXEC_POST_EXIT_CLOSE_TIMEOUT, channel.wait()).await { - Ok(Some(msg)) => msg, - Ok(None) | Err(_) => break, - } - } else { - match channel.wait().await { - Some(msg) => msg, - None => break, - } - }; - match msg { - ChannelMsg::Data { data } => { - let _ = tx - .send(Ok(ExecSandboxEvent { - payload: Some(openshell_core::proto::exec_sandbox_event::Payload::Stdout( - ExecSandboxStdout { - data: data.to_vec(), - }, - )), - })) - .await; - } - ChannelMsg::ExtendedData { data, .. } => { - let _ = tx - .send(Ok(ExecSandboxEvent { - payload: Some(openshell_core::proto::exec_sandbox_event::Payload::Stderr( - ExecSandboxStderr { - data: data.to_vec(), - }, - )), - })) - .await; - } - ChannelMsg::ExitStatus { exit_status } => { - let converted = i32::try_from(exit_status).unwrap_or(i32::MAX); - exit_code = Some(converted); - } - ChannelMsg::Close => { - close_seen = true; - break; - } - _ => {} - } + // The republish installs a replacement renumbered from 1. Its seqs + // overlap the retired space's, so only the epoch separates them. + seed_log_lines(&state, &id, 1); + let replacement = state.tracing_log_bus.cursor_space(&id).unwrap(); + assert_ne!(replacement.epoch, original); + assert_eq!(replacement.highest_seq, 1); + assert!(!cursor_space_is(&state, &id, original)); + assert!(cursor_space_is(&state, &id, replacement.epoch)); } - let _ = channel.close().await; - let _ = client - .disconnect(russh::Disconnect::ByApplication, "exec complete", "en") - .await; - - exec_loop_result(exit_code, close_seen) -} + #[tokio::test] + async fn resume_from_reset_cursor_space_terminates_out_of_range() { + use tokio_stream::StreamExt as _; -// --------------------------------------------------------------------------- -// Tests -// --------------------------------------------------------------------------- + let state = test_server_state().await; + let sandbox = test_sandbox("reset", Vec::new()); + state.store.put_message(&sandbox).await.unwrap(); + let id = sandbox.object_id().to_string(); -#[cfg(test)] -mod tests { - use super::*; - use crate::auth::audit::test_support::{ - assert_authentication_failure, assert_boundary_finding, assert_logon, assert_origin, - assert_redacted, audited, - }; - use crate::compute::NoopTestDriver; + // The reported repro. Before cursors carried an epoch, a bare number + // was all the server had: 2 <= 3 passed the old "is this plausible?" + // bound, the tail replayed only seq 3, and the new space's seqs 1 and 2 + // -- real, unseen events -- were silently swallowed as duplicates. + seed_log_lines(&state, &id, 2); + let retired_cursor = cursor_token(&state, &id, 2); - #[test] - fn exec_requires_ssh_channel_close_after_exit_status() { - assert_eq!(exec_loop_result(Some(0), true).unwrap(), 0); - assert!(exec_loop_result(Some(0), false).is_err()); - assert!(exec_loop_result(None, true).is_err()); - } - use crate::grpc::test_support::{ - authed_request, test_server_state, test_server_state_with_compute_driver, - test_server_state_with_driver, - }; - use openshell_core::proto::datamodel::v1::ObjectMeta; - use openshell_core::proto::{ - GpuResourceRequirements, SandboxServiceExposure, ServiceAuthorizationMode, ServiceEndpoint, - }; + // Teardown retires the space; the next publish starts over at seq 1, + // indistinguishable by number from the client's view of a restart. + state.tracing_log_bus.remove(&id); + seed_log_lines(&state, &id, 3); - #[cfg(not(feature = "experimental"))] - /// A test state whose compute driver records provisioning calls. - async fn test_server_state_with_fake_driver() -> ( - Arc, - Arc, - ) { - let mut state = test_server_state().await; - let driver = Arc::new( - crate::test_support::FakeComputeDriver::new().with_capabilities( - openshell_core::proto::compute::v1::GetCapabilitiesResponse { - driver_name: "test".to_string(), - default_image: "test/image:latest".to_string(), - resource_admission_policy: - openshell_core::resource_admission::DriverAdmissionConfig::default() - .acknowledgement(), - extension: Some(openshell_core::extension_protocol::extension_metadata( - openshell_core::extension_protocol::ExtensionFamily::Compute, - "test/fake", - "test", - [], - )), - ..Default::default() - }, - ), - ); - let compute = crate::compute::ComputeRuntime::from_driver( - "test".to_string(), - driver.clone(), - None, - state.store.clone(), - crate::sandbox_index::SandboxIndex::new(), - crate::sandbox_watch::SandboxWatchBus::new(), - crate::tracing_bus::TracingLogBus::new(), - Arc::new(crate::supervisor_session::SupervisorSessionRegistry::new()), + let response = handle_watch_sandbox( + &state, + authed_request(WatchSandboxRequest { + sandbox: sandbox.object_name().to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), + follow_logs: true, + resume_after_cursor: retired_cursor, + ..Default::default() + }), ) .await .unwrap(); - Arc::get_mut(&mut state).unwrap().compute = compute; - driver.clear_calls(); - (state, driver) - } - #[cfg(not(feature = "experimental"))] - fn create_request_with_policy( - name: &str, - policy: openshell_core::proto::SandboxPolicy, - ) -> Request { - authed_request(CreateSandboxRequest { - workspace_scope: Some(openshell_core::proto::workspace_selector("default")), - name: name.to_string(), - spec: Some(SandboxSpec { - policy: Some(policy), - ..Default::default() - }), - ..Default::default() - }) - } + let mut stream = response.into_inner(); + let snap = stream.next().await.unwrap().unwrap(); + assert!(snap.cursor.is_empty()); - /// Stores a stopped sandbox whose spec holds a Cedar policy, as a - /// Cedar-enabled gateway with a supervisor-enforced driver created it. - #[cfg(not(feature = "experimental"))] - async fn put_stopped_cedar_sandbox(state: &ServerState, name: &str) { - let mut sandbox = test_sandbox(name, Vec::new()); - sandbox.spec.as_mut().unwrap().policy = Some(crate::grpc::test_support::cedar_policy()); - sandbox.set_phase(SandboxPhase::Stopped as i32); - state.store.put_message(&sandbox).await.unwrap(); - } + let item = stream + .next() + .await + .unwrap() + .expect_err("a cursor from a retired space must terminate the stream"); + assert_eq!(item.code(), tonic::Code::OutOfRange, "{item:?}"); + assert!( + item.message().contains("empty resume_after_cursor"), + "status must tell the client to restart without a cursor, not retry: {}", + item.message() + ); - #[cfg(not(feature = "experimental"))] - fn start_request(name: &str) -> Request { - authed_request(StartSandboxRequest { - name: name.to_string(), - workspace_scope: Some(openshell_core::proto::workspace_selector("default")), - ..Default::default() - }) + // Nothing from the new space may be delivered before the error: a + // partial stream would read as "here is everything after your cursor". + assert!(stream.next().await.is_none()); } - #[cfg(not(feature = "experimental"))] #[tokio::test] - async fn create_rejects_cedar_without_cedar_support() { - let (state, driver) = test_server_state_with_fake_driver().await; - let error = handle_create_sandbox( + async fn resume_from_reset_cursor_space_rejected_when_new_space_is_shorter() { + use tokio_stream::StreamExt as _; + + let state = test_server_state().await; + let sandbox = test_sandbox("reset-short", Vec::new()); + state.store.put_message(&sandbox).await.unwrap(); + let id = sandbox.object_id().to_string(); + + // The shape the old numeric bound did catch (5 > 2), kept so it keeps + // passing -- but now it fails for the reason that generalizes. + seed_log_lines(&state, &id, 5); + let retired_cursor = cursor_token(&state, &id, 5); + state.tracing_log_bus.remove(&id); + seed_log_lines(&state, &id, 2); + + let response = handle_watch_sandbox( &state, - create_request_with_policy("cedar", crate::grpc::test_support::cedar_policy()), - ) - .await - .expect_err("Cedar is unsupported"); - assert_eq!(error.code(), tonic::Code::FailedPrecondition, "{error:?}"); - assert!(error.message().contains("without Cedar"), "{error:?}"); - assert!(driver.calls().is_empty(), "{:?}", driver.calls()); + authed_request(WatchSandboxRequest { + sandbox: sandbox.object_name().to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), + follow_logs: true, + resume_after_cursor: retired_cursor, + ..Default::default() + }), + ) + .await + .unwrap(); + + let mut stream = response.into_inner(); + assert!(stream.next().await.unwrap().unwrap().cursor.is_empty()); + let err = stream.next().await.unwrap().expect_err("out of range"); + assert_eq!(err.code(), tonic::Code::OutOfRange, "{err:?}"); + assert!(stream.next().await.is_none()); } - #[cfg(not(feature = "experimental"))] #[tokio::test] - async fn start_rejects_a_stored_cedar_sandbox_without_cedar_support() { - let (state, driver) = test_server_state_with_fake_driver().await; - put_stopped_cedar_sandbox(&state, "stored-cedar").await; + async fn resume_from_reset_cursor_space_rejected_when_seq_is_within_new_range() { + use tokio_stream::StreamExt as _; - let error = handle_start_sandbox(&state, start_request("stored-cedar")) - .await - .expect_err("Cedar is unsupported"); - assert_eq!(error.code(), tonic::Code::FailedPrecondition, "{error:?}"); - assert!(error.message().contains("without Cedar"), "{error:?}"); - assert!(driver.calls().is_empty(), "{:?}", driver.calls()); - } + let state = test_server_state().await; + let sandbox = test_sandbox("reset-within", Vec::new()); + state.store.put_message(&sandbox).await.unwrap(); + let id = sandbox.object_id().to_string(); - /// Resuming starts the workload again, so it applies the start checks. - #[cfg(not(feature = "experimental"))] - #[tokio::test] - async fn resume_rejects_a_stored_cedar_sandbox_without_cedar_support() { - let (state, driver) = test_server_state_with_fake_driver().await; - put_stopped_cedar_sandbox(&state, "stored-cedar").await; + // Seq 1 sits comfortably inside the new space's 1..=3, so every numeric + // bound accepts it. Only the epoch distinguishes the two spaces. This is + // the assertion the pre-fix design structurally could not make. + seed_log_lines(&state, &id, 3); + let retired_cursor = cursor_token(&state, &id, 1); + state.tracing_log_bus.remove(&id); + seed_log_lines(&state, &id, 3); - let error = handle_resume_sandbox( + let response = handle_watch_sandbox( &state, - authed_request(ResumeSandboxRequest { - name: "stored-cedar".to_string(), + authed_request(WatchSandboxRequest { + sandbox: sandbox.object_name().to_string(), workspace_scope: Some(openshell_core::proto::workspace_selector("default")), + follow_logs: true, + resume_after_cursor: retired_cursor, ..Default::default() }), ) .await - .expect_err("Cedar is unsupported"); - assert_eq!(error.code(), tonic::Code::FailedPrecondition, "{error:?}"); - assert!(error.message().contains("without Cedar"), "{error:?}"); - assert!(driver.calls().is_empty(), "{:?}", driver.calls()); + .unwrap(); + + let mut stream = response.into_inner(); + assert!(stream.next().await.unwrap().unwrap().cursor.is_empty()); + let err = stream.next().await.unwrap().expect_err("out of range"); + assert_eq!(err.code(), tonic::Code::OutOfRange, "{err:?}"); + assert!(stream.next().await.is_none()); } #[tokio::test] - async fn missing_launch_signer_precedes_driver_validation_and_preserves_staged_archive() { - let directory = tempfile::tempdir().unwrap(); - let mut state = test_server_state().await; - let mut metadata = openshell_core::extension_protocol::extension_metadata( - openshell_core::extension_protocol::ExtensionFamily::Compute, - "test/launch-authentication", - "test", - [], - ); - metadata - .required_capabilities - .push(openshell_core::extension_protocol::COMPUTE_LAUNCH_AUTHENTICATION.to_string()); - let admission = openshell_core::resource_admission::DriverAdmissionConfig { - allow_driver_config: true, - ..Default::default() - }; - let driver = Arc::new( - crate::test_support::FakeComputeDriver::new().with_capabilities( - openshell_core::proto::compute::v1::GetCapabilitiesResponse { - driver_name: "test".to_string(), - default_image: "test/image:latest".to_string(), - rootfs_tar_staging_dir: directory.path().to_string_lossy().into_owned(), - rootfs_tar_max_bytes: 1024, - resource_admission_policy: admission.acknowledgement(), - extension: Some(metadata), - ..Default::default() - }, - ), - ); - let compute = crate::compute::ComputeRuntime::from_driver( - "test".to_string(), - driver.clone(), - None, - state.store.clone(), - crate::sandbox_index::SandboxIndex::new(), - crate::sandbox_watch::SandboxWatchBus::new(), - crate::tracing_bus::TracingLogBus::new(), - Arc::new(crate::supervisor_session::SupervisorSessionRegistry::new()), - ) - .await - .unwrap() - .with_admission_policy(admission) - .unwrap(); - Arc::get_mut(&mut state).unwrap().compute = compute; - let staging = state.compute.rootfs_tar_staging(); - let slot = staging - .begin("default", "dev-user", "rootfs.tar", 7) - .unwrap(); - std::fs::write(&slot.upload_path, b"archive").unwrap(); - let driver_config = Struct { - fields: std::iter::once(( - "test".to_string(), - Value { - kind: Some(Kind::StructValue(Struct { - fields: std::iter::once(( - crate::compute::rootfs_tar::STAGING_TOKEN_FIELD.to_string(), - Value { - kind: Some(Kind::StringValue(slot.token.clone())), - }, - )) - .collect(), - })), - }, - )) - .collect(), - }; - driver.clear_calls(); - let error = handle_create_sandbox( + async fn resume_after_remove_without_republish_terminates_out_of_range() { + use tokio_stream::StreamExt as _; + + let state = test_server_state().await; + let sandbox = test_sandbox("reset-empty", Vec::new()); + state.store.put_message(&sandbox).await.unwrap(); + let id = sandbox.object_id().to_string(); + + // No space at all: nothing has been published since teardown. The buses + // look merely empty, so `tail_after` reports no gap -- "caught up" would + // be the wrong reading, because the client's events are gone. + seed_log_lines(&state, &id, 3); + let retired_cursor = cursor_token(&state, &id, 3); + state.tracing_log_bus.remove(&id); + + let response = handle_watch_sandbox( &state, - authed_request(CreateSandboxRequest { - name: "missing-signer".to_string(), - spec: Some(SandboxSpec { - template: Some(SandboxTemplate { - driver_config: Some(driver_config), - ..Default::default() - }), - ..Default::default() - }), - workspace_scope: Some(openshell_core::proto::workspace_selector( - "default".to_string(), - )), + authed_request(WatchSandboxRequest { + sandbox: sandbox.object_name().to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), + follow_logs: true, + resume_after_cursor: retired_cursor, ..Default::default() }), ) .await - .unwrap_err(); - assert_eq!(error.code(), tonic::Code::FailedPrecondition); - assert!(error.message().contains("sandbox launch signing")); - assert!( - driver.calls().is_empty(), - "driver validation must not precede signing preflight" - ); - assert_eq!( - staging.peek(&slot.token).unwrap(), - std::path::PathBuf::from(&slot.upload_path) - ); - assert_eq!(std::fs::read(&slot.upload_path).unwrap(), b"archive"); - assert!( - state - .store - .get_message_by_name::("default", "missing-signer") - .await - .unwrap() - .is_none() - ); - } - - // ---- shell_escape ---- + .unwrap(); - #[test] - fn pty_dimensions_default_zero_values_without_overwriting_explicit_values() { - assert_eq!(pty_dimensions(0, 0), (80, 24)); - assert_eq!(pty_dimensions(120, 40), (120, 40)); - assert_eq!(pty_dimensions(0, 40), (80, 40)); + let mut stream = response.into_inner(); + assert!(stream.next().await.unwrap().unwrap().cursor.is_empty()); + let err = stream.next().await.unwrap().expect_err("out of range"); + assert_eq!(err.code(), tonic::Code::OutOfRange, "{err:?}"); + assert!(stream.next().await.is_none()); } - #[test] - fn watch_terminal_phases_include_command_results_and_errors() { - for phase in [ - SandboxPhase::Ready, - SandboxPhase::Completed, - SandboxPhase::Stopped, - SandboxPhase::Suspended, - SandboxPhase::Error, - ] { - assert!(is_watch_terminal(phase), "{phase:?} should stop the watch"); - } - for phase in [ - SandboxPhase::Provisioning, - SandboxPhase::Starting, - SandboxPhase::Stopping, - SandboxPhase::Suspending, - SandboxPhase::Deleting, - SandboxPhase::Unknown, - ] { - assert!( - !is_watch_terminal(phase), - "{phase:?} should keep the watch open" - ); - } - } + #[tokio::test] + async fn resume_with_cursor_from_another_sandbox_terminates_out_of_range() { + use tokio_stream::StreamExt as _; - #[test] - fn sandbox_create_telemetry_uses_resolved_template_gpu_request() { - let request = CreateSandboxRequest { - request_id: String::new(), - spec: Some(SandboxSpec { - providers: vec!["github".to_string()], - policy: Some(openshell_core::proto::SandboxPolicy::default()), - ..SandboxSpec::default() - }), - workload_template: "gpu-kata".to_string(), - workspace_scope: Some(openshell_core::proto::workspace_selector( - "default".to_string(), - )), - ..CreateSandboxRequest::default() - }; - let created = Sandbox { - spec: Some(SandboxSpec { - providers: vec!["github".to_string()], - policy: Some(openshell_core::proto::SandboxPolicy::default()), - resource_requirements: Some(ResourceRequirements { - gpu: Some(GpuResourceRequirements { count: Some(1) }), - }), - ..SandboxSpec::default() - }), - created_from_workload_template: Some(SandboxWorkloadTemplateProvenance { - name: "gpu-kata".to_string(), - resource_version: "7".to_string(), + let state = test_server_state().await; + let a = test_sandbox("epoch-a", Vec::new()); + let b = test_sandbox("epoch-b", Vec::new()); + state.store.put_message(&a).await.unwrap(); + state.store.put_message(&b).await.unwrap(); + let a_id = a.object_id().to_string(); + let b_id = b.object_id().to_string(); + + // Epochs are per sandbox, not per process. A token valid for A must not + // address B's space, even though both are on seq 1..=3 right now. + seed_log_lines(&state, &a_id, 3); + seed_log_lines(&state, &b_id, 3); + let a_cursor = cursor_token(&state, &a_id, 1); + + let response = handle_watch_sandbox( + &state, + authed_request(WatchSandboxRequest { + sandbox: b.object_name().to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), + follow_logs: true, + resume_after_cursor: a_cursor, + ..Default::default() }), - ..Sandbox::default() - }; + ) + .await + .unwrap(); - assert_eq!( - sandbox_create_telemetry_attrs(&request, Some(&created)), - SandboxCreateTelemetryAttrs { - requested_gpu: true, - provider_count: 1, - has_custom_policy: true, - template_source: SandboxTemplateSource::WorkloadTemplate, - } - ); + let mut stream = response.into_inner(); + assert!(stream.next().await.unwrap().unwrap().cursor.is_empty()); + let err = stream.next().await.unwrap().expect_err("out of range"); + assert_eq!(err.code(), tonic::Code::OutOfRange, "{err:?}"); + assert!(stream.next().await.is_none()); } - #[test] - fn sandbox_create_telemetry_falls_back_to_request_for_unresolved_template() { - let request = CreateSandboxRequest { - request_id: String::new(), - spec: Some(SandboxSpec { - providers: vec!["github".to_string()], - ..SandboxSpec::default() + #[tokio::test] + async fn resume_with_cursor_ahead_of_the_space_terminates_out_of_range() { + use tokio_stream::StreamExt as _; + + let state = test_server_state().await; + let sandbox = test_sandbox("ahead", Vec::new()); + state.store.put_message(&sandbox).await.unwrap(); + let id = sandbox.object_id().to_string(); + + seed_log_lines(&state, &id, 2); + // Right epoch, but a seq this space has never issued: only a fabricated + // token gets here. Accepting it would pin the cutoff above every future + // event and stall the stream silently. + let ahead = cursor_token(&state, &id, 99); + + let response = handle_watch_sandbox( + &state, + authed_request(WatchSandboxRequest { + sandbox: sandbox.object_name().to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), + follow_logs: true, + resume_after_cursor: ahead, + ..Default::default() }), - workload_template: "missing-template".to_string(), - workspace_scope: Some(openshell_core::proto::workspace_selector( - "default".to_string(), - )), - ..CreateSandboxRequest::default() - }; + ) + .await + .unwrap(); - assert_eq!( - sandbox_create_telemetry_attrs(&request, None), - SandboxCreateTelemetryAttrs { - requested_gpu: false, - provider_count: 1, - has_custom_policy: false, - template_source: SandboxTemplateSource::WorkloadTemplate, - } - ); + let mut stream = response.into_inner(); + assert!(stream.next().await.unwrap().unwrap().cursor.is_empty()); + let err = stream.next().await.unwrap().expect_err("out of range"); + assert_eq!(err.code(), tonic::Code::OutOfRange, "{err:?}"); + assert!(stream.next().await.is_none()); } - #[test] - fn shell_escape_safe_chars_pass_through() { - assert_eq!(shell_escape("ls").unwrap(), "ls"); - assert_eq!(shell_escape("/usr/bin/python").unwrap(), "/usr/bin/python"); - assert_eq!(shell_escape("file.txt").unwrap(), "file.txt"); - assert_eq!(shell_escape("my-cmd_v2").unwrap(), "my-cmd_v2"); - } + #[tokio::test] + async fn resume_with_malformed_cursor_rejects_invalid_argument() { + let state = test_server_state().await; + let sandbox = test_sandbox("malformed", Vec::new()); + state.store.put_message(&sandbox).await.unwrap(); + let id = sandbox.object_id().to_string(); - #[test] - fn shell_escape_empty_string() { - assert_eq!(shell_escape("").unwrap(), "''"); - } + seed_log_lines(&state, &id, 3); - #[test] - fn shell_escape_wraps_unsafe_chars() { - assert_eq!(shell_escape("hello world").unwrap(), "'hello world'"); - assert_eq!(shell_escape("$(id)").unwrap(), "'$(id)'"); - assert_eq!(shell_escape("; rm -rf /").unwrap(), "'; rm -rf /'"); + // Input validation, so it fails the RPC before any stream exists rather + // than arriving as the first item of an apparently-healthy stream. + for raw in ["5", "v1:not-a-uuid:0", &foreign_cursor(1)[..40]] { + let err = handle_watch_sandbox( + &state, + authed_request(WatchSandboxRequest { + sandbox: sandbox.object_name().to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), + follow_logs: true, + resume_after_cursor: raw.to_string(), + ..Default::default() + }), + ) + .await + .expect_err("malformed cursor must fail the call"); + assert_eq!(err.code(), tonic::Code::InvalidArgument, "{raw:?}: {err:?}"); + assert!( + !err.message().contains(raw), + "status must not echo the client token: {}", + err.message() + ); + } } - #[test] - fn shell_escape_handles_single_quotes() { - assert_eq!(shell_escape("it's").unwrap(), "'it'\"'\"'s'"); - } + #[tokio::test] + async fn resume_with_foreign_epoch_terminates_out_of_range() { + use tokio_stream::StreamExt as _; - #[test] - fn shell_escape_rejects_null_bytes() { - assert!(shell_escape("hello\x00world").is_err()); - } + let state = test_server_state().await; + let sandbox = test_sandbox("foreign", Vec::new()); + state.store.put_message(&sandbox).await.unwrap(); + let id = sandbox.object_id().to_string(); - #[test] - fn shell_escape_allows_newlines() { - assert!(shell_escape("line1\nline2").is_ok()); - assert!(shell_escape("line1\rline2").is_ok()); - assert!(shell_escape("line1\r\nline2").is_ok()); - } + seed_log_lines(&state, &id, 3); - #[test] - fn shell_escape_preserves_newlines_in_single_quotes() { - assert_eq!(shell_escape("line1\nline2").unwrap(), "'line1\nline2'"); - assert_eq!( - shell_escape("def f():\n return 1").unwrap(), - "'def f():\n return 1'" - ); - assert_eq!(shell_escape("line1\r\nline2").unwrap(), "'line1\r\nline2'"); + // Well-formed, so it clears input validation, but from an epoch this + // gateway never minted -- the shape a reconnect to another replica + // takes. + let response = handle_watch_sandbox( + &state, + authed_request(WatchSandboxRequest { + sandbox: sandbox.object_name().to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), + follow_logs: true, + resume_after_cursor: foreign_cursor(1), + ..Default::default() + }), + ) + .await + .unwrap(); + + let mut stream = response.into_inner(); + assert!(stream.next().await.unwrap().unwrap().cursor.is_empty()); + let err = stream.next().await.unwrap().expect_err("out of range"); + assert_eq!(err.code(), tonic::Code::OutOfRange, "{err:?}"); + assert!(stream.next().await.is_none()); } - // ---- build_remote_exec_command ---- + #[tokio::test] + async fn watch_delivers_each_event_once_during_init_race() { + use tokio_stream::StreamExt as _; - #[test] - fn build_remote_exec_command_basic() { - use openshell_core::proto::ExecSandboxRequest; - let req = ExecSandboxRequest { - sandbox: "test".to_string(), - workspace_scope: None, - command: vec!["ls".to_string(), "-la".to_string()], - ..Default::default() - }; - assert_eq!(build_remote_exec_command(&req).unwrap(), "ls -la"); - } + let state = test_server_state().await; + let sandbox = test_sandbox("race", Vec::new()); + state.store.put_message(&sandbox).await.unwrap(); + let id = sandbox.object_id().to_string(); - #[test] - fn build_remote_exec_command_with_env_and_workdir() { - use openshell_core::proto::ExecSandboxRequest; - let req = ExecSandboxRequest { - sandbox: "test".to_string(), - workspace_scope: None, - command: vec![ - "python".to_string(), - "-c".to_string(), - "print('ok')".to_string(), - ], - environment: std::iter::once(("HOME".to_string(), "/home/user".to_string())).collect(), - workdir: "/workspace".to_string(), - ..Default::default() - }; - let cmd = build_remote_exec_command(&req).unwrap(); - assert!(cmd.starts_with("cd /workspace && ")); - assert!(cmd.contains("HOME=/home/user")); - assert!(cmd.contains("'print('\"'\"'ok'\"'\"')'")); - } + // Seed events that land in the tail before the watch subscribes. + seed_log_lines(&state, &id, 5); + + let response = handle_watch_sandbox( + &state, + authed_request(WatchSandboxRequest { + sandbox: sandbox.object_name().to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), + follow_logs: true, + ..Default::default() + }), + ) + .await + .unwrap(); + + // Publish more concurrently with producer initialization. Some of these + // can land after the broadcast subscription but before the tail read, + // putting them in both replay and the live receiver. + for i in 5..15 { + state + .tracing_log_bus + .publish_external(openshell_core::proto::SandboxLogLine { + sandbox_id: id.clone(), + event_time: openshell_core::time::timestamp_from_millis(i64::from(i)).ok(), + level: "INFO".to_string(), + target: "test".to_string(), + message: format!("line {i}"), + source: "gateway".to_string(), + ..Default::default() + }); + } + + let mut stream = response.into_inner(); + let mut cursors = Vec::new(); + while let Ok(Some(item)) = + tokio::time::timeout(std::time::Duration::from_millis(200), stream.next()).await + { + let evt = item.unwrap(); + if !evt.cursor.is_empty() { + cursors.push(seq_of(&evt)); + } + } - #[test] - fn build_remote_exec_command_rejects_null_bytes_in_args() { - use openshell_core::proto::ExecSandboxRequest; - let req = ExecSandboxRequest { - sandbox: "test".to_string(), - workspace_scope: None, - command: vec!["echo".to_string(), "hello\x00world".to_string()], - ..Default::default() - }; - assert!(build_remote_exec_command(&req).is_err()); + // Every delivered cursor is unique (no double delivery) and monotonically + // increasing (replay ordered, then live in cursor order for one source). + let mut sorted = cursors.clone(); + sorted.sort_unstable(); + sorted.dedup(); + assert_eq!( + sorted.len(), + cursors.len(), + "duplicate cursors delivered: {cursors:?}" + ); + assert_eq!( + cursors, sorted, + "cursors not delivered in order: {cursors:?}" + ); } - #[test] - fn build_remote_exec_command_rejects_newlines_in_workdir() { - use openshell_core::proto::ExecSandboxRequest; - let req = ExecSandboxRequest { - sandbox: "test".to_string(), - workspace_scope: None, - command: vec!["ls".to_string()], - workdir: "/tmp\nmalicious".to_string(), - ..Default::default() - }; - // Validation layer rejects newlines in workdir - assert!(validate_exec_request_fields(&req).is_err()); - } + #[tokio::test] + async fn delete_handler_ends_telemetry_for_the_resolved_sandbox_id() { + 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(); + state.store.put_message(&original).await.unwrap(); - #[test] - fn build_remote_exec_command_accepts_multiline_script() { - use openshell_core::proto::ExecSandboxRequest; - let req = ExecSandboxRequest { - sandbox: "test".to_string(), - workspace_scope: None, - command: vec![ - "python3".to_string(), - "-c".to_string(), - "def f():\n return 1\nprint(f())".to_string(), - ], - ..Default::default() - }; - let cmd = build_remote_exec_command(&req).unwrap(); - assert!(cmd.starts_with("python3 -c ")); - assert!(cmd.contains("'def f():\n return 1\nprint(f())'")); - } + // Hold the global guard so the handler can resolve the original ID and + // acquire its delete gate, but cannot yet take the sandbox's local + // lifecycle lock (shared global key) to revalidate or mutate it. + let global_guard = state + .compute + .mutation_guard(MutationScope::Global) + .await + .unwrap(); + let delete_state = state.clone(); + 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(), + )), + }), + ) + .await + }); + tokio::time::timeout(std::time::Duration::from_secs(5), async { + while state.compute.lifecycle_gate_entry_count() == 0 { + tokio::time::sleep(std::time::Duration::from_millis(10)).await; + } + }) + .await + .expect("delete did not resolve and acquire the original sandbox gate"); - #[test] - fn build_remote_exec_command_multiline_with_single_quotes() { - use openshell_core::proto::ExecSandboxRequest; - let req = ExecSandboxRequest { - sandbox: "test".to_string(), - workspace_scope: None, - command: vec![ - "python3".to_string(), - "-c".to_string(), - "print('one')\r\nprint('two')".to_string(), - ], - ..Default::default() - }; - let cmd = build_remote_exec_command(&req).unwrap(); - assert!(cmd.starts_with("python3 -c ")); + state + .store + .delete(Sandbox::object_type(), original.object_id()) + .await + .unwrap(); + 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(); + drop(global_guard); + + let response = delete.await.unwrap().unwrap().into_inner(); + assert_eq!( + response.outcome(), + openshell_core::proto::DeletionOutcome::Completed + ); assert!( - cmd.contains("'print('\"'\"'one'\"'\"')\r\nprint('\"'\"'two'\"'\"')'"), - "CR/LF with embedded single quotes must compose correctly: {cmd}" + state + .store + .get_message::(replacement.object_id()) + .await + .unwrap() + .is_some() + ); + assert_eq!( + state.telemetry.ended_sandbox_sessions(), + [original.object_id().to_string()] ); } - fn forward_init(target: tcp_forward_init::Target, token: &str) -> TcpForwardInit { - TcpForwardInit { - sandbox: "sbx".to_string(), - workspace: String::new(), - service_id: String::new(), - target: Some(target), - authorization_token: token.to_string(), - } - } + #[tokio::test] + async fn internal_delete_rejects_expected_identity_drift_before_mutation() { + let state = test_server_state().await; + let mut sandbox = test_sandbox("guarded-delete", Vec::new()); + sandbox.metadata.as_mut().unwrap().id = "sb-current".to_string(); + state.store.put_message(&sandbox).await.unwrap(); - fn loopback_tcp_target() -> tcp_forward_init::Target { - tcp_forward_init::Target::Tcp(TcpRelayTarget { - host: "127.0.0.1".to_string(), - port: 8080, - }) + let error = state + .compute + .delete_sandbox_with_preconditions( + "default", + "guarded-delete", + SandboxDeletePreconditions { + expected_sandbox_id: Some("sb-stale".to_string()), + expected_resource_version: None, + }, + ) + .await + .unwrap_err(); + + assert_eq!(error.code(), tonic::Code::Aborted); + assert!( + state + .store + .get_message::("sb-current") + .await + .unwrap() + .is_some() + ); } #[tokio::test] - async fn direct_ssh_requires_a_verified_user_with_ssh_scope() { - use crate::auth::principal::Principal; - let mut state = test_server_state().await; - Arc::get_mut(&mut state).unwrap().config.oidc = Some(serde_json::from_value( - serde_json::json!({ "issuer": "https://issuer.example", "audience": "test", "scopes_claim": "scope" }) - ).unwrap()); - let Principal::User(mut user) = forward_caller() else { - panic!("expected user") - }; - user.identity.scopes = vec!["sandbox:read".into()]; - assert!(!direct_ssh_available( - &state, - &Principal::User(user.clone()) - )); - user.identity.scopes.push("sandbox:write".into()); - for provider in [ - IdentityProvider::Oidc, - IdentityProvider::Mtls, - IdentityProvider::LocalDev, - ] { - user.identity.provider = provider; - assert_eq!( - direct_ssh_available(&state, &Principal::User(user.clone())), - provider != IdentityProvider::LocalDev - ); - } - assert!(!direct_ssh_available(&state, &Principal::Anonymous)); - assert!(!direct_ssh_available( - &state, - &crate::auth::principal::test_support::sandbox("sandbox-fwd") - )); - } + async fn internal_delete_rejects_resource_version_without_immutable_identity() { + let state = test_server_state().await; + let mut sandbox = test_sandbox("guarded-delete", Vec::new()); + sandbox.metadata.as_mut().unwrap().id = "sb-current".to_string(); + state.store.put_message(&sandbox).await.unwrap(); - #[test] - fn direct_ssh_rejects_missing_identity_and_any_session_token() { - for (id, token) in [ - ("", ""), - (" ", ""), - (" sandbox-fwd", ""), - ("sandbox-fwd", " "), - ("sandbox-fwd", "legacy-token"), - ] { - let init = forward_init( - tcp_forward_init::Target::DirectSshSandboxId(id.into()), - token, - ); - assert_eq!( - validate_tcp_forward_init(&init).unwrap_err().code(), - tonic::Code::InvalidArgument - ); - } + let error = state + .compute + .delete_sandbox_with_preconditions( + "default", + "guarded-delete", + SandboxDeletePreconditions { + expected_sandbox_id: None, + expected_resource_version: Some(17), + }, + ) + .await + .unwrap_err(); + + assert_eq!(error.code(), tonic::Code::InvalidArgument); + assert!( + state + .store + .get_message::("sb-current") + .await + .unwrap() + .is_some() + ); } - fn sandbox_connection_count(state: &ServerState, budget: RelayBudget, sandbox_id: &str) -> u32 { - budget - .counts(state) - .lock() + #[tokio::test] + async fn attach_sandbox_provider_persists_current_provider_list() { + let state = test_server_state().await; + state + .store + .put_message(&test_provider("work-github", "github")) + .await + .unwrap(); + state + .store + .put_message(&test_sandbox("work", Vec::new())) + .await + .unwrap(); + + let response = handle_attach_sandbox_provider( + &state, + authed_request(AttachSandboxProviderRequest { + request_id: String::new(), + sandbox: "work".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), + provider: "work-github".to_string(), + expected_resource_version: 0, + }), + ) + .await + .unwrap() + .into_inner(); + + assert!(response.attached); + let sandbox = state + .store + .get_message_by_name::("default", "work") + .await .unwrap() - .get(sandbox_id) - .copied() - .unwrap_or(0) + .unwrap(); + assert_eq!(sandbox.phase(), SandboxPhase::Ready as i32); + assert_eq!(sandbox.current_policy_version(), 7); + let spec = sandbox.spec.unwrap(); + assert_eq!(spec.providers, vec!["work-github"]); + assert_eq!(spec.log_level, "debug"); } #[tokio::test] - async fn tcp_forward_without_token_is_admitted_on_the_principal_alone() { + async fn attach_sandbox_provider_uses_configured_provider_profile_sources() { let state = test_server_state().await; - let sandbox = test_sandbox("fwd", Vec::new()); + state + .store + .put_message(&test_provider("work-github", "github")) + .await + .unwrap(); + state + .store + .put_message(&test_sandbox("work", Vec::new())) + .await + .unwrap(); - let guard = acquire_forward_connection_guard( + let response = handle_attach_sandbox_provider( &state, - &forward_caller(), - &forward_init(loopback_tcp_target(), ""), - &sandbox, + authed_request(AttachSandboxProviderRequest { + request_id: String::new(), + sandbox: "work".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), + provider: "work-github".to_string(), + expected_resource_version: 0, + }), ) .await - .expect("tcp forward without a session token"); + .expect("an imported github profile should resolve from the user source") + .into_inner(); - assert!( - guard.token.is_none(), - "no per-token accounting without a token" - ); - assert!(state.ssh_connections_by_token.lock().unwrap().is_empty()); - assert_eq!( - sandbox_connection_count(&state, RelayBudget::Service, sandbox.object_id()), - 1 - ); - drop(guard); + assert!(response.attached); + let sandbox = response.sandbox.expect("updated sandbox"); assert_eq!( - sandbox_connection_count(&state, RelayBudget::Service, sandbox.object_id()), - 0, - "dropping the guard releases the sandbox slot" + sandbox.spec.expect("sandbox spec").providers, + vec!["work-github"] ); } - const FORWARD_TCP_PATH: &str = "/openshell.v1.OpenShell/ForwardTcp"; + #[tokio::test] + async fn attach_sandbox_provider_is_idempotent_and_avoids_duplicates() { + let state = test_server_state().await; + state + .store + .put_message(&test_provider("work-github", "github")) + .await + .unwrap(); + state + .store + .put_message(&test_sandbox( + "work", + vec!["work-github".to_string(), "work-github".to_string()], + )) + .await + .unwrap(); - fn forward_caller() -> crate::auth::principal::Principal { - authed_request(()) - .extensions_mut() - .remove::() - .expect("dev principal") + let response = handle_attach_sandbox_provider( + &state, + authed_request(AttachSandboxProviderRequest { + request_id: String::new(), + sandbox: "work".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), + provider: "work-github".to_string(), + expected_resource_version: 0, + }), + ) + .await + .unwrap() + .into_inner(); + + assert!(!response.attached); + let providers = state + .store + .get_message_by_name::("default", "work") + .await + .unwrap() + .unwrap() + .spec + .unwrap() + .providers; + assert_eq!(providers, vec!["work-github"]); } - /// Acquire a forward slot inside a routed `ForwardTcp` request, returning - /// the result and the OCSF events it emitted. - async fn acquire_audited( - state: &Arc, - init: &TcpForwardInit, - sandbox: &Sandbox, - ) -> ( - Result, - Vec, - ) { - audited( - FORWARD_TCP_PATH, - acquire_forward_connection_guard(state, &forward_caller(), init, sandbox), + fn attach_request(sandbox: &str, provider: &str) -> Request { + authed_request(AttachSandboxProviderRequest { + request_id: String::new(), + sandbox: sandbox.to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), + provider: provider.to_string(), + expected_resource_version: 0, + }) + } + + #[tokio::test] + async fn attach_provider_does_not_wait_for_unrelated_sandbox_guard() { + let state = test_server_state().await; + state + .store + .put_message(&test_provider("work-github", "github")) + .await + .unwrap(); + state + .store + .put_message(&test_sandbox("work", Vec::new())) + .await + .unwrap(); + let unrelated = test_sandbox("unrelated", Vec::new()); + state.store.put_message(&unrelated).await.unwrap(); + let unrelated_guard = crate::persistence::lock_order::branch( + state + .compute + .mutation_guard(MutationScope::sandbox("default", unrelated.object_id())), ) .await - } + .unwrap(); - async fn store_ssh_session( - state: &ServerState, - token: &str, - sandbox_id: &str, - revoked: bool, - expires_at_ms: i64, - ) { - let session = SshSession { - metadata: Some(ObjectMeta { - id: token.to_string(), - name: format!("session-{token}"), - created_time: None, - labels: HashMap::new(), - resource_version: 0, - annotations: HashMap::new(), - workspace: "default".to_string(), - deletion_time: None, - }), - sandbox_id: sandbox_id.to_string(), - token: token.to_string(), - revoked, - expiration_time: openshell_core::time::optional_timestamp_from_legacy_millis( - expires_at_ms, - ) - .unwrap(), - }; - state.store.put_message(&session).await.unwrap(); + let response = tokio::time::timeout( + std::time::Duration::from_secs(5), + handle_attach_sandbox_provider(&state, attach_request("work", "work-github")), + ) + .await + .expect("attach should not wait for an unrelated sandbox mutation") + .expect("attach should succeed") + .into_inner(); + assert!(response.attached); + drop(unrelated_guard); } - /// Assert `events` is one SSH session token failure for `reason` that - /// never mentions `token`. - fn assert_ssh_token_failure(events: &[serde_json::Value], reason: &str, token: &str) { - assert_eq!(events.len(), 1, "{events:?}"); - let event = &events[0]; - assert_authentication_failure(event, FORWARD_TCP_PATH, reason); - assert_eq!(event["auth_protocol"], "ssh_session_token"); - assert_eq!(event["user"]["uid"], "dev-user"); - assert_origin(event); - if !token.is_empty() { - assert_redacted(event, token); - } + #[tokio::test] + async fn attach_provider_waits_for_workspace_guard() { + let state = test_server_state().await; + state + .store + .put_message(&test_provider("work-github", "github")) + .await + .unwrap(); + state + .store + .put_message(&test_sandbox("work", Vec::new())) + .await + .unwrap(); + let workspace_guard = state + .compute + .mutation_guard(MutationScope::Workspace("default")) + .await + .unwrap(); + + let task_state = state.clone(); + let mut attach = tokio::spawn(async move { + handle_attach_sandbox_provider(&task_state, attach_request("work", "work-github")).await + }); + assert!( + tokio::time::timeout(std::time::Duration::from_millis(100), &mut attach) + .await + .is_err(), + "attach should wait for a provider writer in its workspace" + ); + drop(workspace_guard); + + let response = tokio::time::timeout(std::time::Duration::from_secs(5), attach) + .await + .expect("attach should finish after the workspace guard is released") + .expect("join attach task") + .expect("attach should succeed") + .into_inner(); + assert!(response.attached); } #[tokio::test] - async fn ssh_forward_without_token_is_rejected() { + async fn detach_sandbox_provider_is_idempotent_and_removes_all_matches() { let state = test_server_state().await; - let sandbox = test_sandbox("fwd", Vec::new()); + state + .store + .put_message(&test_provider_with_credential_key( + "other", + "github", + "GITHUB_TOKEN", + )) + .await + .unwrap(); + state + .store + .put_message(&test_sandbox( + "work", + vec![ + "work-github".to_string(), + "other".to_string(), + "work-github".to_string(), + ], + )) + .await + .unwrap(); - let (result, events) = acquire_audited( + let response = handle_detach_sandbox_provider( &state, - &forward_init(tcp_forward_init::Target::Ssh(SshRelayTarget::default()), ""), - &sandbox, + authed_request(DetachSandboxProviderRequest { + request_id: String::new(), + sandbox: "work".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), + provider: "work-github".to_string(), + expected_resource_version: 0, + }), ) - .await; - let err = result - .err() - .expect("ssh targets keep requiring the session token"); - - assert_eq!(err.code(), tonic::Code::Unauthenticated); - assert_eq!( - err.message(), - "authorization_token is required for SSH targets" - ); - assert_eq!( - sandbox_connection_count(&state, RelayBudget::Ssh, sandbox.object_id()), - 0 - ); - assert_ssh_token_failure(&events, "missing_credential", ""); - } + .await + .unwrap() + .into_inner(); - #[tokio::test] - async fn tcp_forward_with_unknown_token_is_still_rejected() { - let state = test_server_state().await; - let sandbox = test_sandbox("fwd", Vec::new()); + assert!(response.detached); + let providers = state + .store + .get_message_by_name::("default", "work") + .await + .unwrap() + .unwrap() + .spec + .unwrap() + .providers; + assert_eq!(providers, vec!["other"]); - let (result, events) = acquire_audited( + let response = handle_detach_sandbox_provider( &state, - &forward_init(loopback_tcp_target(), "canary-ssh-token-unknown"), - &sandbox, + authed_request(DetachSandboxProviderRequest { + request_id: String::new(), + sandbox: "work".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), + provider: "work-github".to_string(), + expected_resource_version: 0, + }), ) - .await; - let err = result.err().expect("a supplied token is always validated"); - - assert_eq!(err.code(), tonic::Code::Unauthenticated); - assert_eq!(err.message(), "SSH session token not found"); - assert_eq!( - sandbox_connection_count(&state, RelayBudget::Service, sandbox.object_id()), - 0 - ); - assert_ssh_token_failure(&events, "invalid_credential", "canary-ssh-token-unknown"); + .await + .unwrap() + .into_inner(); + assert!(!response.detached); } #[tokio::test] - async fn rejected_ssh_session_tokens_name_their_reason() { + async fn detach_rejects_provider_referenced_by_policy_credential_binding() { let state = test_server_state().await; - let sandbox = test_sandbox("fwd", Vec::new()); - let future_ms = current_time_ms() + 60_000; - store_ssh_session( - &state, - "canary-ssh-token-revoked", - "sandbox-fwd", - true, - future_ms, - ) - .await; - store_ssh_session( - &state, - "canary-ssh-token-other", - "sandbox-other", - false, - future_ms, - ) - .await; - store_ssh_session( + state + .store + .put_message(&test_provider("work-gcp", "google-cloud")) + .await + .unwrap(); + + let mut sandbox = test_sandbox("work", vec!["work-gcp".to_string()]); + let policy = sandbox + .spec + .as_mut() + .and_then(|spec| spec.policy.as_mut()) + .unwrap(); + policy.network_policies.insert( + "gcp_storage".to_string(), + openshell_core::proto::NetworkPolicyRule { + name: "gcp_storage".to_string(), + endpoints: vec![openshell_core::proto::NetworkEndpoint { + host: "storage.googleapis.com".to_string(), + port: 443, + credential_binding: Some(openshell_core::proto::NetworkCredentialBinding { + provider: "work-gcp".to_string(), + }), + ..Default::default() + }], + ..Default::default() + }, + ); + state.store.put_message(&sandbox).await.unwrap(); + + let error = handle_detach_sandbox_provider( &state, - "canary-ssh-token-expired", - "sandbox-fwd", - false, - 1_000, + authed_request(DetachSandboxProviderRequest { + request_id: String::new(), + sandbox: "work".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), + provider: "work-gcp".to_string(), + expected_resource_version: 0, + }), ) - .await; - - for (token, message, reason) in [ - ( - "canary-ssh-token-revoked", - "SSH session token is not valid", - "invalid_credential", - ), - ( - "canary-ssh-token-other", - "SSH session token is not valid", - "audience_or_issuer_mismatch", - ), - ( - "canary-ssh-token-expired", - "SSH session token expired", - "expired_credential", - ), - ] { - let (result, events) = acquire_audited( - &state, - &forward_init( - tcp_forward_init::Target::Ssh(SshRelayTarget::default()), - token, - ), - &sandbox, - ) - .await; - let err = result.err().expect(token); + .await + .expect_err("a referenced provider must remain attached"); - assert_eq!(err.code(), tonic::Code::Unauthenticated, "{token}"); - assert_eq!(err.message(), message, "{token}"); - assert_ssh_token_failure(&events, reason, token); - } + assert_eq!(error.code(), tonic::Code::FailedPrecondition); + assert!(error.message().contains("not attached")); + let providers = state + .store + .get_message_by_name::("default", "work") + .await + .unwrap() + .unwrap() + .spec + .unwrap() + .providers; + assert_eq!(providers, vec!["work-gcp"]); } #[tokio::test] - async fn session_token_on_a_tcp_target_logs_on() { + async fn list_sandbox_providers_returns_attached_provider_records() { + use openshell_core::proto::CreateWorkspaceRequest; + let state = test_server_state().await; - let sandbox = test_sandbox("fwd", Vec::new()); - store_ssh_session(&state, "canary-ssh-token-tcp", "sandbox-fwd", false, 0).await; + state + .store + .put_message(&test_provider("work-github", "github")) + .await + .unwrap(); + state + .store + .put_message(&test_provider("work-gitlab", "gitlab")) + .await + .unwrap(); + state + .store + .put_message(&test_sandbox( + "work", + vec!["work-github".to_string(), "work-gitlab".to_string()], + )) + .await + .unwrap(); + state + .store + .put_message(&test_sandbox("other", vec!["work-github".to_string()])) + .await + .unwrap(); - let (result, events) = acquire_audited( + let first_page = handle_list_sandbox_providers( &state, - &forward_init(loopback_tcp_target(), "canary-ssh-token-tcp"), - &sandbox, + authed_request(ListSandboxProvidersRequest { + sandbox: "work".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), + page_size: 1, + page_token: String::new(), + }), ) - .await; - result.expect("older clients still send a session token"); - - assert_eq!(events.len(), 1, "{events:?}"); - assert_logon(&events[0], FORWARD_TCP_PATH); - assert_eq!(events[0]["auth_protocol"], "ssh_session_token"); - assert_redacted(&events[0], "canary-ssh-token"); - } + .await + .unwrap() + .into_inner(); - #[tokio::test] - async fn ssh_session_token_logs_on_once() { - let state = test_server_state().await; - let sandbox = test_sandbox("fwd", Vec::new()); - store_ssh_session(&state, "canary-ssh-token-valid", "sandbox-fwd", false, 0).await; - let init = forward_init( - tcp_forward_init::Target::Ssh(SshRelayTarget::default()), - "canary-ssh-token-valid", + assert_eq!(first_page.providers.len(), 1); + assert_eq!(first_page.providers[0].r#type, "github"); + assert_eq!( + first_page.providers[0].credentials.get("TOKEN"), + Some(&"REDACTED".to_string()) ); + assert!(!first_page.next_page_token.is_empty()); - let (first, events) = acquire_audited(&state, &init, &sandbox).await; - let (second, repeated) = acquire_audited(&state, &init, &sandbox).await; - first.expect("valid session token"); - second.expect("valid session token"); - - assert!(repeated.is_empty(), "{repeated:?}"); - assert_eq!(events.len(), 1, "{events:?}"); - let event = &events[0]; - assert_logon(event, FORWARD_TCP_PATH); - assert_eq!(event["auth_protocol"], "ssh_session_token"); - assert_eq!(event["user"]["uid"], "dev-user"); - assert_origin(event); - assert_redacted(event, "canary-ssh-token"); - } + crate::grpc::workspace::handle_create_workspace( + &state, + Request::new(CreateWorkspaceRequest { + request_id: String::new(), + name: "beta".to_string(), + labels: HashMap::new(), + }), + ) + .await + .expect("beta workspace should be created"); + let mut beta_provider = test_provider("work-github", "github"); + beta_provider.metadata.as_mut().unwrap().id = "provider-beta-work-github".to_string(); + beta_provider.metadata.as_mut().unwrap().workspace = "beta".to_string(); + state.store.put_message(&beta_provider).await.unwrap(); + let mut beta_sandbox = test_sandbox("work", vec!["work-github".to_string()]); + beta_sandbox.metadata.as_mut().unwrap().id = "sandbox-beta-work".to_string(); + beta_sandbox.metadata.as_mut().unwrap().workspace = "beta".to_string(); + state.store.put_message(&beta_sandbox).await.unwrap(); - #[tokio::test] - async fn tcp_forwards_are_capped_per_sandbox() { - let state = test_server_state().await; - let sandbox = test_sandbox("fwd", Vec::new()); - let init = forward_init(loopback_tcp_target(), ""); - let cap = openshell_core::config::DEFAULT_MAX_CONNECTIONS_PER_SANDBOX; + let err = handle_list_sandbox_providers( + &state, + authed_request(ListSandboxProvidersRequest { + sandbox: "work".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector("beta")), + page_size: 1, + page_token: first_page.next_page_token.clone(), + }), + ) + .await + .expect_err("a token for one workspace must not list a same-named sandbox elsewhere"); + assert_eq!(err.code(), tonic::Code::InvalidArgument); - let mut guards = Vec::new(); - for _ in 0..cap { - guards.push( - acquire_forward_connection_guard(&state, &forward_caller(), &init, &sandbox) - .await - .expect("within the per-sandbox cap"), - ); - } - let err = acquire_forward_connection_guard(&state, &forward_caller(), &init, &sandbox) + let mut sandbox = state + .store + .get_message_by_name::("default", "work") .await - .err() - .expect("cap reached"); - assert_eq!(err.code(), tonic::Code::ResourceExhausted); - assert_eq!( - err.message(), - "sandbox service forward connection limit reached" - ); - assert_eq!( - sandbox_connection_count(&state, RelayBudget::Service, sandbox.object_id()), - cap - ); + .unwrap() + .expect("sandbox exists"); + sandbox + .spec + .as_mut() + .expect("sandbox has a spec") + .providers + .retain(|name| name != "work-github"); + state.store.put_message(&sandbox).await.unwrap(); - guards.pop(); - let guard = acquire_forward_connection_guard(&state, &forward_caller(), &init, &sandbox) - .await - .expect("slot freed by a closed connection"); - drop(guard); - drop(guards); - assert_eq!( - sandbox_connection_count(&state, RelayBudget::Service, sandbox.object_id()), - 0 - ); + let err = handle_list_sandbox_providers( + &state, + authed_request(ListSandboxProvidersRequest { + sandbox: "other".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), + page_size: 1, + page_token: first_page.next_page_token.clone(), + }), + ) + .await + .expect_err("a token for one sandbox must not list another sandbox"); + assert_eq!(err.code(), tonic::Code::InvalidArgument); + + let second_page = handle_list_sandbox_providers( + &state, + authed_request(ListSandboxProvidersRequest { + sandbox: "work".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), + page_size: 100, + page_token: first_page.next_page_token, + }), + ) + .await + .unwrap() + .into_inner(); + assert_eq!(second_page.providers.len(), 1); + assert_eq!(second_page.providers[0].r#type, "gitlab"); + assert!(second_page.next_page_token.is_empty()); } #[tokio::test] - async fn ssh_and_service_budgets_are_independent() { - let mut state = test_server_state().await; - { - let config = &mut Arc::get_mut(&mut state).expect("sole state owner").config; - config.max_ssh_connections_per_sandbox = 1; - config.max_service_connections_per_sandbox = 2; - } - let sandbox = test_sandbox("fwd", Vec::new()); - store_ssh_session(&state, "canary-ssh-token-a", "sandbox-fwd", false, 0).await; - store_ssh_session(&state, "canary-ssh-token-b", "sandbox-fwd", false, 0).await; - let tcp = forward_init(loopback_tcp_target(), ""); - let ssh = |token: &str| { - forward_init( - tcp_forward_init::Target::Ssh(SshRelayTarget::default()), - token, - ) - }; - let acquire = |init: TcpForwardInit| { - let state = state.clone(); - let sandbox = sandbox.clone(); - async move { - acquire_forward_connection_guard(&state, &forward_caller(), &init, &sandbox).await - } - }; + async fn attach_sandbox_provider_validates_provider_exists() { + let state = test_server_state().await; + state + .store + .put_message(&test_sandbox("work", Vec::new())) + .await + .unwrap(); - let _forwards = [ - acquire(tcp.clone()).await.expect("first forward"), - acquire(tcp.clone()).await.expect("second forward"), - ]; - let err = acquire(tcp).await.err().expect("forward budget spent"); - assert_eq!( - err.message(), - "sandbox service forward connection limit reached" - ); + let err = handle_attach_sandbox_provider( + &state, + authed_request(AttachSandboxProviderRequest { + request_id: String::new(), + sandbox: "work".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), + provider: "missing".to_string(), + expected_resource_version: 0, + }), + ) + .await + .unwrap_err(); - let ssh_guard = acquire(ssh("canary-ssh-token-a")) - .await - .expect("open forwards leave the SSH budget alone"); - let err = acquire(ssh("canary-ssh-token-b")) - .await - .err() - .expect("SSH budget spent"); - assert_eq!(err.code(), tonic::Code::ResourceExhausted); - assert_eq!(err.message(), "sandbox SSH connection limit reached"); - let direct = forward_init( - tcp_forward_init::Target::DirectSshSandboxId(sandbox.object_id().into()), - "", - ); - assert_eq!( - acquire(direct.clone()).await.err().unwrap().code(), - tonic::Code::ResourceExhausted - ); - drop(ssh_guard); - let direct_guard = acquire(direct).await.unwrap(); - assert!(direct_guard.token.is_none()); - assert_eq!( - acquire(ssh("canary-ssh-token-a")) - .await - .err() - .unwrap() - .code(), - tonic::Code::ResourceExhausted - ); - assert_eq!( - sandbox_connection_count(&state, RelayBudget::Ssh, sandbox.object_id()), - 1 - ); - assert_eq!( - sandbox_connection_count(&state, RelayBudget::Service, sandbox.object_id()), - 2 - ); - drop(direct_guard); - assert!(acquire(ssh("canary-ssh-token-a")).await.is_ok()); + assert_eq!(err.code(), tonic::Code::FailedPrecondition); } + // ---- validate_interactive_exec_start ---- + #[test] - fn tcp_forward_init_allows_loopback_targets() { - for host in ["127.0.0.1", "::1", "localhost"] { - let init = TcpForwardInit { - sandbox: "sbx".to_string(), - workspace: String::new(), - service_id: String::new(), - target: Some(tcp_forward_init::Target::Tcp(TcpRelayTarget { - host: host.to_string(), - port: 8080, - })), - authorization_token: String::new(), - }; - validate_tcp_forward_init(&init).expect("loopback target should pass"); - } + fn interactive_exec_rejects_empty_stream() { + let err = validate_interactive_exec_start(None).unwrap_err(); + assert_eq!(err.code(), tonic::Code::InvalidArgument); + assert!(err.message().contains("expected start message")); } #[test] - fn tcp_forward_init_allows_ssh_target() { - let init = TcpForwardInit { - sandbox: "sbx".to_string(), - workspace: String::new(), - target: Some(tcp_forward_init::Target::Ssh(SshRelayTarget::default())), - ..Default::default() + fn interactive_exec_rejects_stdin_as_first_message() { + use openshell_core::proto::exec_sandbox_input; + let msg = ExecSandboxInput { + payload: Some(exec_sandbox_input::Payload::Stdin(b"hello".to_vec())), }; - match validate_tcp_forward_init(&init).expect("ssh target should pass") { - relay_open::Target::Ssh(_) => {} - other @ relay_open::Target::Tcp(_) => panic!("expected SSH target, got {other:?}"), - } + let err = validate_interactive_exec_start(Some(msg)).unwrap_err(); + assert_eq!(err.code(), tonic::Code::InvalidArgument); + assert!(err.message().contains("start payload")); } #[test] - fn tcp_forward_init_rejects_non_loopback_targets() { - let init = TcpForwardInit { - sandbox: "sbx".to_string(), - workspace: String::new(), - service_id: String::new(), - target: Some(tcp_forward_init::Target::Tcp(TcpRelayTarget { - host: "example.com".to_string(), - port: 8080, - })), - authorization_token: String::new(), + fn interactive_exec_rejects_resize_as_first_message() { + use openshell_core::proto::{ExecSandboxWindowResize, exec_sandbox_input}; + let msg = ExecSandboxInput { + payload: Some(exec_sandbox_input::Payload::Resize( + ExecSandboxWindowResize { cols: 80, rows: 24 }, + )), }; - assert_eq!( - validate_tcp_forward_init(&init) - .expect_err("hostname rejected") - .message(), - "tcp target host must be loopback" - ); + let err = validate_interactive_exec_start(Some(msg)).unwrap_err(); + assert_eq!(err.code(), tonic::Code::InvalidArgument); + assert!(err.message().contains("start payload")); } #[test] - fn tcp_forward_init_rejects_invalid_port() { - let init = TcpForwardInit { - sandbox: "sbx".to_string(), - workspace: String::new(), - service_id: String::new(), - target: Some(tcp_forward_init::Target::Tcp(TcpRelayTarget { - host: "127.0.0.1".to_string(), - port: 0, - })), - authorization_token: String::new(), - }; - assert_eq!( - validate_tcp_forward_init(&init) - .expect_err("zero port rejected") - .message(), - "tcp target port must be between 1 and 65535" - ); + fn interactive_exec_rejects_none_payload() { + let msg = ExecSandboxInput { payload: None }; + let err = validate_interactive_exec_start(Some(msg)).unwrap_err(); + assert_eq!(err.code(), tonic::Code::InvalidArgument); } #[test] - fn tcp_forward_init_requires_target() { - let init = TcpForwardInit { - sandbox: "sbx".to_string(), - workspace: String::new(), - ..Default::default() + fn interactive_exec_rejects_missing_sandbox_name() { + use openshell_core::proto::exec_sandbox_input; + let msg = ExecSandboxInput { + payload: Some(exec_sandbox_input::Payload::Start(ExecSandboxRequest { + command: vec!["bash".to_string()], + ..Default::default() + })), }; - assert_eq!( - validate_tcp_forward_init(&init) - .expect_err("missing target rejected") - .message(), - "tcp forward target is required" - ); + let err = validate_interactive_exec_start(Some(msg)).unwrap_err(); + assert_eq!(err.code(), tonic::Code::InvalidArgument); + assert!(err.message().contains("sandbox")); } - // ---- petname / generate_name ---- - #[test] - fn sandbox_name_defaults_to_petname_format() { - for _ in 0..50 { - let name = petname::petname(2, "-").expect("petname should produce a name"); - let parts: Vec<&str> = name.split('-').collect(); - assert_eq!( - parts.len(), - 2, - "expected two hyphen-separated words, got: {name}" - ); - for part in &parts { - assert!( - !part.is_empty() && part.chars().all(|c| c.is_ascii_lowercase()), - "each word should be non-empty lowercase ascii: {name}" - ); - } - } + fn interactive_exec_rejects_missing_command() { + use openshell_core::proto::exec_sandbox_input; + let msg = ExecSandboxInput { + payload: Some(exec_sandbox_input::Payload::Start(ExecSandboxRequest { + sandbox: "test-id".to_string(), + workspace_scope: None, + ..Default::default() + })), + }; + let err = validate_interactive_exec_start(Some(msg)).unwrap_err(); + assert_eq!(err.code(), tonic::Code::InvalidArgument); + assert!(err.message().contains("command")); } #[test] - fn generate_routable_name_respects_length_limit() { - for _ in 0..200 { - let name = generate_routable_name(); - assert!( - name.len() <= MAX_ROUTABLE_NAME_LEN, - "generated name '{name}' exceeds {MAX_ROUTABLE_NAME_LEN} chars" - ); - assert!(!name.is_empty(), "generated name should not be empty"); - } + fn interactive_exec_rejects_invalid_env_key() { + use openshell_core::proto::exec_sandbox_input; + let msg = ExecSandboxInput { + payload: Some(exec_sandbox_input::Payload::Start(ExecSandboxRequest { + sandbox: "test-id".to_string(), + workspace_scope: None, + command: vec!["bash".to_string()], + environment: std::iter::once(("bad key!".to_string(), "val".to_string())).collect(), + ..Default::default() + })), + }; + let err = validate_interactive_exec_start(Some(msg)).unwrap_err(); + assert_eq!(err.code(), tonic::Code::InvalidArgument); + assert!(err.message().contains("environment")); } #[test] - fn generate_name_fallback_is_valid() { - for _ in 0..50 { - let name = generate_name(); - assert_eq!(name.len(), 6, "unexpected length for fallback name: {name}"); - assert!( - name.chars().all(|c| c.is_ascii_lowercase()), - "fallback name should be all lowercase: {name}" - ); - } - } - - /// Import a minimal profile so a synthetic provider type resolves. - /// - /// Provider profiles are import-only: a provider whose type no profile - /// declares cannot compose a sandbox. Tests about limits, CAS or credential - /// collisions still need their placeholder types to exist. - async fn import_test_profile(state: &ServerState, id: &str) { - state - .store - .put_message(&crate::provider_profile_sources::stored_provider_profile( - openshell_core::proto::ProviderProfile { - id: id.to_string(), - display_name: id.to_string(), - category: openshell_core::proto::ProviderProfileCategory::Other as i32, - ..Default::default() - }, - )) - .await - .expect("store test provider profile"); - } - - fn test_provider(name: &str, provider_type: &str) -> Provider { - test_provider_with_credential_key(name, provider_type, "TOKEN") + fn interactive_exec_accepts_valid_start() { + use openshell_core::proto::exec_sandbox_input; + let msg = ExecSandboxInput { + payload: Some(exec_sandbox_input::Payload::Start(ExecSandboxRequest { + sandbox: "test-id".to_string(), + workspace_scope: None, + command: vec!["bash".to_string()], + tty: true, + cols: 120, + rows: 40, + ..Default::default() + })), + }; + let req = validate_interactive_exec_start(Some(msg)).unwrap(); + assert_eq!(req.sandbox, "test-id"); + assert_eq!(req.command, vec!["bash"]); + assert!(req.tty); + assert_eq!(req.cols, 120); + assert_eq!(req.rows, 40); } - fn test_provider_with_credential_key( - name: &str, - provider_type: &str, - credential_key: &str, - ) -> Provider { - Provider { - metadata: Some(ObjectMeta { - id: format!("provider-{name}"), - name: name.to_string(), - created_time: openshell_core::time::timestamp_from_millis(1_000_000).ok(), - labels: HashMap::new(), - resource_version: 0, - annotations: HashMap::new(), - workspace: "default".to_string(), - deletion_time: None, - }), - r#type: provider_type.to_string(), - credentials: std::iter::once((credential_key.to_string(), "secret".to_string())) - .collect(), - config: HashMap::new(), - credential_expiration_times: HashMap::new(), - profile_workspace: "default".to_string(), - credential_handles: HashMap::new(), - } - } + #[tokio::test] + async fn interactive_exec_rejects_sandbox_not_found() { + let state = test_server_state().await; - fn test_sandbox(name: &str, providers: Vec) -> Sandbox { - let mut sandbox = Sandbox { - metadata: Some(ObjectMeta { - id: format!("sandbox-{name}"), - name: name.to_string(), - created_time: openshell_core::time::timestamp_from_millis(1_000_000).ok(), - labels: std::iter::once(("team".to_string(), "agents".to_string())).collect(), - resource_version: 0, - annotations: HashMap::new(), - workspace: "default".to_string(), - deletion_time: None, - }), - spec: Some(SandboxSpec { - log_level: "debug".to_string(), - policy: Some(openshell_core::proto::SandboxPolicy::default()), - providers, - ..Default::default() - }), + let req = ExecSandboxRequest { + sandbox: "nonexistent".to_string(), + workspace_scope: None, + command: vec!["bash".to_string()], + tty: true, ..Default::default() }; - sandbox.set_phase(SandboxPhase::Ready as i32); - sandbox.set_current_policy_version(7); - sandbox + let sandbox_result = state + .store + .get_message_by_name::("default", &req.sandbox) + .await + .unwrap(); + assert!(sandbox_result.is_none()); } - fn test_workload_template(name: &str) -> SandboxWorkloadTemplate { - SandboxWorkloadTemplate { - metadata: Some(ObjectMeta { - id: String::new(), - name: name.to_string(), - created_time: openshell_core::time::timestamp_from_millis(0).ok(), - labels: HashMap::from([("team".to_string(), "runtime".to_string())]), - resource_version: 0, - annotations: HashMap::new(), - workspace: String::new(), - deletion_time: None, - }), - spec: Some(openshell_core::proto::SandboxWorkloadTemplateSpec { - workload: Some(openshell_core::proto::SandboxWorkloadConfig { - image: "registry.example.com/agent:latest".to_string(), - environment: HashMap::from([("FEATURE_FLAG".to_string(), "on".to_string())]), - resources: Some(SandboxResources { - cpu: "2".to_string(), - memory: "4Gi".to_string(), - gpu: Some(GpuResourceRequirements { count: Some(1) }), - }), + #[tokio::test] + async fn interactive_exec_rejects_sandbox_not_ready() { + let state = test_server_state().await; + let mut sandbox = test_sandbox("not-ready", Vec::new()); + sandbox.set_phase(SandboxPhase::Provisioning as i32); + state.store.put_message(&sandbox).await.unwrap(); + + let stored = state + .store + .get_message::("sandbox-not-ready") + .await + .unwrap() + .unwrap(); + assert_ne!( + SandboxPhase::try_from(stored.phase()).ok(), + Some(SandboxPhase::Ready) + ); + } + + #[tokio::test] + async fn create_sandbox_rejects_provider_credential_key_collisions() { + let state = test_server_state().await; + import_test_profile(&state, "outlook").await; + import_test_profile(&state, "google-drive").await; + state + .store + .put_message(&test_provider("provider-a", "outlook")) + .await + .unwrap(); + state + .store + .put_message(&test_provider("provider-b", "google-drive")) + .await + .unwrap(); + + let err = handle_create_sandbox( + &state, + authed_request(CreateSandboxRequest { + parent: String::new(), + request_id: String::new(), + name: "collision".to_string(), + spec: Some(SandboxSpec { + providers: vec!["provider-a".to_string(), "provider-b".to_string()], + ..Default::default() }), - driver_config: None, - desired_service_level: None, + labels: HashMap::new(), + annotations: HashMap::new(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), + await_main_process_attachment: false, + workload_template: String::new(), + service_exposures: Vec::new(), }), - } - } + ) + .await + .unwrap_err(); - fn proto_string_value(value: &Value) -> Option<&str> { - match value.kind.as_ref() { - Some(Kind::StringValue(value)) => Some(value.as_str()), - _ => None, - } + assert_eq!(err.code(), tonic::Code::FailedPrecondition); + assert!(err.message().contains("TOKEN")); + assert!(err.message().contains("provider-a")); + assert!(err.message().contains("provider-b")); } #[tokio::test] - async fn watch_producer_releases_request_span_when_client_disconnects() { - use crate::otel_tracing::test_exporter; - use tokio_stream::StreamExt as _; - use tracing::Instrument as _; - - let state = test_server_state().await; - let sandbox = test_sandbox("watched", Vec::new()); - state.store.put_message(&sandbox).await.unwrap(); + async fn provider_create_failure_releases_global_guard_before_compensation() { + let state = test_server_state_with_compute_driver( + "test", + Arc::new(NoopTestDriver::authenticating_sandbox_with_runtime( + "unused", "", + )), + ) + .await; + state + .store + .put_message(&test_provider("work-github", "github")) + .await + .unwrap(); - let traced = test_exporter::install_traced(); - let request_span = tracing::info_span!("disconnected_watch_request"); - let mut handler = Box::pin( - handle_watch_sandbox( + let result = tokio::time::timeout( + std::time::Duration::from_secs(1), + handle_create_sandbox( &state, - authed_request(WatchSandboxRequest { - sandbox: "watched".to_string(), + authed_request(CreateSandboxRequest { + name: "provider-fail".to_string(), + spec: Some(SandboxSpec { + providers: vec!["work-github".to_string()], + ..Default::default() + }), workspace_scope: Some(openshell_core::proto::workspace_selector( "default".to_string(), )), ..Default::default() }), - ) - .instrument(request_span.clone()), - ); - let response = handler.as_mut().await.unwrap(); - // A completed instrumented future can retain its span until the future - // itself is dropped. Release the handler's clone so this test isolates - // whether the spawned watch producer retains the request span. - drop(handler); - let mut stream = response.into_inner(); - stream - .next() - .await - .expect("watch producer should send the initial snapshot") - .unwrap(); - - drop(request_span); - stream.disconnect_and_wait().await; - traced.wait_for_span("disconnected_watch_request").await; + ), + ) + .await + .expect("create compensation must not deadlock") + .expect_err("empty runtime identity must fail create"); - assert_eq!( - traced.spans_named("disconnected_watch_request").len(), - 1, - "watch producer should release the request span after client disconnect" - ); + assert_eq!(result.code(), tonic::Code::Internal, "{}", result.message()); + let retained = state + .store + .get_message_by_name::("default", "provider-fail") + .await + .unwrap() + .expect("accepted asynchronous cleanup must retain the sandbox record"); + assert_eq!(retained.phase(), SandboxPhase::Deleting as i32); } #[tokio::test] - async fn logs_only_watch_ends_when_sweeper_frees_sandbox_deleted_elsewhere() { - use tokio_stream::StreamExt as _; - + async fn create_sandbox_uses_configured_provider_profile_sources() { let state = test_server_state().await; - let sandbox = test_sandbox("swept", Vec::new()); - state.store.put_message(&sandbox).await.unwrap(); - let id = sandbox.object_id().to_string(); - let response = handle_watch_sandbox( + let response = handle_create_sandbox( &state, - authed_request(WatchSandboxRequest { - sandbox: sandbox.object_name().to_string(), - workspace_scope: Some(openshell_core::proto::workspace_selector("default")), - follow_logs: true, - ..Default::default() + authed_request(CreateSandboxRequest { + parent: String::new(), + request_id: String::new(), + name: "user-catalog".to_string(), + spec: Some(SandboxSpec::default()), + labels: HashMap::new(), + annotations: HashMap::new(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), + await_main_process_attachment: false, + workload_template: String::new(), + service_exposures: Vec::new(), }), ) .await - .unwrap(); - let mut stream = response.into_inner(); + .expect("an imported github profile should resolve from the user source") + .into_inner(); - // A delivered log line proves the watch has subscribed. - seed_log_lines(&state, &id, 1); - loop { - let event = stream.next().await.unwrap().unwrap(); - if !event.cursor.is_empty() { - break; - } + assert_eq!( + response.sandbox.expect("created sandbox").object_name(), + "user-catalog" + ); + } + + async fn child_sandboxes_state() -> Arc { + child_sandboxes_state_with_limit(10).await + } + + async fn child_sandboxes_state_with_limit(limit: u32) -> Arc { + let mut state = test_server_state().await; + let inner = Arc::get_mut(&mut state).unwrap(); + inner.config.enable_child_sandboxes = true; + inner.config.max_concurrent_children = limit; + inner.compute = inner.compute.clone().with_child_sandboxes(true); + state + } + + async fn put_parent_record( + state: &ServerState, + name: &str, + providers: &[&str], + parent: Option, + deleting: bool, + ) -> String { + let id = uuid::Uuid::new_v4().to_string(); + let mut sandbox = Sandbox { + metadata: Some(ObjectMeta { + id: id.clone(), + name: name.to_string(), + workspace: "default".to_string(), + ..Default::default() + }), + spec: Some(SandboxSpec { + providers: providers.iter().map(ToString::to_string).collect(), + ..Default::default() + }), + parent, + ..Default::default() + }; + if deleting { + sandbox.set_phase(SandboxPhase::Deleting as i32); } + state.store.put_message(&sandbox).await.unwrap(); + put_policy_revision_with_status( + state, + &id, + 1, + &openshell_policy::restrictive_default_policy(), + "loaded", + ) + .await; + id + } - // Another replica deletes the record; this one never runs delete cleanup. + async fn put_policy_revision_with_status( + state: &ServerState, + sandbox_id: &str, + version: i64, + policy: &openshell_core::proto::SandboxPolicy, + status: &str, + ) { state - .store - .delete(Sandbox::object_type(), &id) - .await - .unwrap(); - let mut suspects = HashSet::new(); - for expected in [0, 1] { - let closed = crate::bus_sweeper::sweep_once( - &state.store, - &state.tracing_log_bus, - std::time::Duration::ZERO, - &mut suspects, + .store + .put_policy_revision( + &uuid::Uuid::new_v4().to_string(), + sandbox_id, + "default", + version, + &policy.encode_to_vec(), + &openshell_core::policy_identity::deterministic_policy_hash(policy), ) .await .unwrap(); - assert_eq!(closed, expected); + state + .store + .update_policy_status( + sandbox_id, + version, + status, + None, + (status == "loaded").then(current_time_ms), + ) + .await + .unwrap(); + // As the report handler does: a load moves the sandbox's current + // policy version forward. + if status == "loaded" + && let Some(mut sandbox) = state + .store + .get_message::(sandbox_id) + .await + .unwrap() + && i64::from(sandbox.current_policy_version()) < version + { + sandbox.set_current_policy_version(u32::try_from(version).unwrap()); + state.store.put_message(&sandbox).await.unwrap(); } - - let ended = tokio::time::timeout(std::time::Duration::from_secs(5), async { - while let Some(item) = stream.next().await { - if item.is_err() { - break; - } - } - }) - .await; - assert!( - ended.is_ok(), - "logs-only watch should end once its buffers are freed" - ); } - /// Seed `n` log lines onto the log bus; cursors run 1..=n. - fn seed_log_lines(state: &ServerState, sandbox_id: &str, n: usize) { - for i in 0..n { - state - .tracing_log_bus - .publish_external(openshell_core::proto::SandboxLogLine { - sandbox_id: sandbox_id.to_string(), - event_time: openshell_core::time::timestamp_from_millis(i as i64).ok(), - level: "INFO".to_string(), - target: "test".to_string(), - message: format!("line {i}"), - source: "gateway".to_string(), + fn lead_policy(advisor_proposed: bool) -> openshell_core::proto::SandboxPolicy { + let mut policy = openshell_policy::restrictive_default_policy(); + policy.network_policies.insert( + "api".to_string(), + openshell_core::proto::NetworkPolicyRule { + name: "api".to_string(), + endpoints: vec![openshell_core::proto::NetworkEndpoint { + host: "api.example.com".to_string(), + port: 443, + advisor_proposed, ..Default::default() - }); - } - } - - fn seed_platform_event(state: &ServerState, sandbox_id: &str, reason: &str) { - state.tracing_log_bus.platform_event_bus.publish( - sandbox_id, - SandboxStreamEvent { - payload: Some(openshell_core::proto::sandbox_stream_event::Payload::Event( - openshell_core::proto::PlatformEvent { - event_time: openshell_core::time::timestamp_from_millis(0).ok(), - source: "test".to_string(), - r#type: "Normal".to_string(), - reason: reason.to_string(), - message: reason.to_string(), - metadata: HashMap::new(), - }, - )), - cursor: String::new(), + }], + ..Default::default() }, ); + policy } - /// Build the token a client would hold for `seq` in this sandbox's *current* - /// cursor space. Capture it before any teardown to model a real reconnect. - fn cursor_token(state: &ServerState, sandbox_id: &str, seq: u64) -> String { - let space = state - .tracing_log_bus - .cursor_space(sandbox_id) - .expect("cursor space exists; publish before taking a token"); - WatchCursor::new(space.epoch, seq).encode() + async fn latest_policy( + state: &ServerState, + sandbox_id: &str, + ) -> crate::persistence::PolicyRecord { + state + .store + .get_latest_policy(sandbox_id) + .await + .unwrap() + .expect("policy revision") } - /// A well-formed token from an epoch this server never issued. - fn foreign_cursor(seq: u64) -> String { - WatchCursor::new(uuid::Uuid::new_v4(), seq).encode() + async fn create_child(state: &Arc, name: &str, parent: &str) -> Sandbox { + handle_create_sandbox( + state, + authed_request(child_request(name, parent, SandboxSpec::default())), + ) + .await + .expect("child sandbox is created") + .into_inner() + .sandbox + .expect("created sandbox") } - /// Sequence number carried by a delivered event. Panics on non-resumable - /// events, so a test that expects a log line cannot silently pass on a - /// snapshot. - fn seq_of(evt: &SandboxStreamEvent) -> u64 { - WatchCursor::parse(&evt.cursor) - .expect("resumable event must carry a valid cursor") - .seq + fn child_request(name: &str, parent: &str, spec: SandboxSpec) -> CreateSandboxRequest { + CreateSandboxRequest { + parent: parent.to_string(), + name: name.to_string(), + spec: Some(spec), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), + ..Default::default() + } } #[tokio::test] - async fn resume_replays_only_events_after_cursor() { - use tokio_stream::StreamExt as _; - - let state = test_server_state().await; - let sandbox = test_sandbox("resumed", Vec::new()); - state.store.put_message(&sandbox).await.unwrap(); - let id = sandbox.object_id().to_string(); - - // Cursors 1,2,3. - seed_log_lines(&state, &id, 3); + async fn create_child_sandbox_records_its_parent() { + let state = child_sandboxes_state().await; + let lead_id = put_parent_record(&state, "lead", &[], None, false).await; - let response = handle_watch_sandbox( + let child = handle_create_sandbox( &state, - authed_request(WatchSandboxRequest { - sandbox: sandbox.object_name().to_string(), - workspace_scope: Some(openshell_core::proto::workspace_selector("default")), - follow_logs: true, - resume_after_cursor: cursor_token(&state, &id, 1), - ..Default::default() - }), + authed_request(child_request("worker1", "lead", SandboxSpec::default())), ) .await - .unwrap(); + .expect("a child of a root sandbox is created") + .into_inner() + .sandbox + .expect("created sandbox"); - let mut stream = response.into_inner(); - // Snapshot first (status re-read, no cursor). - let snap = stream.next().await.unwrap().unwrap(); - assert!( - snap.cursor.is_empty(), - "first event should be the status snapshot" + assert_eq!( + child.parent, + Some(openshell_core::proto::SandboxParent { + name: "lead".to_string(), + id: lead_id, + }) ); - - // Then only seqs 2 and 3; seq 1 already seen by the client. - let a = stream.next().await.unwrap().unwrap(); - let b = stream.next().await.unwrap().unwrap(); - assert_eq!(seq_of(&a), 2); - assert_eq!(seq_of(&b), 3); } #[tokio::test] - async fn resume_merges_log_and_platform_events_in_cursor_order() { - use tokio_stream::StreamExt as _; - - let state = test_server_state().await; - let sandbox = test_sandbox("merged", Vec::new()); - state.store.put_message(&sandbox).await.unwrap(); - let id = sandbox.object_id().to_string(); - - // Interleave across the shared allocator: log=1, platform=2, log=3, platform=4. - seed_log_lines(&state, &id, 1); // cursor 1 - seed_platform_event(&state, &id, "e2"); // cursor 2 - state - .tracing_log_bus - .publish_external(openshell_core::proto::SandboxLogLine { - sandbox_id: id.clone(), - event_time: openshell_core::time::timestamp_from_millis(3).ok(), - level: "INFO".to_string(), - target: "test".to_string(), - message: "line 3".to_string(), - source: "gateway".to_string(), - ..Default::default() - }); // cursor 3 - seed_platform_event(&state, &id, "e4"); // cursor 4 - - let response = handle_watch_sandbox( + async fn create_sandbox_records_its_creator() { + let state = child_sandboxes_state().await; + let root = handle_create_sandbox( &state, - authed_request(WatchSandboxRequest { - sandbox: sandbox.object_name().to_string(), - workspace_scope: Some(openshell_core::proto::workspace_selector("default")), - follow_logs: true, - follow_events: true, - resume_after_cursor: cursor_token(&state, &id, 1), - ..Default::default() - }), + authed_request(child_request("lead", "", SandboxSpec::default())), ) .await - .unwrap(); - - let mut stream = response.into_inner(); - let snap = stream.next().await.unwrap().unwrap(); - assert!(snap.cursor.is_empty()); + .expect("root sandbox is created") + .into_inner() + .sandbox + .expect("created sandbox"); + put_policy_revision_with_status( + &state, + root.object_id(), + 1, + &openshell_policy::restrictive_default_policy(), + "loaded", + ) + .await; + let child = handle_create_sandbox( + &state, + authed_request(child_request("worker1", "lead", SandboxSpec::default())), + ) + .await + .expect("child sandbox is created") + .into_inner() + .sandbox + .expect("created sandbox"); - // Merged from both buses, ascending by shared seq: 2,3,4. - let mut got = Vec::new(); - for _ in 0..3 { - got.push(seq_of(&stream.next().await.unwrap().unwrap())); - } - assert_eq!(got, vec![2, 3, 4]); + let user = |sandbox: &Sandbox| sandbox.created_on_behalf_of.clone().unwrap().subject; + assert_eq!(user(&root), "dev-user"); + assert_eq!(user(&child), "dev-user"); } - /// The initial tail is the resume path's twin: it draws from the same two - /// buses over the same shared cursor space, so it owes the client the same - /// ascending order. - /// - /// Before the merge, each bus was drained in its own pass and the tail came - /// out grouped by source -- logs 1,3 then platform 2,4 -- so a client - /// tracking the highest cursor saw it go backwards mid-tail. #[tokio::test] - async fn initial_tail_merges_log_and_platform_events_in_cursor_order() { - use tokio_stream::StreamExt as _; + async fn child_without_providers_copies_the_parent_providers() { + let state = child_sandboxes_state().await; + put_parent_record(&state, "lead", &["a", "b"], None, false).await; - let state = test_server_state().await; - let sandbox = test_sandbox("tailmerged", Vec::new()); - state.store.put_message(&sandbox).await.unwrap(); - let id = sandbox.object_id().to_string(); + let mut spec = SandboxSpec::default(); + resolve_create_parent(&state, "default", "lead", &mut spec) + .await + .expect("parent resolves"); + assert_eq!(spec.providers, vec!["a".to_string(), "b".to_string()]); - // Interleave across the shared allocator: log=1, platform=2, log=3, platform=4. - seed_log_lines(&state, &id, 1); // cursor 1 - seed_platform_event(&state, &id, "e2"); // cursor 2 - state - .tracing_log_bus - .publish_external(openshell_core::proto::SandboxLogLine { - sandbox_id: id.clone(), - event_time: openshell_core::time::timestamp_from_millis(3).ok(), - level: "INFO".to_string(), - target: "test".to_string(), - message: "line 3".to_string(), - source: "gateway".to_string(), - ..Default::default() - }); // cursor 3 - seed_platform_event(&state, &id, "e4"); // cursor 4 + let mut spec = SandboxSpec { + providers: vec!["a".to_string()], + ..Default::default() + }; + resolve_create_parent(&state, "default", "lead", &mut spec) + .await + .expect("parent resolves"); + assert_eq!(spec.providers, vec!["a".to_string()]); + } - let response = handle_watch_sandbox( + #[tokio::test] + async fn child_provider_detached_before_the_lock_is_refused() { + let state = child_sandboxes_state().await; + let lead_id = put_parent_record(&state, "lead", &["a"], None, false).await; + let parent = openshell_core::proto::SandboxParent { + name: "lead".to_string(), + id: lead_id, + }; + + // The child resolved its providers when the lead still had "b". + let err = check_parent_has_room( &state, - authed_request(WatchSandboxRequest { - sandbox: sandbox.object_name().to_string(), - workspace_scope: Some(openshell_core::proto::workspace_selector("default")), - follow_logs: true, - follow_events: true, - // event_tail has no default; 0 would replay no platform events. - event_tail: 10, - ..Default::default() - }), + "default", + &parent, + &["a".to_string(), "b".to_string()], ) .await - .unwrap(); - - let mut stream = response.into_inner(); - let snap = stream.next().await.unwrap().unwrap(); - assert!(snap.cursor.is_empty()); - - let mut got = Vec::new(); - for _ in 0..4 { - got.push(seq_of(&stream.next().await.unwrap().unwrap())); - } - assert_eq!(got, vec![1, 2, 3, 4]); + .unwrap_err(); + assert_eq!(err.code(), tonic::Code::FailedPrecondition); + assert!( + err.message() + .contains("provider 'b' is not attached to parent 'lead'"), + "{}", + err.message() + ); + check_parent_has_room(&state, "default", &parent, &["a".to_string()]) + .await + .expect("providers the lead still has are accepted"); } #[tokio::test] - async fn live_delivery_orders_events_across_sources_by_cursor() { - use tokio_stream::StreamExt as _; - - let state = test_server_state().await; - let sandbox = test_sandbox("liveorder", Vec::new()); - state.store.put_message(&sandbox).await.unwrap(); - let id = sandbox.object_id().to_string(); - - let response = handle_watch_sandbox( + async fn child_of_a_root_whose_policy_is_still_pending_copies_it() { + let state = child_sandboxes_state().await; + let lead = handle_create_sandbox( &state, - authed_request(WatchSandboxRequest { - sandbox: sandbox.object_name().to_string(), - workspace_scope: Some(openshell_core::proto::workspace_selector("default")), - follow_logs: true, - follow_events: true, - ..Default::default() - }), + authed_request(child_request( + "lead", + "", + SandboxSpec { + policy: Some(lead_policy(false)), + ..Default::default() + }, + )), ) .await - .unwrap(); - - let mut stream = response.into_inner(); - // The snapshot itself only proves both subscriptions are live -- the - // replay reads come after it. But on this current-thread runtime the - // producer cannot yield between the two, so by the time the test task - // is scheduled again the producer has run through to the live loop. - let snap = stream.next().await.unwrap().unwrap(); - assert!(snap.cursor.is_empty()); + .expect("root sandbox is created") + .into_inner() + .sandbox + .expect("created sandbox"); + let lead_record = latest_policy(&state, lead.object_id()).await; + assert_ne!(lead_record.status, "loaded"); - // Publish without awaiting in between. On the current-thread runtime - // the producer cannot interleave, so both channels hold ready events - // when it next polls -- the state where `select!` picks arbitrarily and - // would otherwise emit a log cursor ahead of a lower platform cursor. - for i in 0..5 { - seed_log_lines(&state, &id, 1); // odd cursors - seed_platform_event(&state, &id, &format!("e{i}")); // even cursors - } + let child = create_child(&state, "worker1", "lead").await; - let mut got = Vec::new(); - for _ in 0..10 { - got.push(seq_of(&stream.next().await.unwrap().unwrap())); - } - assert_eq!(got, (1..=10).collect::>()); + let child_record = latest_policy(&state, child.object_id()).await; + assert_eq!(child_record.version, 1); + assert_eq!( + super::super::policy::canonical_policy_record_identity(&child_record).unwrap(), + super::super::policy::canonical_policy_record_identity(&lead_record).unwrap(), + ); } - /// A reconnect resumes from the highest cursor the client saw, so live - /// delivery may never emit a cursor while a lower one is still undelivered. - /// The producer drains the log receiver before the platform one: a log line - /// published after that first drain but before the platform drain finishes - /// misses the batch, and its seq is below platform cursors the same batch - /// carries. Emitting them strands the log line -- a disconnect there resumes - /// above it, and no replay ever returns it. The publication watermark holds - /// back anything the drain cannot prove it saw in full. - /// - /// Reaching that interleaving takes a wide drain: the producer is first - /// parked on a full stream channel so a platform backlog accumulates, then - /// both sources are hammered from other worker threads while it walks that - /// backlog. Serialized against the test task the window does not exist -- - /// the drain holds no await a single-threaded test could wedge open. - #[tokio::test(flavor = "multi_thread", worker_threads = 4)] - async fn live_delivery_never_emits_a_cursor_above_an_undrained_event() { - use tokio_stream::StreamExt as _; + #[tokio::test] + async fn child_copies_the_root_latest_revision_even_if_it_failed_or_is_pending() { + let state = child_sandboxes_state().await; + let lead_id = put_parent_record(&state, "lead", &[], None, false).await; + put_policy_revision_with_status(&state, &lead_id, 2, &lead_policy(false), "failed").await; - /// Enough to overrun the 256-slot stream channel and park the producer. - const PARK: usize = 400; - /// Platform events queued while it is parked. The next drain walks all - /// of them, and that walk is the window the hammers below publish into. - /// Kept under the 1024-slot broadcast capacity so nothing is dropped. - const BACKLOG: usize = 600; - const HAMMER: usize = 300; - /// Hitting the window is a race, so repeat it. One round reproduced the - /// unfixed behavior in two runs of three; four caught it in ten of ten. - const ROUNDS: u64 = 4; - /// The single line published to confirm the producer finished - /// initialization before the rounds below start publishing. - const HANDSHAKE: u64 = 1; - const PER_ROUND: u64 = (PARK + BACKLOG + HAMMER * 2) as u64; - const TOTAL: u64 = PER_ROUND * ROUNDS + HANDSHAKE; + let failed_copy = create_child(&state, "worker1", "lead").await; + assert!(holds_parent_latest(&state, failed_copy.object_id(), &lead_id).await); - let state = test_server_state().await; - let sandbox = test_sandbox("watermark", Vec::new()); - state.store.put_message(&sandbox).await.unwrap(); - let id = sandbox.object_id().to_string(); + put_policy_revision_with_status(&state, &lead_id, 3, &lead_policy(true), "pending").await; + let pending_copy = create_child(&state, "worker2", "lead").await; + assert!(holds_parent_latest(&state, pending_copy.object_id(), &lead_id).await); + } - let response = handle_watch_sandbox( - &state, - authed_request(WatchSandboxRequest { - sandbox: sandbox.object_name().to_string(), - workspace_scope: Some(openshell_core::proto::workspace_selector("default")), - follow_logs: true, - follow_events: true, + #[tokio::test] + async fn child_of_a_root_with_no_policy_revision_is_refused() { + let state = child_sandboxes_state().await; + state + .store + .put_message(&Sandbox { + metadata: Some(ObjectMeta { + id: uuid::Uuid::new_v4().to_string(), + name: "lead".to_string(), + workspace: "default".to_string(), + ..Default::default() + }), + spec: Some(SandboxSpec::default()), ..Default::default() - }), + }) + .await + .unwrap(); + + let err = handle_create_sandbox( + &state, + authed_request(child_request("worker1", "lead", SandboxSpec::default())), ) .await - .unwrap(); - let mut stream = response.into_inner(); - // The snapshot only proves both subscriptions are live; the producer - // sends it before reading either replay window. Publishing the rest of - // this test against that state is unsound: the log tail is capped at - // 200 by default, so a burst landing before the read is truncated, the - // rest is suppressed as already replayed, and the test stalls. - // - // One line is the handshake. Receiving it with a cursor -- replayed or - // live, either way -- proves the producer is past both tail reads, and - // one line cannot overflow any tail. Everything below is published into - // a producer known to be in the live loop. - let snap = stream.next().await.unwrap().unwrap(); - assert!(snap.cursor.is_empty()); - seed_log_lines(&state, &id, 1); - let handshake = stream.next().await.unwrap().unwrap(); - assert_eq!( - seq_of(&handshake), - HANDSHAKE, - "handshake line should be seq 1" + .unwrap_err(); + assert_eq!(err.code(), tonic::Code::FailedPrecondition); + assert!( + err.message() + .contains("parent sandbox 'lead' has no policy yet"), + "{}", + err.message() ); + } - let mut highest = HANDSHAKE; - let mut seen = HANDSHAKE; - let mut last_cursor = handshake.cursor; - - for round in 0..ROUNDS { - // Nothing reads during this round's setup, so the producer fills - // the stream channel and blocks part-way through this batch. - seed_log_lines(&state, &id, PARK); - tokio::time::sleep(std::time::Duration::from_millis(50)).await; - - for i in 0..BACKLOG { - seed_platform_event(&state, &id, &format!("b{round}-{i}")); - } - - let log_hammer = { - let state = Arc::clone(&state); - let id = id.clone(); - tokio::spawn(async move { - for _ in 0..HAMMER { - seed_log_lines(&state, &id, 1); - } - }) - }; - let platform_hammer = { - let state = Arc::clone(&state); - let id = id.clone(); - tokio::spawn(async move { - for i in 0..HAMMER { - seed_platform_event(&state, &id, &format!("h{round}-{i}")); - } - }) - }; - - while seen < PER_ROUND * (round + 1) + HANDSHAKE { - let evt = tokio::time::timeout(std::time::Duration::from_secs(30), stream.next()) - .await - .unwrap_or_else(|_| { - panic!( - "live delivery stalled after {seen}/{TOTAL} events, highest {highest}" - ) - }) - .unwrap() - .unwrap(); - let seq = seq_of(&evt); - // Ascending delivery is what makes a highest-cursor resume safe. - // Without the watermark this trips: a log line published during - // the platform walk follows platform cursors emitted above it. - assert!(seq > highest, "cursor {seq} emitted after {highest}"); - highest = seq; - last_cursor = evt.cursor; - seen += 1; - } + #[tokio::test] + async fn child_of_a_root_started_under_a_global_policy_gets_its_policy_later() { + let state = child_sandboxes_state().await; + let lead_id = uuid::Uuid::new_v4().to_string(); + state + .store + .put_message(&Sandbox { + metadata: Some(ObjectMeta { + id: lead_id.clone(), + name: "lead".to_string(), + workspace: "default".to_string(), + ..Default::default() + }), + spec: Some(SandboxSpec::default()), + ..Default::default() + }) + .await + .unwrap(); + let global = super::super::StoredSettings { + revision: 1, + settings: std::iter::once(( + super::super::policy::POLICY_SETTING_KEY.to_string(), + super::super::StoredSettingValue::Bytes(hex::encode( + openshell_policy::restrictive_default_policy().encode_to_vec(), + )), + )) + .collect(), + ..Default::default() + }; + super::super::policy::save_global_settings(state.store.as_ref(), &global) + .await + .unwrap(); - log_hammer.await.unwrap(); - platform_hammer.await.unwrap(); - } + let worker = create_child(&state, "worker1", "lead").await; + let worker_id = worker.object_id().to_string(); + assert!(worker.spec.unwrap().policy.is_none()); + assert!( + state + .store + .get_latest_policy(&worker_id) + .await + .unwrap() + .is_none() + ); - // Every seq in the space belongs to one of the two buses, so `TOTAL` - // ascending events ending at `TOTAL` means none was skipped. - assert_eq!(highest, TOTAL, "live delivery skipped a cursor"); + put_policy_revision_with_status(&state, &lead_id, 1, &lead_policy(false), "loaded").await; + sync_children(&state, &lead_id).await.unwrap(); + assert!(holds_parent_latest(&state, &worker_id, &lead_id).await); + } - // Reconnecting from that cursor is consistent with what was delivered: - // the replay resumes at the next event rather than past one. - seed_log_lines(&state, &id, 1); - seed_platform_event(&state, &id, "after-resume"); - drop(stream); + #[tokio::test] + async fn child_keeps_advisor_markers_from_an_approved_proposal() { + let state = child_sandboxes_state().await; + let lead_id = put_parent_record(&state, "lead", &[], None, false).await; + // An approved proposal leaves its endpoints marked as advisor-proposed. + put_policy_revision_with_status(&state, &lead_id, 2, &lead_policy(true), "loaded").await; - let response = handle_watch_sandbox( - &state, - authed_request(WatchSandboxRequest { - sandbox: sandbox.object_name().to_string(), - workspace_scope: Some(openshell_core::proto::workspace_selector("default")), - follow_logs: true, - follow_events: true, - resume_after_cursor: last_cursor, - ..Default::default() - }), - ) - .await - .unwrap(); - let mut stream = response.into_inner(); - let snap = stream.next().await.unwrap().unwrap(); - assert!(snap.cursor.is_empty()); + let child = create_child(&state, "worker1", "lead").await; - let a = stream.next().await.unwrap().unwrap(); - let b = stream.next().await.unwrap().unwrap(); - assert_eq!(seq_of(&a), TOTAL + 1); - assert_eq!(seq_of(&b), TOTAL + 2); + let child_record = latest_policy(&state, child.object_id()).await; + let (child_policy, _) = + super::super::policy::canonical_policy_record_identity(&child_record).unwrap(); + assert!(child_policy.network_policies["api"].endpoints[0].advisor_proposed); + } + + fn delete_request(name: &str) -> DeleteSandboxRequest { + DeleteSandboxRequest { + request_id: String::new(), + allow_missing: false, + name: name.to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), + } } - /// A lag warning carries no cursor, so it is never replayed on resume. Sent - /// after the surviving events of its own batch, a disconnect in between - /// leaves the client checkpointed past the dropped range having never been - /// told anything was dropped. The warning must lead the batch. - /// - /// Which branch `select!` takes is arbitrary, so the run is repeated: the - /// assertion holds on both paths, but only the platform-first path reaches - /// the drain's lag counter, which is where the ordering used to be wrong. - /// Eight attempts caught the unfixed ordering in three runs of five; forty - /// caught it in six of six. #[tokio::test] - async fn lag_warning_precedes_the_events_of_its_batch() { - use openshell_core::proto::sandbox_stream_event::Payload; - use tokio_stream::StreamExt as _; + async fn deleting_a_parent_with_live_children_is_refused() { + let state = child_sandboxes_state().await; + let lead_id = put_parent_record(&state, "lead", &[], None, false).await; + let link = openshell_core::proto::SandboxParent { + name: "lead".to_string(), + id: lead_id.clone(), + }; + put_parent_record(&state, "worker1", &[], Some(link.clone()), false).await; + put_parent_record(&state, "worker2", &[], Some(link), false).await; - /// `select!` polls the log receiver before the platform one in three of - /// its four rotations, and only the platform-first path reaches the - /// drain's lag counter. Repeat enough that missing it is negligible. - const ATTEMPTS: usize = 40; + let err = handle_delete_sandbox_inner(&state, authed_request(delete_request("lead"))) + .await + .unwrap_err(); + assert_eq!(err.code(), tonic::Code::FailedPrecondition); + assert!( + err.message() + .contains("sandbox 'lead' has 2 child sandboxes; delete them first"), + "{}", + err.message() + ); + let lead = state + .store + .get_message::(&lead_id) + .await + .unwrap() + .expect("the refused parent still exists"); + assert!( + !crate::compute::is_being_deleted(&lead), + "a refused delete must not mark the parent as deleting" + ); + } + /// A root and a child record on a gateway with child sandboxes off, as + /// left behind after the flag is turned off. + async fn lead_and_worker_with_children_off() -> (Arc, String, String) { let state = test_server_state().await; + assert!(!state.config.enable_child_sandboxes); + let lead_id = put_parent_record(&state, "lead", &[], None, false).await; + let link = openshell_core::proto::SandboxParent { + name: "lead".to_string(), + id: lead_id.clone(), + }; + let worker_id = put_parent_record(&state, "worker1", &[], Some(link), false).await; + (state, lead_id, worker_id) + } - for attempt in 0..ATTEMPTS { - let sandbox = test_sandbox(&format!("lagorder{attempt}"), Vec::new()); - state.store.put_message(&sandbox).await.unwrap(); - let id = sandbox.object_id().to_string(); + #[tokio::test] + async fn with_child_sandboxes_off_a_root_delete_skips_the_child_count() { + let (state, _, _) = lead_and_worker_with_children_off().await; - let response = handle_watch_sandbox( - &state, - authed_request(WatchSandboxRequest { - sandbox: sandbox.object_name().to_string(), - workspace_scope: Some(openshell_core::proto::workspace_selector("default")), - follow_logs: true, - follow_events: true, - ..Default::default() - }), - ) + handle_delete_sandbox_inner(&state, authed_request(delete_request("lead"))) .await - .unwrap(); - let mut stream = response.into_inner(); - let snap = stream.next().await.unwrap().unwrap(); - assert!(snap.cursor.is_empty()); - - // One platform event plus a log burst past the 1024-slot broadcast - // capacity, published without an await in between so the producer - // sees both on a single wake-up: a deliverable event and a drop. - seed_platform_event(&state, &id, "e1"); - seed_log_lines(&state, &id, 1100); - - let first = stream.next().await.unwrap().unwrap(); - assert!( - matches!(first.payload, Some(Payload::Warning(_))), - "the lag warning must arrive before any event of the lagged batch, got {:?}", - first.payload - ); - } + .expect("the delete does not count children"); } #[tokio::test] - async fn resume_at_latest_cursor_suppresses_duplicates() { - use tokio_stream::StreamExt as _; + async fn with_child_sandboxes_off_no_sync_copies_the_root_policy() { + let (state, lead_id, worker_id) = lead_and_worker_with_children_off().await; + put_policy_revision_with_status(&state, &lead_id, 2, &lead_policy(false), "loaded").await; - let state = test_server_state().await; - let sandbox = test_sandbox("nodup", Vec::new()); - state.store.put_message(&sandbox).await.unwrap(); - let id = sandbox.object_id().to_string(); + sync_children(&state, &lead_id).await.unwrap(); + sync_all_children(&state).await.unwrap(); - // Cursors 1,2,3; client already saw through 3. - seed_log_lines(&state, &id, 3); + assert_eq!(latest_policy(&state, &worker_id).await.version, 1); + assert!(!holds_parent_latest(&state, &worker_id, &lead_id).await); + } - let response = handle_watch_sandbox( + #[tokio::test] + async fn a_child_still_being_deleted_blocks_the_parent() { + let state = child_sandboxes_state().await; + let lead_id = put_parent_record(&state, "lead", &[], None, false).await; + let worker_id = put_parent_record( &state, - authed_request(WatchSandboxRequest { - sandbox: sandbox.object_name().to_string(), - workspace_scope: Some(openshell_core::proto::workspace_selector("default")), - follow_logs: true, - resume_after_cursor: cursor_token(&state, &id, 3), - ..Default::default() + "worker1", + &[], + Some(openshell_core::proto::SandboxParent { + name: "lead".to_string(), + id: lead_id, }), + true, ) - .await - .unwrap(); - - let mut stream = response.into_inner(); - let snap = stream.next().await.unwrap().unwrap(); - assert!(snap.cursor.is_empty()); + .await; - // No resumable events remain; the live loop yields nothing promptly. - let next = tokio::time::timeout(std::time::Duration::from_millis(200), stream.next()).await; + let err = handle_delete_sandbox_inner(&state, authed_request(delete_request("lead"))) + .await + .unwrap_err(); + assert_eq!(err.code(), tonic::Code::FailedPrecondition); assert!( - next.is_err(), - "expected no further events after resume at latest cursor, got {next:?}" + err.message().contains( + "sandbox 'lead' has 1 child sandbox still being deleted; \ + try again once they are gone" + ), + "{}", + err.message() ); + + state.store.delete("sandbox", &worker_id).await.unwrap(); + handle_delete_sandbox_inner(&state, authed_request(delete_request("lead"))) + .await + .expect("once the child is gone, the parent can be deleted"); } - #[tokio::test] - async fn resume_from_trimmed_cursor_terminates_out_of_range() { - use tokio_stream::StreamExt as _; + /// A root `lead` with one child `worker1`. Returns the child's id. + async fn put_lead_and_worker(state: &ServerState) -> String { + let lead_id = put_parent_record(state, "lead", &[], None, false).await; + let link = openshell_core::proto::SandboxParent { + name: "lead".to_string(), + id: lead_id, + }; + put_parent_record(state, "worker1", &[], Some(link), false).await + } - let state = test_server_state().await; - let sandbox = test_sandbox("gap", Vec::new()); - state.store.put_message(&sandbox).await.unwrap(); - let id = sandbox.object_id().to_string(); + fn default_scope() -> openshell_core::proto::WorkspaceSelector { + openshell_core::proto::workspace_selector("default".to_string()) + } - // Exceed the 2000-line tail so the earliest cursors are trimmed. - seed_log_lines(&state, &id, 2005); + /// A root `lead` with provider `work-github` and a child `worker1` created + /// through the API, so the child has the provider and a current copy of + /// the lead's v1. Returns both ids. + async fn lead_and_child_sharing_a_provider(state: &Arc) -> (String, String) { + state + .store + .put_message(&test_provider_with_credential_key( + "work-github", + "github", + "GITHUB_TOKEN", + )) + .await + .unwrap(); + let lead_id = put_parent_record(state, "lead", &["work-github"], None, false).await; + let worker = create_child(state, "worker1", "lead").await; + assert_eq!(worker.spec.as_ref().unwrap().providers, vec!["work-github"]); + (lead_id, worker.object_id().to_string()) + } - let response = handle_watch_sandbox( - &state, - authed_request(WatchSandboxRequest { - sandbox: sandbox.object_name().to_string(), - workspace_scope: Some(openshell_core::proto::workspace_selector("default")), - follow_logs: true, - // Seq 2 was trimmed; this is an unrecoverable gap. - resume_after_cursor: cursor_token(&state, &id, 2), - ..Default::default() + async fn sandbox_spec(state: &ServerState, sandbox_id: &str) -> SandboxSpec { + state + .store + .get_message::(sandbox_id) + .await + .unwrap() + .unwrap() + .spec + .unwrap() + } + + async fn detach_from_lead(state: &Arc, provider: &str) { + let response = handle_detach_sandbox_provider( + state, + authed_request(DetachSandboxProviderRequest { + request_id: String::new(), + sandbox: "lead".to_string(), + workspace_scope: Some(default_scope()), + provider: provider.to_string(), + expected_resource_version: 0, }), ) .await - .unwrap(); + .unwrap() + .into_inner(); + assert!(response.detached); + } - let mut stream = response.into_inner(); - // Snapshot still arrives first (fresh state), then the terminal gap status. - let snap = stream.next().await.unwrap().unwrap(); - assert!(snap.cursor.is_empty()); + /// A root `lead` with a child `worker1` sharing provider `work-github`, + /// whose `lead` record is then removed, as a downgraded gateway can leave + /// it. Returns both ids. + async fn orphaned_child(state: &Arc) -> (String, String) { + let (lead_id, worker_id) = lead_and_child_sharing_a_provider(state).await; + state + .store + .delete(Sandbox::object_type(), &lead_id) + .await + .unwrap(); + (lead_id, worker_id) + } - let err = stream - .next() + #[tokio::test] + async fn an_orphaned_child_is_served_configuration_without_providers() { + let state = child_sandboxes_state().await; + let (_, worker_id) = orphaned_child(&state).await; + let worker = sandbox_record(&state, &worker_id).await; + + let inputs = super::super::policy::load_sandbox_config_inputs(&state, worker.clone()) .await - .unwrap() - .expect_err("trimmed cursor must terminate the stream"); - assert_eq!(err.code(), tonic::Code::OutOfRange, "{err:?}"); + .unwrap(); + assert!(inputs.sandbox().spec.as_ref().unwrap().providers.is_empty()); + assert!(delivered_variables(&state, &worker).await.is_empty()); + let config = child_config(&state, &worker_id).await; assert!( - err.message().contains('2'), - "gap status should report the requested cursor: {}", - err.message() + config.configuration_admitted, + "{}", + config.configuration_error ); - - // Stream ends after the terminal status. - assert!(stream.next().await.is_none()); } - /// The guard behind the producer's post-replay epoch re-check. - /// - /// Validation and the two `tail_after` reads take their locks separately, so - /// a teardown plus a republish can swap the space in between and leave the - /// reads applying an old seq to a replacement's buffers -- `tail_after` only - /// compares numbers, so it reports no gap while skipping every replacement - /// event at or below that seq. The producer re-checks the epoch once both - /// tails are in hand and before emitting anything; this pins what that check - /// must answer. - /// - /// The interleaving itself is not reachable from a test: the producer runs - /// validation, both reads, and the re-check with no await in between, so - /// there is nothing to suspend it on. #[tokio::test] - async fn cursor_space_is_rejects_a_replacement_space() { - let state = test_server_state().await; - let sandbox = test_sandbox("respace", Vec::new()); - state.store.put_message(&sandbox).await.unwrap(); - let id = sandbox.object_id().to_string(); - - seed_log_lines(&state, &id, 1); - let original = state.tracing_log_bus.cursor_space(&id).unwrap().epoch; - assert!(cursor_space_is(&state, &id, original)); + async fn the_scan_leaves_an_orphaned_child_running() { + let state = child_sandboxes_state().await; + let (_, worker_id) = orphaned_child(&state).await; + let mut running = sandbox_record(&state, &worker_id).await; + running.set_phase(SandboxPhase::Ready as i32); + state.store.put_message(&running).await.unwrap(); + let before = latest_policy(&state, &worker_id).await; - // Teardown alone leaves no space to point into. - state.tracing_log_bus.remove(&id); - assert!(state.tracing_log_bus.cursor_space(&id).is_none()); - assert!(!cursor_space_is(&state, &id, original)); + sync_all_children(&state).await.unwrap(); - // The republish installs a replacement renumbered from 1. Its seqs - // overlap the retired space's, so only the epoch separates them. - seed_log_lines(&state, &id, 1); - let replacement = state.tracing_log_bus.cursor_space(&id).unwrap(); - assert_ne!(replacement.epoch, original); - assert_eq!(replacement.highest_seq, 1); - assert!(!cursor_space_is(&state, &id, original)); - assert!(cursor_space_is(&state, &id, replacement.epoch)); + let worker = sandbox_record(&state, &worker_id).await; + assert_eq!( + SandboxPhase::try_from(worker.phase()).unwrap(), + SandboxPhase::Ready + ); + assert_eq!( + latest_policy(&state, &worker_id).await.version, + before.version + ); } #[tokio::test] - async fn resume_from_reset_cursor_space_terminates_out_of_range() { - use tokio_stream::StreamExt as _; + async fn a_new_root_under_the_old_name_does_not_adopt_an_orphan() { + let state = child_sandboxes_state().await; + let (_, worker_id) = orphaned_child(&state).await; + let before = latest_policy(&state, &worker_id).await; + let new_lead_id = put_parent_record(&state, "lead", &[], None, false).await; + put_policy_revision_with_status(&state, &new_lead_id, 2, &lead_policy(false), "loaded") + .await; - let state = test_server_state().await; - let sandbox = test_sandbox("reset", Vec::new()); - state.store.put_message(&sandbox).await.unwrap(); - let id = sandbox.object_id().to_string(); + sync_children(&state, &new_lead_id).await.unwrap(); + sync_all_children(&state).await.unwrap(); - // The reported repro. Before cursors carried an epoch, a bare number - // was all the server had: 2 <= 3 passed the old "is this plausible?" - // bound, the tail replayed only seq 3, and the new space's seqs 1 and 2 - // -- real, unseen events -- were silently swallowed as duplicates. - seed_log_lines(&state, &id, 2); - let retired_cursor = cursor_token(&state, &id, 2); + let after = latest_policy(&state, &worker_id).await; + assert_eq!(after.version, before.version, "nothing is copied"); + } - // Teardown retires the space; the next publish starts over at seq 1, - // indistinguishable by number from the client's view of a restart. - state.tracing_log_bus.remove(&id); - seed_log_lines(&state, &id, 3); + fn list_children_request( + parent: &str, + page_size: i32, + page_token: String, + ) -> ListSandboxesRequest { + ListSandboxesRequest { + page_size, + page_token, + label_selector: String::new(), + parent: parent.to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), + } + } - let response = handle_watch_sandbox( + fn listed_names(response: &ListSandboxesResponse) -> Vec<&str> { + response + .sandboxes + .iter() + .map(ObjectName::object_name) + .collect() + } + + #[tokio::test] + async fn a_parent_filter_pages_through_only_that_parents_children() { + let state = child_sandboxes_state().await; + // Store order is creation time, then name: a-lead, b, c, d, e-other. + let lead_id = put_parent_record(&state, "a-lead", &[], None, false).await; + let link = openshell_core::proto::SandboxParent { + name: "a-lead".to_string(), + id: lead_id, + }; + for name in ["b-child", "c-child", "d-child"] { + put_parent_record(&state, name, &[], Some(link.clone()), false).await; + } + put_parent_record(&state, "e-other", &[], None, false).await; + + // Store pages of two are [a-lead, b-child] [c-child, d-child] + // [e-other], so the first response fills on c-child, partway through + // the second store page; d-child must still come next. + let first = handle_list_sandboxes( &state, - authed_request(WatchSandboxRequest { - sandbox: sandbox.object_name().to_string(), - workspace_scope: Some(openshell_core::proto::workspace_selector("default")), - follow_logs: true, - resume_after_cursor: retired_cursor, - ..Default::default() - }), + authed_request(list_children_request("a-lead", 2, String::new())), + ) + .await + .unwrap() + .into_inner(); + assert_eq!(listed_names(&first), ["b-child", "c-child"]); + assert!(!first.next_page_token.is_empty()); + + let second = handle_list_sandboxes( + &state, + authed_request(list_children_request("a-lead", 2, first.next_page_token)), + ) + .await + .unwrap() + .into_inner(); + assert_eq!(listed_names(&second), ["d-child"]); + assert!(second.next_page_token.is_empty()); + } + + #[tokio::test] + async fn a_parent_filter_does_not_list_an_old_roots_orphans() { + let state = child_sandboxes_state().await; + orphaned_child(&state).await; + put_parent_record(&state, "lead", &[], None, false).await; + + let listed = handle_list_sandboxes( + &state, + authed_request(list_children_request("lead", 100, String::new())), ) .await - .unwrap(); + .unwrap() + .into_inner(); + assert!(listed.sandboxes.is_empty()); + } - let mut stream = response.into_inner(); - let snap = stream.next().await.unwrap().unwrap(); - assert!(snap.cursor.is_empty()); + #[tokio::test] + async fn a_sandbox_caller_lists_only_its_own_children_whatever_it_asks_for() { + let state = child_sandboxes_state().await; + let lead_id = put_parent_record(&state, "lead", &[], None, false).await; + let other_id = put_parent_record(&state, "other", &[], None, false).await; + for (name, parent, id) in [ + ("w1", "lead", &lead_id), + ("w2", "lead", &lead_id), + ("x1", "other", &other_id), + ] { + let link = openshell_core::proto::SandboxParent { + name: parent.to_string(), + id: id.clone(), + }; + put_parent_record(&state, name, &[], Some(link), false).await; + } - let item = stream - .next() + // Another root's name and every workspace are both ignored. + let mut request = list_children_request("other", 100, String::new()); + request.workspace_scope = Some(openshell_core::proto::all_workspaces_selector()); + let listed = handle_list_sandboxes(&state, sandbox_request(&lead_id, request)) .await .unwrap() - .expect_err("a cursor from a retired space must terminate the stream"); - assert_eq!(item.code(), tonic::Code::OutOfRange, "{item:?}"); - assert!( - item.message().contains("empty resume_after_cursor"), - "status must tell the client to restart without a cursor, not retry: {}", - item.message() - ); + .into_inner(); + assert_eq!(listed_names(&listed), ["w1", "w2"]); + } - // Nothing from the new space may be delivered before the error: a - // partial stream would read as "here is everything after your cursor". - assert!(stream.next().await.is_none()); + /// Call an MCP tool as the sandbox `caller_id`, through the real gRPC + /// stack and handlers, and return the tool result. + async fn call_mcp_tool( + state: &Arc, + caller_id: &str, + tool: &str, + arguments: serde_json::Value, + ) -> serde_json::Value { + call_mcp_as( + state, + sandbox_caller(caller_id), + None, + None, + tool, + arguments, + ) + .await } - #[tokio::test] - async fn resume_from_reset_cursor_space_rejected_when_new_space_is_shorter() { - use tokio_stream::StreamExt as _; + fn sandbox_caller(sandbox_id: &str) -> crate::auth::principal::Principal { + use crate::auth::principal::{Principal, SandboxIdentitySource, SandboxPrincipal}; - let state = test_server_state().await; - let sandbox = test_sandbox("reset-short", Vec::new()); - state.store.put_message(&sandbox).await.unwrap(); - let id = sandbox.object_id().to_string(); + Principal::Sandbox(SandboxPrincipal { + sandbox_id: sandbox_id.to_string(), + source: SandboxIdentitySource::BootstrapJwt { + issuer: "openshell-gateway:test".to_string(), + auth_epoch: None, + }, + trust_domain: Some("openshell".to_string()), + }) + } - // The shape the old numeric bound did catch (5 > 2), kept so it keeps - // passing -- but now it fails for the reason that generalizes. - seed_log_lines(&state, &id, 5); - let retired_cursor = cursor_token(&state, &id, 5); - state.tracing_log_bus.remove(&id); - seed_log_lines(&state, &id, 2); + /// Call one MCP tool as `caller` through the real router and handlers, + /// with an RBAC policy and a bridge workspace header when given. + async fn call_mcp_as( + state: &Arc, + caller: crate::auth::principal::Principal, + authz_policy: Option, + workspace: Option<&str>, + tool: &str, + arguments: serde_json::Value, + ) -> serde_json::Value { + let body = serde_json::json!({ + "jsonrpc": "2.0", "id": 1, "method": "tools/call", + "params": {"name": tool, "arguments": arguments}, + }); + post_mcp_as(state, caller, authz_policy, workspace, body).await["result"].clone() + } - let response = handle_watch_sandbox( - &state, - authed_request(WatchSandboxRequest { - sandbox: sandbox.object_name().to_string(), - workspace_scope: Some(openshell_core::proto::workspace_selector("default")), - follow_logs: true, - resume_after_cursor: retired_cursor, - ..Default::default() - }), + /// Post one JSON-RPC message to `/mcp` as `caller` through the real + /// router and handlers, and return the whole reply. + async fn post_mcp_as( + state: &Arc, + caller: crate::auth::principal::Principal, + authz_policy: Option, + workspace: Option<&str>, + body: serde_json::Value, + ) -> serde_json::Value { + use crate::auth::authenticator::test_support::MockAuthenticator; + use crate::auth::authenticator::{Authentication, AuthenticatorChain}; + use tower::ServiceExt; + + let chain = AuthenticatorChain::new(vec![Arc::new(MockAuthenticator::returning(Ok( + Authentication::Accepted(caller), + )))]); + let stack = crate::multiplex::AuthGrpcRouter::new( + openshell_core::proto::open_shell_server::OpenShellServer::new( + crate::OpenShellService::new(state.clone()), + ), + Some(chain), + authz_policy, + ); + let connection = crate::mcp::McpConnection::new(stack.caller_authenticator(), stack) + .with_short_create_wait() + .with_store(state.store.clone()); + let mut request = http::Request::post("/mcp") + .header("content-type", "application/json") + .header("authorization", "Bearer caller-token"); + if let Some(workspace) = workspace { + request = request.header("x-openshell-workspace", workspace); + } + let response = crate::mcp::router() + .layer(axum::Extension(connection)) + .oneshot( + request + .body(axum::body::Body::from(body.to_string())) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(response.status(), http::StatusCode::OK); + let reply: serde_json::Value = serde_json::from_slice( + &axum::body::to_bytes(response.into_body(), usize::MAX) + .await + .unwrap(), ) - .await .unwrap(); - - let mut stream = response.into_inner(); - assert!(stream.next().await.unwrap().unwrap().cursor.is_empty()); - let err = stream.next().await.unwrap().expect_err("out of range"); - assert_eq!(err.code(), tonic::Code::OutOfRange, "{err:?}"); - assert!(stream.next().await.is_none()); + reply } #[tokio::test] - async fn resume_from_reset_cursor_space_rejected_when_seq_is_within_new_range() { - use tokio_stream::StreamExt as _; + async fn mcp_list_reaches_the_handler_through_the_grpc_stack() { + let state = child_sandboxes_state().await; + let lead_id = put_parent_record(&state, "lead", &[], None, false).await; + let link = openshell_core::proto::SandboxParent { + name: "lead".to_string(), + id: lead_id.clone(), + }; + put_parent_record(&state, "w1", &[], Some(link), false).await; - let state = test_server_state().await; - let sandbox = test_sandbox("reset-within", Vec::new()); + let result = call_mcp_tool(&state, &lead_id, "list", serde_json::json!({})).await; + assert_eq!(result["isError"], false, "{result}"); + let names: Vec<_> = result["structuredContent"]["sandboxes"] + .as_array() + .unwrap() + .iter() + .map(|child| child["name"].as_str().unwrap()) + .collect(); + assert_eq!(names, ["w1"]); + } + + /// Record the OIDC user `subject` as the creator of sandbox `id`. + async fn set_creator(state: &ServerState, id: &str, subject: &str) { + set_creator_from(state, id, subject, "oidc").await; + } + + async fn set_creator_from(state: &ServerState, id: &str, subject: &str, provider: &str) { + let mut sandbox = state + .store + .get_message::(id) + .await + .unwrap() + .unwrap(); + sandbox.created_on_behalf_of = Some(openshell_core::proto::UserRef { + subject: subject.to_string(), + identity_provider: provider.to_string(), + }); state.store.put_message(&sandbox).await.unwrap(); - let id = sandbox.object_id().to_string(); + } - // Seq 1 sits comfortably inside the new space's 1..=3, so every numeric - // bound accepts it. Only the epoch distinguishes the two spaces. This is - // the assertion the pre-fix design structurally could not make. - seed_log_lines(&state, &id, 3); - let retired_cursor = cursor_token(&state, &id, 1); - state.tracing_log_bus.remove(&id); - seed_log_lines(&state, &id, 3); + async fn put_member(state: &ServerState, subject: &str) { + state + .store + .put_message(&openshell_core::proto::WorkspaceMember { + metadata: Some(ObjectMeta { + id: uuid::Uuid::new_v4().to_string(), + name: subject.to_string(), + workspace: "default".to_string(), + ..Default::default() + }), + principal_subject: subject.to_string(), + role: openshell_core::proto::WorkspaceRole::User.into(), + }) + .await + .unwrap(); + } - let response = handle_watch_sandbox( - &state, - authed_request(WatchSandboxRequest { - sandbox: sandbox.object_name().to_string(), - workspace_scope: Some(openshell_core::proto::workspace_selector("default")), - follow_logs: true, - resume_after_cursor: retired_cursor, - ..Default::default() - }), - ) - .await - .unwrap(); + /// A root created by a workspace member, ready to create children. + async fn member_root(state: &Arc, name: &str, providers: &[&str]) -> String { + let id = put_parent_record(state, name, providers, None, false).await; + put_member(state, "alice").await; + set_creator(state, &id, "alice").await; + id + } - let mut stream = response.into_inner(); - assert!(stream.next().await.unwrap().unwrap().cursor.is_empty()); - let err = stream.next().await.unwrap().expect_err("out of range"); - assert_eq!(err.code(), tonic::Code::OutOfRange, "{err:?}"); - assert!(stream.next().await.is_none()); + fn sandbox_child_request(name: &str) -> CreateSandboxRequest { + CreateSandboxRequest { + name: name.to_string(), + spec: Some(SandboxSpec::default()), + ..Default::default() + } } - #[tokio::test] - async fn resume_after_remove_without_republish_terminates_out_of_range() { - use tokio_stream::StreamExt as _; + fn quantities(pairs: &[(&str, &str)]) -> Value { + let fields = pairs + .iter() + .map(|(name, quantity)| { + let value = Value { + kind: Some(Kind::StringValue((*quantity).to_string())), + }; + ((*name).to_string(), value) + }) + .collect(); + Value { + kind: Some(Kind::StructValue(Struct { fields })), + } + } - let state = test_server_state().await; - let sandbox = test_sandbox("reset-empty", Vec::new()); - state.store.put_message(&sandbox).await.unwrap(); - let id = sandbox.object_id().to_string(); + fn resources(sections: &[(&str, Value)]) -> Struct { + Struct { + fields: sections + .iter() + .map(|(section, value)| ((*section).to_string(), value.clone())) + .collect(), + } + } - // No space at all: nothing has been published since teardown. The buses - // look merely empty, so `tail_after` reports no gap -- "caught up" would - // be the wrong reading, because the client's events are gone. - seed_log_lines(&state, &id, 3); - let retired_cursor = cursor_token(&state, &id, 3); - state.tracing_log_bus.remove(&id); + /// Give the root a template, as `sandbox create --from` would. + async fn set_root_template(state: &Arc, id: &str, template: SandboxTemplate) { + let mut root = state + .store + .get_message::(id) + .await + .unwrap() + .unwrap(); + root.spec.as_mut().unwrap().template = Some(template); + state.store.put_message(&root).await.unwrap(); + } - let response = handle_watch_sandbox( + fn isolated_template() -> SandboxTemplate { + SandboxTemplate { + image: "registry.example.com/lead:1".to_string(), + runtime_class_name: "gvisor".to_string(), + user_namespaces: Some(true), + ..Default::default() + } + } + + #[tokio::test] + async fn a_sandbox_caller_child_copies_image_cpu_memory_and_isolation_only() { + let state = child_sandboxes_state().await; + let lead_id = member_root(&state, "lead", &[]).await; + let mut lead = state + .store + .get_message::(&lead_id) + .await + .unwrap() + .unwrap(); + let lead_resources = resources(&[ + ( + "limits", + quantities(&[("cpu", "2"), ("memory", "4Gi"), ("nvidia.com/gpu", "1")]), + ), + ( + "requests", + quantities(&[("cpu", "1"), ("example.com/fpga", "1")]), + ), + ("claims", quantities(&[("gpu", "a100")])), + ]); + let spec = lead.spec.as_mut().unwrap(); + spec.template = Some(SandboxTemplate { + resources: Some(lead_resources), + labels: HashMap::from([("team".to_string(), "a".to_string())]), + agent_socket: "/run/agent.sock".to_string(), + ..isolated_template() + }); + spec.resource_requirements = Some(ResourceRequirements { + gpu: Some(GpuResourceRequirements { count: Some(1) }), + }); + spec.environment = HashMap::from([("SECRET_MODE".to_string(), "on".to_string())]); + lead.metadata.as_mut().unwrap().labels = + HashMap::from([("team".to_string(), "a".to_string())]); + state.store.put_message(&lead).await.unwrap(); + + let child = handle_create_sandbox( &state, - authed_request(WatchSandboxRequest { - sandbox: sandbox.object_name().to_string(), - workspace_scope: Some(openshell_core::proto::workspace_selector("default")), - follow_logs: true, - resume_after_cursor: retired_cursor, - ..Default::default() - }), + sandbox_request(&lead_id, sandbox_child_request("worker")), ) .await + .unwrap() + .into_inner() + .sandbox .unwrap(); - let mut stream = response.into_inner(); - assert!(stream.next().await.unwrap().unwrap().cursor.is_empty()); - let err = stream.next().await.unwrap().expect_err("out of range"); - assert_eq!(err.code(), tonic::Code::OutOfRange, "{err:?}"); - assert!(stream.next().await.is_none()); + assert_eq!(child.parent.as_ref().unwrap().id, lead_id); + assert_eq!(child.object_workspace(), "default"); + let spec = child.spec.as_ref().unwrap(); + let template = spec.template.as_ref().unwrap(); + assert_eq!(template.image, "registry.example.com/lead:1"); + assert_eq!( + template.resources, + Some(resources(&[ + ("limits", quantities(&[("cpu", "2"), ("memory", "4Gi")])), + ("requests", quantities(&[("cpu", "1")])), + ])), + "only CPU and memory are copied" + ); + assert_eq!(template.runtime_class_name, "gvisor"); + assert_eq!(template.user_namespaces, Some(true)); + assert!(template.labels.is_empty()); + assert!(template.agent_socket.is_empty()); + assert!(spec.resource_requirements.is_none(), "no GPU is copied"); + assert!(spec.environment.is_empty()); + assert!(child.metadata.as_ref().unwrap().labels.is_empty()); + } + + #[tokio::test] + async fn a_sandbox_caller_may_set_only_name_template_and_providers() { + let state = child_sandboxes_state().await; + let lead_id = member_root(&state, "lead", &[]).await; + let with_spec = |spec: SandboxSpec| CreateSandboxRequest { + spec: Some(spec), + ..sandbox_child_request("worker") + }; + for (request, field) in [ + ( + CreateSandboxRequest { + workspace_scope: Some(openshell_core::proto::workspace_selector( + "other".to_string(), + )), + ..sandbox_child_request("worker") + }, + "workspace_scope", + ), + ( + CreateSandboxRequest { + parent: "lead".to_string(), + ..sandbox_child_request("worker") + }, + "parent", + ), + ( + CreateSandboxRequest { + labels: HashMap::from([("a".to_string(), "b".to_string())]), + ..sandbox_child_request("worker") + }, + "labels", + ), + ( + with_spec(SandboxSpec { + template: Some(SandboxTemplate { + image: "evil".to_string(), + ..Default::default() + }), + ..Default::default() + }), + "spec.template", + ), + ( + with_spec(SandboxSpec { + environment: HashMap::from([("A".to_string(), "b".to_string())]), + ..Default::default() + }), + "spec.environment", + ), + ( + with_spec(SandboxSpec { + command: vec!["sh".to_string()], + ..Default::default() + }), + "spec.command", + ), + ( + with_spec(SandboxSpec { + policy: Some(openshell_policy::restrictive_default_policy()), + ..Default::default() + }), + "spec.policy", + ), + ] { + let err = handle_create_sandbox(&state, sandbox_request(&lead_id, request)) + .await + .unwrap_err(); + assert_eq!(err.code(), tonic::Code::InvalidArgument, "{field}"); + assert_eq!( + err.message(), + format!("field '{field}' is not allowed for sandbox callers") + ); + } + } + + #[test] + fn the_backstop_refuses_fields_the_named_checks_miss() { + // Checked on its own, as for a field added to the request later. + let allowed = CreateSandboxRequest { + spec: Some(SandboxSpec { + providers: vec!["github".to_string()], + ..Default::default() + }), + workload_template: "agents".to_string(), + ..sandbox_child_request("worker") + }; + refuse_unlisted_fields_for_sandbox_caller(&allowed).unwrap(); + for request in [ + CreateSandboxRequest { + request_id: "r1".to_string(), + ..allowed.clone() + }, + CreateSandboxRequest { + spec: Some(SandboxSpec { + resource_requirements: Some(ResourceRequirements { + gpu: Some(GpuResourceRequirements { count: Some(1) }), + }), + ..Default::default() + }), + ..allowed + }, + ] { + let err = refuse_unlisted_fields_for_sandbox_caller(&request).unwrap_err(); + assert_eq!(err.code(), tonic::Code::InvalidArgument); + assert_eq!( + err.message(), + "the request sets fields that are not allowed for sandbox callers" + ); + } } #[tokio::test] - async fn resume_with_cursor_from_another_sandbox_terminates_out_of_range() { - use tokio_stream::StreamExt as _; - - let state = test_server_state().await; - let a = test_sandbox("epoch-a", Vec::new()); - let b = test_sandbox("epoch-b", Vec::new()); - state.store.put_message(&a).await.unwrap(); - state.store.put_message(&b).await.unwrap(); - let a_id = a.object_id().to_string(); - let b_id = b.object_id().to_string(); - - // Epochs are per sandbox, not per process. A token valid for A must not - // address B's space, even though both are on seq 1..=3 right now. - seed_log_lines(&state, &a_id, 3); - seed_log_lines(&state, &b_id, 3); - let a_cursor = cursor_token(&state, &a_id, 1); + async fn a_sandbox_caller_uses_only_templates_made_available_to_agents() { + let state = child_sandboxes_state().await; + let lead_id = member_root(&state, "lead", &[]).await; + let put_template = |name: &str, labelled: bool, driver_config: bool| { + let mut template = test_workload_template(name); + let metadata = template.metadata.as_mut().unwrap(); + metadata.id = uuid::Uuid::new_v4().to_string(); + metadata.workspace = "default".to_string(); + if labelled { + metadata + .labels + .insert(AGENT_USABLE_TEMPLATE_LABEL.to_string(), "true".to_string()); + } + if driver_config { + template.spec.as_mut().unwrap().driver_config = Some(Struct::default()); + } + let state = state.clone(); + async move { state.store.put_message(&template).await.unwrap() } + }; + put_template("agents", true, false).await; + put_template("unlabelled", false, false).await; + put_template("driver", true, true).await; + let from_template = |name: &str, template: &str| CreateSandboxRequest { + workload_template: template.to_string(), + ..sandbox_child_request(name) + }; - let response = handle_watch_sandbox( + let child = handle_create_sandbox( &state, - authed_request(WatchSandboxRequest { - sandbox: b.object_name().to_string(), - workspace_scope: Some(openshell_core::proto::workspace_selector("default")), - follow_logs: true, - resume_after_cursor: a_cursor, - ..Default::default() - }), + sandbox_request(&lead_id, from_template("w1", "agents")), ) .await + .unwrap() + .into_inner() + .sandbox .unwrap(); + let template = child.spec.as_ref().unwrap().template.as_ref().unwrap(); + assert_eq!(template.image, "registry.example.com/agent:latest"); - let mut stream = response.into_inner(); - assert!(stream.next().await.unwrap().unwrap().cursor.is_empty()); - let err = stream.next().await.unwrap().expect_err("out of range"); - assert_eq!(err.code(), tonic::Code::OutOfRange, "{err:?}"); - assert!(stream.next().await.is_none()); - } - - #[tokio::test] - async fn resume_with_cursor_ahead_of_the_space_terminates_out_of_range() { - use tokio_stream::StreamExt as _; - - let state = test_server_state().await; - let sandbox = test_sandbox("ahead", Vec::new()); - state.store.put_message(&sandbox).await.unwrap(); - let id = sandbox.object_id().to_string(); - - seed_log_lines(&state, &id, 2); - // Right epoch, but a seq this space has never issued: only a fabricated - // token gets here. Accepting it would pin the cutoff above every future - // event and stall the stream silently. - let ahead = cursor_token(&state, &id, 99); - - let response = handle_watch_sandbox( + // A template child still runs with the root's isolation settings. + set_root_template(&state, &lead_id, isolated_template()).await; + let child = handle_create_sandbox( &state, - authed_request(WatchSandboxRequest { - sandbox: sandbox.object_name().to_string(), - workspace_scope: Some(openshell_core::proto::workspace_selector("default")), - follow_logs: true, - resume_after_cursor: ahead, - ..Default::default() - }), + sandbox_request(&lead_id, from_template("w3", "agents")), ) .await + .unwrap() + .into_inner() + .sandbox .unwrap(); + let template = child.spec.as_ref().unwrap().template.as_ref().unwrap(); + assert_eq!(template.image, "registry.example.com/agent:latest"); + assert_eq!(template.runtime_class_name, "gvisor"); + assert_eq!(template.user_namespaces, Some(true)); - let mut stream = response.into_inner(); - assert!(stream.next().await.unwrap().unwrap().cursor.is_empty()); - let err = stream.next().await.unwrap().expect_err("out of range"); - assert_eq!(err.code(), tonic::Code::OutOfRange, "{err:?}"); - assert!(stream.next().await.is_none()); + for name in ["unlabelled", "driver", "missing"] { + let err = + handle_create_sandbox(&state, sandbox_request(&lead_id, from_template("w2", name))) + .await + .unwrap_err(); + assert_eq!(err.code(), tonic::Code::FailedPrecondition, "{name}"); + assert_eq!( + err.message(), + format!("template '{name}' is not available to agents") + ); + } } - #[tokio::test] - async fn resume_with_malformed_cursor_rejects_invalid_argument() { - let state = test_server_state().await; - let sandbox = test_sandbox("malformed", Vec::new()); - state.store.put_message(&sandbox).await.unwrap(); - let id = sandbox.object_id().to_string(); - - seed_log_lines(&state, &id, 3); - - // Input validation, so it fails the RPC before any stream exists rather - // than arriving as the first item of an apparently-healthy stream. - for raw in ["5", "v1:not-a-uuid:0", &foreign_cursor(1)[..40]] { - let err = handle_watch_sandbox( - &state, - authed_request(WatchSandboxRequest { - sandbox: sandbox.object_name().to_string(), - workspace_scope: Some(openshell_core::proto::workspace_selector("default")), - follow_logs: true, - resume_after_cursor: raw.to_string(), - ..Default::default() - }), - ) - .await - .expect_err("malformed cursor must fail the call"); - assert_eq!(err.code(), tonic::Code::InvalidArgument, "{raw:?}: {err:?}"); - assert!( - !err.message().contains(raw), - "status must not echo the client token: {}", - err.message() - ); + /// Store a template in `workspace`, labelled for agents when `labelled`, + /// with driver configuration when `driver_config`. + async fn put_agent_template( + state: &Arc, + workspace: &str, + name: &str, + labelled: bool, + driver_config: bool, + ) { + let mut template = test_workload_template(name); + let metadata = template.metadata.as_mut().unwrap(); + metadata.id = uuid::Uuid::new_v4().to_string(); + metadata.workspace = workspace.to_string(); + if labelled { + metadata + .labels + .insert(AGENT_USABLE_TEMPLATE_LABEL.to_string(), "true".to_string()); } + if driver_config { + template.spec.as_mut().unwrap().driver_config = Some(Struct::default()); + } + state.store.put_message(&template).await.unwrap(); } #[tokio::test] - async fn resume_with_foreign_epoch_terminates_out_of_range() { - use tokio_stream::StreamExt as _; - - let state = test_server_state().await; - let sandbox = test_sandbox("foreign", Vec::new()); - state.store.put_message(&sandbox).await.unwrap(); - let id = sandbox.object_id().to_string(); + async fn a_sandbox_caller_lists_only_templates_made_available_to_agents() { + let state = child_sandboxes_state().await; + let lead_id = member_root(&state, "lead", &[]).await; + put_agent_template(&state, "default", "agents", true, false).await; + put_agent_template(&state, "default", "unlabelled", false, false).await; + put_agent_template(&state, "default", "driver", true, true).await; + put_agent_template(&state, "other", "elsewhere", true, false).await; + + // Whatever scope or selector the request names. + let request = ListSandboxTemplatesRequest { + workspace_scope: Some(openshell_core::proto::all_workspaces_selector()), + label_selector: "team=runtime".to_string(), + ..Default::default() + }; + let listed = handle_list_sandbox_templates(&state, sandbox_request(&lead_id, request)) + .await + .unwrap() + .into_inner(); + let names: Vec<&str> = listed + .templates + .iter() + .map(ObjectName::object_name) + .collect(); + assert_eq!(names, ["agents"]); + let workload = listed.templates[0] + .spec + .as_ref() + .unwrap() + .workload + .as_ref() + .unwrap(); + assert_eq!(workload.image, "registry.example.com/agent:latest"); + assert!(workload.environment.is_empty(), "environment is withheld"); + } - seed_log_lines(&state, &id, 3); + #[tokio::test] + async fn mcp_tools_list_offers_a_sandbox_its_agent_templates() { + let state = child_sandboxes_state().await; + let lead_id = member_root(&state, "lead", &[]).await; + put_agent_template(&state, "default", "agents", true, false).await; + put_agent_template(&state, "default", "unlabelled", false, false).await; - // Well-formed, so it clears input validation, but from an epoch this - // gateway never minted -- the shape a reconnect to another replica - // takes. - let response = handle_watch_sandbox( + let reply = post_mcp_as( &state, - authed_request(WatchSandboxRequest { - sandbox: sandbox.object_name().to_string(), - workspace_scope: Some(openshell_core::proto::workspace_selector("default")), - follow_logs: true, - resume_after_cursor: foreign_cursor(1), + sandbox_caller(&lead_id), + None, + None, + serde_json::json!({"jsonrpc": "2.0", "id": 1, "method": "tools/list"}), + ) + .await; + let create = reply["result"]["tools"] + .as_array() + .unwrap() + .iter() + .find(|tool| tool["name"] == "create_sandbox") + .unwrap(); + let template = &create["inputSchema"]["properties"]["template"]; + assert_eq!(template["enum"], serde_json::json!(["agents"]), "{create}"); + let description = create["description"].as_str().unwrap(); + assert!( + description.contains("agents (image registry.example.com/agent:latest)"), + "{description}" + ); + assert!(!description.contains("unlabelled"), "{description}"); + } + + #[test] + fn a_child_keeps_isolation_its_template_asked_for() { + let plain_root = Sandbox { + spec: Some(SandboxSpec { + template: Some(SandboxTemplate::default()), ..Default::default() }), - ) - .await - .unwrap(); + ..Default::default() + }; + let mut child = isolated_template(); + copy_isolation_from_caller(&plain_root, &mut child); + assert_eq!(child.runtime_class_name, "gvisor"); + assert_eq!(child.user_namespaces, Some(true)); - let mut stream = response.into_inner(); - assert!(stream.next().await.unwrap().unwrap().cursor.is_empty()); - let err = stream.next().await.unwrap().expect_err("out of range"); - assert_eq!(err.code(), tonic::Code::OutOfRange, "{err:?}"); - assert!(stream.next().await.is_none()); + let kata_root = Sandbox { + spec: Some(SandboxSpec { + template: Some(SandboxTemplate { + runtime_class_name: "kata".to_string(), + user_namespaces: Some(false), + ..Default::default() + }), + ..Default::default() + }), + ..Default::default() + }; + let mut child = isolated_template(); + copy_isolation_from_caller(&kata_root, &mut child); + assert_eq!(child.runtime_class_name, "kata", "the root's class wins"); + assert_eq!(child.user_namespaces, Some(true), "never turned off"); } #[tokio::test] - async fn watch_delivers_each_event_once_during_init_race() { - use tokio_stream::StreamExt as _; - - let state = test_server_state().await; - let sandbox = test_sandbox("race", Vec::new()); - state.store.put_message(&sandbox).await.unwrap(); - let id = sandbox.object_id().to_string(); - - // Seed events that land in the tail before the watch subscribes. - seed_log_lines(&state, &id, 5); + async fn a_root_with_driver_config_cannot_create_children_over_mcp() { + let state = child_sandboxes_state().await; + let lead_id = member_root(&state, "lead", &[]).await; + set_root_template( + &state, + &lead_id, + SandboxTemplate { + driver_config: Some(Struct::default()), + ..isolated_template() + }, + ) + .await; - let response = handle_watch_sandbox( + let err = handle_create_sandbox( &state, - authed_request(WatchSandboxRequest { - sandbox: sandbox.object_name().to_string(), - workspace_scope: Some(openshell_core::proto::workspace_selector("default")), - follow_logs: true, - ..Default::default() - }), + sandbox_request(&lead_id, sandbox_child_request("worker")), ) .await - .unwrap(); + .unwrap_err(); + assert_eq!(err.code(), tonic::Code::FailedPrecondition); + assert_eq!( + err.message(), + "this sandbox has driver configuration, which children cannot copy" + ); + } - // Publish more concurrently with producer initialization. Some of these - // can land after the broadcast subscription but before the tail read, - // putting them in both replay and the live receiver. - for i in 5..15 { - state - .tracing_log_bus - .publish_external(openshell_core::proto::SandboxLogLine { - sandbox_id: id.clone(), - event_time: openshell_core::time::timestamp_from_millis(i64::from(i)).ok(), - level: "INFO".to_string(), - target: "test".to_string(), - message: format!("line {i}"), - source: "gateway".to_string(), - ..Default::default() - }); - } + #[tokio::test] + async fn a_sandbox_caller_child_may_not_take_a_provider_its_parent_lacks() { + let state = child_sandboxes_state().await; + let lead_id = member_root(&state, "lead", &["github"]).await; + let request = CreateSandboxRequest { + spec: Some(SandboxSpec { + providers: vec!["gitlab".to_string()], + ..Default::default() + }), + ..sandbox_child_request("worker") + }; + let err = handle_create_sandbox(&state, sandbox_request(&lead_id, request)) + .await + .unwrap_err(); + assert_eq!(err.code(), tonic::Code::FailedPrecondition); + assert_eq!( + err.message(), + "provider 'gitlab' is not attached to parent 'lead'" + ); + } - let mut stream = response.into_inner(); - let mut cursors = Vec::new(); - while let Ok(Some(item)) = - tokio::time::timeout(std::time::Duration::from_millis(200), stream.next()).await - { - let evt = item.unwrap(); - if !evt.cursor.is_empty() { - cursors.push(seq_of(&evt)); - } - } + #[tokio::test] + async fn a_sandbox_caller_needs_a_creator_who_still_has_access() { + let mut state = member_checked_state().await; + let create = |state: Arc, id: String, name: &'static str| async move { + handle_create_sandbox(&state, sandbox_request(&id, sandbox_child_request(name))).await + }; - // Every delivered cursor is unique (no double delivery) and monotonically - // increasing (replay ordered, then live in cursor order for one source). - let mut sorted = cursors.clone(); - sorted.sort_unstable(); - sorted.dedup(); + let no_creator = put_parent_record(&state, "no-creator", &[], None, false).await; + let err = create(state.clone(), no_creator, "w1").await.unwrap_err(); + assert_eq!(err.code(), tonic::Code::FailedPrecondition); assert_eq!( - sorted.len(), - cursors.len(), - "duplicate cursors delivered: {cursors:?}" + err.message(), + "this sandbox was not started by a workspace user, so it cannot create children" ); + + let lost = put_parent_record(&state, "lost", &[], None, false).await; + set_creator(&state, &lost, "bob").await; + let err = create(state.clone(), lost, "w2").await.unwrap_err(); + assert_eq!(err.code(), tonic::Code::PermissionDenied); assert_eq!( - cursors, sorted, - "cursors not delivered in order: {cursors:?}" + err.message(), + "the user who started this sandbox is not a member of workspace 'default' with \ + the user role; a platform admin can add them with: openshell workspace member \ + add --workspace default --subject --role user" ); + + let member = member_root(&state, "member", &[]).await; + create(state.clone(), member, "w3").await.unwrap(); + + // The built-in development user counts only while such users are + // allowed, checked at each create. + let dev_subject = crate::multiplex::UNAUTHENTICATED_DEV_SUBJECT; + let dev = put_parent_record(&state, "dev", &[], None, false).await; + set_creator_from(&state, &dev, dev_subject, "local_dev").await; + let err = create(state.clone(), dev.clone(), "w4").await.unwrap_err(); + assert_eq!(err.code(), tonic::Code::PermissionDenied); + // An OIDC user who carries the development user's subject is not it. + let lookalike = put_parent_record(&state, "lookalike", &[], None, false).await; + set_creator(&state, &lookalike, dev_subject).await; + Arc::get_mut(&mut state) + .unwrap() + .config + .auth + .allow_unauthenticated_users = true; + create(state.clone(), dev, "w5").await.unwrap(); + let err = create(state.clone(), lookalike, "w6").await.unwrap_err(); + assert_eq!(err.code(), tonic::Code::PermissionDenied); } + /// With no admin role configured every authenticated user is a platform + /// admin, so a creator needs no membership; a root with no recorded + /// creator is still refused. #[tokio::test] - async fn delete_handler_ends_telemetry_for_the_resolved_sandbox_id() { - 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(); - state.store.put_message(&original).await.unwrap(); + async fn a_creator_needs_no_membership_when_no_admin_role_is_configured() { + let state = child_sandboxes_state().await; + assert!(state.admin_role.is_empty()); - // Hold the global guard so the handler can resolve the original ID and - // acquire its delete gate, but cannot yet take the sandbox's local - // lifecycle lock (shared global key) to revalidate or mutate it. - let global_guard = state - .compute - .mutation_guard(MutationScope::Global) + let lead = put_parent_record(&state, "lead", &[], None, false).await; + set_creator(&state, &lead, "bob").await; + handle_create_sandbox(&state, sandbox_request(&lead, sandbox_child_request("w1"))) .await .unwrap(); - let delete_state = state.clone(); - 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(), - )), - }), - ) - .await - }); - tokio::time::timeout(std::time::Duration::from_secs(5), async { - while state.compute.lifecycle_gate_entry_count() == 0 { - tokio::time::sleep(std::time::Duration::from_millis(10)).await; - } - }) + + let no_creator = put_parent_record(&state, "no-creator", &[], None, false).await; + let err = handle_create_sandbox( + &state, + sandbox_request(&no_creator, sandbox_child_request("w2")), + ) .await - .expect("delete did not resolve and acquire the original sandbox gate"); + .unwrap_err(); + assert_eq!(err.code(), tonic::Code::FailedPrecondition); + } - state - .store - .delete(Sandbox::object_type(), original.object_id()) - .await - .unwrap(); - 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(); - drop(global_guard); + #[tokio::test] + async fn an_mcp_child_records_the_user_its_root_was_created_for() { + let state = child_sandboxes_state().await; + let lead_id = member_root(&state, "lead", &[]).await; - let response = delete.await.unwrap().unwrap().into_inner(); + let child = handle_create_sandbox( + &state, + sandbox_request(&lead_id, sandbox_child_request("worker")), + ) + .await + .unwrap() + .into_inner() + .sandbox + .unwrap(); + + let alice = Some(openshell_core::proto::UserRef { + subject: "alice".to_string(), + identity_provider: "oidc".to_string(), + }); + assert_eq!(child.created_on_behalf_of, alice); assert_eq!( - response.outcome(), - openshell_core::proto::DeletionOutcome::Completed - ); - assert!( - state - .store - .get_message::(replacement.object_id()) + sandbox_record(&state, child.object_id()) .await - .unwrap() - .is_some() + .created_on_behalf_of, + alice, + "stored, not only returned" + ); + } + + #[tokio::test] + async fn an_audit_event_records_the_user_a_sandbox_acts_for() { + let state = child_sandboxes_state().await; + let lead_id = member_root(&state, "lead", &[]).await; + let unknown_root = put_parent_record(&state, "old-root", &[], None, false).await; + let stack = crate::multiplex::AuthGrpcRouter::new( + openshell_core::proto::open_shell_server::OpenShellServer::new( + crate::OpenShellService::new(state.clone()), + ), + None, + None, ); + let connection = crate::mcp::McpConnection::new(stack.caller_authenticator(), stack); + + // Without a store, and for a root without a creator, it is unknown. assert_eq!( - state.telemetry.ended_sandbox_sessions(), - [original.object_id().to_string()] + crate::mcp::acting_for(&connection, &lead_id).await, + "unknown" + ); + let connection = connection.with_store(state.store.clone()); + assert_eq!(crate::mcp::acting_for(&connection, &lead_id).await, "alice"); + assert_eq!( + crate::mcp::acting_for(&connection, &unknown_root).await, + "unknown" + ); + assert_eq!( + crate::mcp::acting_for(&connection, "missing").await, + "unknown" ); } #[tokio::test] - async fn internal_delete_rejects_expected_identity_drift_before_mutation() { - let state = test_server_state().await; - let mut sandbox = test_sandbox("guarded-delete", Vec::new()); - sandbox.metadata.as_mut().unwrap().id = "sb-current".to_string(); - state.store.put_message(&sandbox).await.unwrap(); + async fn a_child_sandbox_cannot_create_children() { + let state = child_sandboxes_state().await; + let lead_id = member_root(&state, "lead", &[]).await; + let link = openshell_core::proto::SandboxParent { + name: "lead".to_string(), + id: lead_id, + }; + let child_id = put_parent_record(&state, "child", &[], Some(link), false).await; + set_creator(&state, &child_id, "alice").await; + let err = handle_create_sandbox( + &state, + sandbox_request(&child_id, sandbox_child_request("grandchild")), + ) + .await + .unwrap_err(); + assert_eq!(err.code(), tonic::Code::FailedPrecondition); + assert_eq!( + err.message(), + "only root sandboxes can create child sandboxes" + ); + } - let error = state - .compute - .delete_sandbox_with_preconditions( - "default", - "guarded-delete", - SandboxDeletePreconditions { - expected_sandbox_id: Some("sb-stale".to_string()), - expected_resource_version: None, - }, - ) + #[tokio::test] + async fn a_sandbox_caller_execs_only_in_its_own_children() { + let state = child_sandboxes_state().await; + let lead_id = member_root(&state, "lead", &[]).await; + let other_id = put_parent_record(&state, "other", &[], None, false).await; + for (name, parent, id) in [("mine", "lead", &lead_id), ("theirs", "other", &other_id)] { + let link = openshell_core::proto::SandboxParent { + name: parent.to_string(), + id: id.clone(), + }; + put_parent_record(&state, name, &[], Some(link), false).await; + } + let exec = |name: &str| ExecSandboxRequest { + sandbox: name.to_string(), + command: vec!["ls".to_string()], + ..Default::default() + }; + + for name in ["theirs", "other", "lead", "missing"] { + let err = handle_exec_sandbox(&state, sandbox_request(&lead_id, exec(name))) + .await + .unwrap_err(); + assert_eq!(err.code(), tonic::Code::NotFound, "{name}"); + assert_eq!(err.message(), format!("sandbox '{name}' not found")); + } + + // Its own child is found; this one is not ready yet. + let err = handle_exec_sandbox(&state, sandbox_request(&lead_id, exec("mine"))) .await .unwrap_err(); + assert_eq!(err.code(), tonic::Code::FailedPrecondition); + assert_eq!(err.message(), "sandbox is not ready"); - assert_eq!(error.code(), tonic::Code::Aborted); + for (request, field) in [ + ( + ExecSandboxRequest { + environment: HashMap::from([("A".to_string(), "b".to_string())]), + ..exec("mine") + }, + "environment", + ), + ( + ExecSandboxRequest { + tty: true, + ..exec("mine") + }, + "tty", + ), + ( + ExecSandboxRequest { + cols: 80, + ..exec("mine") + }, + "cols", + ), + ( + ExecSandboxRequest { + rows: 24, + ..exec("mine") + }, + "rows", + ), + ] { + let err = handle_exec_sandbox(&state, sandbox_request(&lead_id, request)) + .await + .unwrap_err(); + assert_eq!(err.code(), tonic::Code::InvalidArgument, "{field}"); + assert_eq!( + err.message(), + format!("field '{field}' is not allowed for sandbox callers") + ); + } + } + + fn sandbox_principal_for(sandbox_id: &str) -> crate::auth::principal::SandboxPrincipal { + let request = sandbox_request(sandbox_id, ()); + match request + .extensions() + .get::() + { + Some(crate::auth::principal::Principal::Sandbox(principal)) => principal.clone(), + _ => unreachable!("sandbox_request sets a sandbox principal"), + } + } + + #[tokio::test] + async fn a_sandbox_caller_deletes_only_its_own_children() { + let state = child_sandboxes_state().await; + let lead_id = member_root(&state, "lead", &[]).await; + let other_id = put_parent_record(&state, "other", &[], None, false).await; + for (name, parent, id) in [("mine", "lead", &lead_id), ("theirs", "other", &other_id)] { + let link = openshell_core::proto::SandboxParent { + name: parent.to_string(), + id: id.clone(), + }; + put_parent_record(&state, name, &[], Some(link), false).await; + } + let delete = |name: &str| DeleteSandboxRequest { + name: name.to_string(), + ..Default::default() + }; + + for name in ["theirs", "other", "lead", "missing"] { + let err = handle_delete_sandbox(&state, sandbox_request(&lead_id, delete(name))) + .await + .unwrap_err(); + assert_eq!(err.code(), tonic::Code::NotFound, "{name}"); + assert_eq!(err.message(), format!("sandbox '{name}' not found")); + } + for (request, field) in [ + ( + DeleteSandboxRequest { + allow_missing: true, + ..delete("mine") + }, + "allow_missing", + ), + ( + DeleteSandboxRequest { + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), + ..delete("mine") + }, + "workspace_scope", + ), + ] { + let err = handle_delete_sandbox(&state, sandbox_request(&lead_id, request)) + .await + .unwrap_err(); + assert_eq!(err.code(), tonic::Code::InvalidArgument, "{field}"); + assert_eq!( + err.message(), + format!("field '{field}' is not allowed for sandbox callers") + ); + } + + handle_delete_sandbox(&state, sandbox_request(&lead_id, delete("mine"))) + .await + .expect("its own child is deleted"); + // Deleting a root with children is refused for users; "other" still + // has its child, so the sandbox caller's delete reached only "mine". assert!( state .store - .get_message::("sb-current") + .get_message_by_name::("default", "theirs") .await .unwrap() .is_some() @@ -6851,802 +10470,1534 @@ mod tests { } #[tokio::test] - async fn internal_delete_rejects_resource_version_without_immutable_identity() { - let state = test_server_state().await; - let mut sandbox = test_sandbox("guarded-delete", Vec::new()); - sandbox.metadata.as_mut().unwrap().id = "sb-current".to_string(); - state.store.put_message(&sandbox).await.unwrap(); - - let error = state + async fn a_reused_name_is_not_deleted_in_place_of_the_checked_child() { + let state = child_sandboxes_state().await; + let lead_id = member_root(&state, "lead", &[]).await; + let link = openshell_core::proto::SandboxParent { + name: "lead".to_string(), + id: lead_id.clone(), + }; + let checked_id = put_parent_record(&state, "w", &[], Some(link), false).await; + let caller = sandbox_principal_for(&lead_id); + + // While the checked child still holds the name, a conflict is + // reported as it is. + let conflict = Status::aborted("some other conflict"); + let status = + aborted_child_delete(&state, &caller, "w", &checked_id, conflict.clone()).await; + assert_eq!(status.code(), tonic::Code::Aborted); + + // The name now belongs to another root: the delete bound to the + // checked id is refused and the new sandbox survives. + state + .store + .delete(Sandbox::object_type(), &checked_id) + .await + .unwrap(); + let reused_id = put_parent_record(&state, "w", &[], None, false).await; + let err = state .compute - .delete_sandbox_with_preconditions( + .delete_sandbox_allow_missing_with_preconditions( "default", - "guarded-delete", + "w", + false, SandboxDeletePreconditions { - expected_sandbox_id: None, - expected_resource_version: Some(17), + expected_sandbox_id: Some(checked_id.clone()), + ..Default::default() }, ) .await .unwrap_err(); - - assert_eq!(error.code(), tonic::Code::InvalidArgument); + assert_eq!(err.code(), tonic::Code::Aborted); assert!( state .store - .get_message::("sb-current") + .get_message::(&reused_id) .await .unwrap() .is_some() ); + + // ...and the agent is told its child is gone. + let status = aborted_child_delete(&state, &caller, "w", &checked_id, err).await; + assert_eq!(status.code(), tonic::Code::NotFound); + assert_eq!(status.message(), "sandbox 'w' not found"); } #[tokio::test] - async fn attach_sandbox_provider_persists_current_provider_list() { - let state = test_server_state().await; - state - .store - .put_message(&test_provider("work-github", "github")) + async fn a_sandbox_caller_reads_only_its_own_childs_own_lines() { + use openshell_core::proto::{GetSandboxLogsRequest, SandboxLogLine}; + let state = child_sandboxes_state().await; + let lead_id = member_root(&state, "lead", &[]).await; + let other_id = put_parent_record(&state, "other", &[], None, false).await; + let mut child_id = String::new(); + for (name, parent, id) in [("mine", "lead", &lead_id), ("theirs", "other", &other_id)] { + let link = openshell_core::proto::SandboxParent { + name: parent.to_string(), + id: id.clone(), + }; + let id = put_parent_record(&state, name, &[], Some(link), false).await; + if name == "mine" { + child_id = id; + } + } + let logs = |name: &str, lines: u32| GetSandboxLogsRequest { + sandbox: name.to_string(), + lines, + ..Default::default() + }; + + for name in ["theirs", "other", "lead", "missing"] { + let err = crate::grpc::policy::handle_get_sandbox_logs( + &state, + sandbox_request(&lead_id, logs(name, 10)), + ) .await - .unwrap(); - state - .store - .put_message(&test_sandbox("work", Vec::new())) + .unwrap_err(); + assert_eq!(err.code(), tonic::Code::NotFound, "{name}"); + } + for (request, field) in [ + ( + GetSandboxLogsRequest { + sources: vec!["gateway".to_string()], + ..logs("mine", 10) + }, + "sources", + ), + ( + GetSandboxLogsRequest { + min_level: "ERROR".to_string(), + ..logs("mine", 10) + }, + "min_level", + ), + ] { + let err = crate::grpc::policy::handle_get_sandbox_logs( + &state, + sandbox_request(&lead_id, request), + ) .await - .unwrap(); + .unwrap_err(); + assert_eq!(err.code(), tonic::Code::InvalidArgument, "{field}"); + assert_eq!( + err.message(), + format!("field '{field}' is not allowed for sandbox callers") + ); + } - let response = handle_attach_sandbox_provider( + // The child is not ready; its newest sandbox lines still come back, + // counted after the gateway lines between them are dropped. + for i in 0..6 { + for source in ["sandbox", "gateway"] { + state.tracing_log_bus.publish_external(SandboxLogLine { + sandbox_id: child_id.clone(), + level: "INFO".to_string(), + message: format!("{source} {i}"), + source: source.to_string(), + ..Default::default() + }); + } + } + let reply = crate::grpc::policy::handle_get_sandbox_logs( &state, - authed_request(AttachSandboxProviderRequest { - request_id: String::new(), - sandbox: "work".to_string(), - workspace_scope: Some(openshell_core::proto::workspace_selector( - "default".to_string(), - )), - provider: "work-github".to_string(), - expected_resource_version: 0, - }), + sandbox_request(&lead_id, logs("mine", 4)), + ) + .await + .unwrap() + .into_inner(); + let messages: Vec<_> = reply.logs.iter().map(|log| log.message.as_str()).collect(); + assert_eq!( + messages, + ["sandbox 2", "sandbox 3", "sandbox 4", "sandbox 5"] + ); + } + + #[tokio::test] + async fn mcp_create_retry_returns_the_child_even_at_the_limit() { + let state = child_sandboxes_state_with_limit(1).await; + let lead_id = member_root(&state, "lead", &[]).await; + + // The child never becomes ready here, so the short wait times out, + // and that is not an error. + let first = call_mcp_tool( + &state, + &lead_id, + "create_sandbox", + serde_json::json!({"name": "w1"}), ) - .await - .unwrap() - .into_inner(); + .await; + assert_eq!(first["isError"], false, "{first}"); + let reply = &first["structuredContent"]; + assert_eq!(reply["name"], "w1"); + assert_eq!(reply["already_existed"], false); + assert_eq!(reply["timed_out"], true); - assert!(response.attached); - let sandbox = state - .store - .get_message_by_name::("default", "work") - .await - .unwrap() - .unwrap(); - assert_eq!(sandbox.phase(), SandboxPhase::Ready as i32); - assert_eq!(sandbox.current_policy_version(), 7); - let spec = sandbox.spec.unwrap(); - assert_eq!(spec.providers, vec!["work-github"]); - assert_eq!(spec.log_level, "debug"); + let retry = call_mcp_tool( + &state, + &lead_id, + "create_sandbox", + serde_json::json!({"name": "w1"}), + ) + .await; + assert_eq!(retry["isError"], false, "{retry}"); + assert_eq!(retry["structuredContent"]["already_existed"], true); } #[tokio::test] - async fn attach_sandbox_provider_uses_configured_provider_profile_sources() { - let state = test_server_state().await; - state - .store - .put_message(&test_provider("work-github", "github")) - .await - .unwrap(); - state - .store - .put_message(&test_sandbox("work", Vec::new())) - .await - .unwrap(); + async fn mcp_create_refuses_a_name_that_is_not_the_callers_child() { + let state = child_sandboxes_state().await; + let lead_id = member_root(&state, "lead", &[]).await; + put_parent_record(&state, "other-root", &[], None, false).await; - let response = handle_attach_sandbox_provider( + let result = call_mcp_tool( &state, - authed_request(AttachSandboxProviderRequest { - request_id: String::new(), - sandbox: "work".to_string(), - workspace_scope: Some(openshell_core::proto::workspace_selector( - "default".to_string(), - )), - provider: "work-github".to_string(), - expected_resource_version: 0, - }), + &lead_id, + "create_sandbox", + serde_json::json!({"name": "other-root"}), ) - .await - .expect("an imported github profile should resolve from the user source") - .into_inner(); - - assert!(response.attached); - let sandbox = response.sandbox.expect("updated sandbox"); + .await; + assert_eq!(result["isError"], true, "{result}"); + assert_eq!(result["structuredContent"]["error"], "already_exists"); assert_eq!( - sandbox.spec.expect("sandbox spec").providers, - vec!["work-github"] + result["structuredContent"]["message"], + "a sandbox named 'other-root' already exists in this workspace" ); } #[tokio::test] - async fn attach_sandbox_provider_is_idempotent_and_avoids_duplicates() { - let state = test_server_state().await; - state - .store - .put_message(&test_provider("work-github", "github")) - .await - .unwrap(); - state + async fn mcp_create_reports_a_failed_child() { + let state = child_sandboxes_state().await; + let lead_id = member_root(&state, "lead", &[]).await; + let link = openshell_core::proto::SandboxParent { + name: "lead".to_string(), + id: lead_id.clone(), + }; + let child_id = put_parent_record(&state, "w1", &[], Some(link), false).await; + let mut child = state .store - .put_message(&test_sandbox( - "work", - vec!["work-github".to_string(), "work-github".to_string()], - )) + .get_message::(&child_id) .await + .unwrap() .unwrap(); + child.set_phase(SandboxPhase::Error as i32); + child.status.get_or_insert_with(Default::default).conditions = + vec![openshell_core::proto::SandboxCondition { + r#type: "Ready".to_string(), + status: "False".to_string(), + message: "image pull failed".to_string(), + ..Default::default() + }]; + state.store.put_message(&child).await.unwrap(); - let response = handle_attach_sandbox_provider( + let result = call_mcp_tool( &state, - authed_request(AttachSandboxProviderRequest { - request_id: String::new(), - sandbox: "work".to_string(), - workspace_scope: Some(openshell_core::proto::workspace_selector( - "default".to_string(), - )), - provider: "work-github".to_string(), - expected_resource_version: 0, - }), + &lead_id, + "create_sandbox", + serde_json::json!({"name": "w1"}), ) - .await - .unwrap() - .into_inner(); - - assert!(!response.attached); - let providers = state - .store - .get_message_by_name::("default", "work") - .await - .unwrap() - .unwrap() - .spec - .unwrap() - .providers; - assert_eq!(providers, vec!["work-github"]); + .await; + assert_eq!(result["isError"], true, "{result}"); + assert_eq!( + result["structuredContent"]["message"], + "sandbox 'w1' failed: image pull failed" + ); } - fn attach_request(sandbox: &str, provider: &str) -> Request { - authed_request(AttachSandboxProviderRequest { - request_id: String::new(), - sandbox: sandbox.to_string(), - workspace_scope: Some(openshell_core::proto::workspace_selector( - "default".to_string(), - )), - provider: provider.to_string(), - expected_resource_version: 0, + fn mcp_user(subject: &str, roles: &[&str]) -> crate::auth::principal::Principal { + crate::auth::principal::Principal::User(crate::auth::principal::UserPrincipal { + identity: crate::auth::identity::Identity { + subject: subject.to_string(), + display_name: None, + roles: roles.iter().map(ToString::to_string).collect(), + scopes: Vec::new(), + provider: IdentityProvider::Oidc, + }, }) } - #[tokio::test] - async fn attach_provider_does_not_wait_for_unrelated_sandbox_guard() { - let state = test_server_state().await; - state - .store - .put_message(&test_provider("work-github", "github")) - .await - .unwrap(); + /// A child-sandbox state whose users are checked against workspace + /// membership (an empty admin role would make every user an admin). + async fn member_checked_state() -> Arc { + let mut state = child_sandboxes_state().await; + Arc::get_mut(&mut state).unwrap().admin_role = "openshell-admin".to_string(); state + } + + fn mcp_names(result: &serde_json::Value) -> Vec { + result["structuredContent"]["sandboxes"] + .as_array() + .unwrap() + .iter() + .map(|sandbox| sandbox["name"].as_str().unwrap().to_string()) + .collect() + } + + #[tokio::test] + async fn mcp_users_act_only_in_workspaces_they_belong_to() { + let state = member_checked_state().await; + put_parent_record(&state, "lead", &[], None, false).await; + let far_id = put_parent_record(&state, "far", &[], None, false).await; + let mut far = state .store - .put_message(&test_sandbox("work", Vec::new())) + .get_message::(&far_id) .await + .unwrap() .unwrap(); - let unrelated = test_sandbox("unrelated", Vec::new()); - state.store.put_message(&unrelated).await.unwrap(); - let unrelated_guard = crate::persistence::lock_order::branch( - state - .compute - .mutation_guard(MutationScope::sandbox("default", unrelated.object_id())), + far.metadata.as_mut().unwrap().workspace = "team".to_string(); + state.store.delete("sandbox", &far_id).await.unwrap(); + state.store.put_message(&far).await.unwrap(); + put_member(&state, "alice").await; + let alice = || mcp_user("alice", &["openshell-user"]); + + let list = call_mcp_as(&state, alice(), None, None, "list", serde_json::json!({})).await; + assert_eq!(list["isError"], false, "{list}"); + assert_eq!(mcp_names(&list), vec!["lead".to_string()]); + let logs = call_mcp_as( + &state, + alice(), + None, + None, + "logs", + serde_json::json!({"name": "lead"}), ) - .await - .unwrap(); + .await; + assert_eq!(logs["isError"], false, "{logs}"); - let response = tokio::time::timeout( - std::time::Duration::from_secs(5), - handle_attach_sandbox_provider(&state, attach_request("work", "work-github")), + // Another workspace, and a sandbox there, read as missing. + let logs = call_mcp_as( + &state, + alice(), + None, + Some("team"), + "logs", + serde_json::json!({"name": "far"}), ) - .await - .expect("attach should not wait for an unrelated sandbox mutation") - .expect("attach should succeed") - .into_inner(); - assert!(response.attached); - drop(unrelated_guard); + .await; + assert_eq!(logs["structuredContent"]["error"], "not_found", "{logs}"); + let list = call_mcp_as( + &state, + alice(), + None, + Some("team"), + "list", + serde_json::json!({}), + ) + .await; + assert_eq!(list["isError"], true, "{list}"); + // So does a sandbox in a workspace the user is not a member of. + let bob = mcp_user("bob", &["openshell-user"]); + let logs = call_mcp_as( + &state, + bob, + None, + None, + "logs", + serde_json::json!({"name": "lead"}), + ) + .await; + assert_eq!(logs["structuredContent"]["error"], "not_found", "{logs}"); } #[tokio::test] - async fn attach_provider_waits_for_workspace_guard() { - let state = test_server_state().await; - state - .store - .put_message(&test_provider("work-github", "github")) - .await - .unwrap(); - state - .store - .put_message(&test_sandbox("work", Vec::new())) - .await - .unwrap(); - let workspace_guard = state - .compute - .mutation_guard(MutationScope::Workspace("default")) - .await - .unwrap(); + async fn mcp_users_need_the_role_for_each_method() { + let state = member_checked_state().await; + put_parent_record(&state, "lead", &[], None, false).await; + put_member(&state, "carol").await; + let policy = || AuthzPolicy { + admin_role: "openshell-admin".to_string(), + user_role: "openshell-user".to_string(), + scopes_enabled: false, + }; - let task_state = state.clone(); - let mut attach = tokio::spawn(async move { - handle_attach_sandbox_provider(&task_state, attach_request("work", "work-github")).await - }); - assert!( - tokio::time::timeout(std::time::Duration::from_millis(100), &mut attach) - .await - .is_err(), - "attach should wait for a provider writer in its workspace" + let refused = call_mcp_as( + &state, + mcp_user("carol", &[]), + Some(policy()), + None, + "list", + serde_json::json!({}), + ) + .await; + assert_eq!( + refused["structuredContent"]["error"], "permission_denied", + "{refused}" ); - drop(workspace_guard); - - let response = tokio::time::timeout(std::time::Duration::from_secs(5), attach) - .await - .expect("attach should finish after the workspace guard is released") - .expect("join attach task") - .expect("attach should succeed") - .into_inner(); - assert!(response.attached); + let allowed = call_mcp_as( + &state, + mcp_user("carol", &["openshell-user"]), + Some(policy()), + None, + "list", + serde_json::json!({}), + ) + .await; + assert_eq!(allowed["isError"], false, "{allowed}"); } #[tokio::test] - async fn detach_sandbox_provider_is_idempotent_and_removes_all_matches() { - let state = test_server_state().await; - state - .store - .put_message(&test_provider_with_credential_key( - "other", - "github", - "GITHUB_TOKEN", - )) - .await - .unwrap(); - state + async fn mcp_users_create_roots_and_children_but_no_grandchildren() { + let state = member_checked_state().await; + put_parent_record(&state, "lead", &[], None, false).await; + put_member(&state, "alice").await; + let create = |arguments| { + call_mcp_as( + &state, + mcp_user("alice", &["openshell-user"]), + None, + None, + "create_sandbox", + arguments, + ) + }; + + let root = create(serde_json::json!({"name": "r1", "image": "alpine:3"})).await; + assert_eq!(root["isError"], false, "{root}"); + let r1 = state .store - .put_message(&test_sandbox( - "work", - vec![ - "work-github".to_string(), - "other".to_string(), - "work-github".to_string(), - ], - )) + .get_message_by_name::("default", "r1") .await + .unwrap() .unwrap(); + assert!(r1.parent.is_none()); + assert_eq!(r1.created_on_behalf_of.unwrap().subject, "alice"); + assert_eq!( + r1.spec.as_ref().unwrap().template.as_ref().unwrap().image, + "alpine:3" + ); - let response = handle_detach_sandbox_provider( + let child = create(serde_json::json!({"name": "c1", "parent": "lead"})).await; + assert_eq!(child["isError"], false, "{child}"); + assert_eq!(child["structuredContent"]["parent"], "lead"); + + let grandchild = create(serde_json::json!({"name": "g1", "parent": "c1"})).await; + assert_eq!(grandchild["isError"], true, "{grandchild}"); + } + + #[tokio::test] + async fn an_mcp_sandbox_caller_ignores_a_workspace_header() { + let state = child_sandboxes_state().await; + let lead_id = put_parent_record(&state, "lead", &[], None, false).await; + let link = openshell_core::proto::SandboxParent { + name: "lead".to_string(), + id: lead_id.clone(), + }; + put_parent_record(&state, "w1", &[], Some(link), false).await; + let caller = + crate::auth::principal::Principal::Sandbox(crate::auth::principal::SandboxPrincipal { + sandbox_id: lead_id, + source: crate::auth::principal::SandboxIdentitySource::BootstrapJwt { + issuer: "openshell-gateway:test".to_string(), + auth_epoch: None, + }, + trust_domain: Some("openshell".to_string()), + }); + + let list = call_mcp_as( &state, - authed_request(DetachSandboxProviderRequest { - request_id: String::new(), - sandbox: "work".to_string(), - workspace_scope: Some(openshell_core::proto::workspace_selector( - "default".to_string(), - )), - provider: "work-github".to_string(), - expected_resource_version: 0, - }), + caller, + None, + Some("team"), + "list", + serde_json::json!({}), ) - .await - .unwrap() - .into_inner(); + .await; + assert_eq!(list["isError"], false, "{list}"); + assert_eq!(mcp_names(&list), vec!["w1".to_string()]); + } - assert!(response.detached); - let providers = state - .store - .get_message_by_name::("default", "work") + #[tokio::test] + async fn a_parent_filter_needs_one_workspace_and_an_existing_parent() { + let state = child_sandboxes_state().await; + put_parent_record(&state, "lead", &[], None, false).await; + + let mut all_workspaces = list_children_request("lead", 100, String::new()); + all_workspaces.workspace_scope = Some(openshell_core::proto::all_workspaces_selector()); + let err = handle_list_sandboxes(&state, authed_request(all_workspaces)) .await - .unwrap() - .unwrap() - .spec - .unwrap() - .providers; - assert_eq!(providers, vec!["other"]); + .unwrap_err(); + assert_eq!(err.code(), tonic::Code::InvalidArgument); + assert!( + err.message() + .contains("a parent filter needs a single workspace") + ); - let response = handle_detach_sandbox_provider( + let err = handle_list_sandboxes( &state, - authed_request(DetachSandboxProviderRequest { - request_id: String::new(), - sandbox: "work".to_string(), - workspace_scope: Some(openshell_core::proto::workspace_selector( - "default".to_string(), - )), - provider: "work-github".to_string(), - expected_resource_version: 0, - }), + authed_request(list_children_request("missing", 100, String::new())), ) .await - .unwrap() - .into_inner(); - assert!(!response.detached); + .unwrap_err(); + assert_eq!(err.code(), tonic::Code::NotFound); } #[tokio::test] - async fn detach_rejects_provider_referenced_by_policy_credential_binding() { - let state = test_server_state().await; + async fn a_page_token_is_tied_to_the_parent_it_was_listed_for() { + let state = child_sandboxes_state().await; + let lead_id = put_parent_record(&state, "lead", &[], None, false).await; + let link = openshell_core::proto::SandboxParent { + name: "lead".to_string(), + id: lead_id.clone(), + }; + for name in ["worker1", "worker2"] { + put_parent_record(&state, name, &[], Some(link.clone()), false).await; + } + let list = |parent: &str, token: String| { + handle_list_sandboxes( + &state, + authed_request(list_children_request(parent, 1, token)), + ) + }; + + let unfiltered = list("", String::new()).await.unwrap().into_inner(); + let err = list("lead", unfiltered.next_page_token).await.unwrap_err(); + assert_eq!(err.code(), tonic::Code::InvalidArgument); + + let filtered = list("lead", String::new()).await.unwrap().into_inner(); + let err = list("", filtered.next_page_token.clone()) + .await + .unwrap_err(); + assert_eq!(err.code(), tonic::Code::InvalidArgument); + + // A new root under the same name is a different parent. state .store - .put_message(&test_provider("work-gcp", "google-cloud")) + .delete(Sandbox::object_type(), &lead_id) .await .unwrap(); + put_parent_record(&state, "lead", &[], None, false).await; + let err = list("lead", filtered.next_page_token).await.unwrap_err(); + assert_eq!(err.code(), tonic::Code::InvalidArgument); + } - let mut sandbox = test_sandbox("work", vec!["work-gcp".to_string()]); - let policy = sandbox - .spec - .as_mut() - .and_then(|spec| spec.policy.as_mut()) - .unwrap(); - policy.network_policies.insert( - "gcp_storage".to_string(), - openshell_core::proto::NetworkPolicyRule { - name: "gcp_storage".to_string(), - endpoints: vec![openshell_core::proto::NetworkEndpoint { - host: "storage.googleapis.com".to_string(), - port: 443, - credential_binding: Some(openshell_core::proto::NetworkCredentialBinding { - provider: "work-gcp".to_string(), - }), - ..Default::default() - }], - ..Default::default() - }, + #[tokio::test] + async fn detaching_a_provider_from_a_parent_detaches_it_from_its_children() { + let state = child_sandboxes_state().await; + let (_, worker_id) = lead_and_child_sharing_a_provider(&state).await; + let before = sandbox_spec(&state, &worker_id).await; + + detach_from_lead(&state, "work-github").await; + + // The parent's policy did not change, so the child's copy is current + // and only the provider is removed, as a detach removes it. + eventually(|| async { sandbox_spec(&state, &worker_id).await.providers.is_empty() }).await; + let after = sandbox_spec(&state, &worker_id).await; + assert_ne!( + after.provider_attachment_epoch, before.provider_attachment_epoch, + "the supervisor must see a new attachment epoch to drop the credential" ); - state.store.put_message(&sandbox).await.unwrap(); + assert_eq!(latest_policy(&state, &worker_id).await.version, 1); + } - let error = handle_detach_sandbox_provider( - &state, - authed_request(DetachSandboxProviderRequest { - request_id: String::new(), - sandbox: "work".to_string(), - workspace_scope: Some(openshell_core::proto::workspace_selector( - "default".to_string(), - )), - provider: "work-gcp".to_string(), - expected_resource_version: 0, - }), - ) - .await - .expect_err("a referenced provider must remain attached"); + #[tokio::test] + async fn the_scan_detaches_a_provider_a_child_missed_losing() { + let state = child_sandboxes_state().await; + let (lead_id, worker_id) = lead_and_child_sharing_a_provider(&state).await; + lead_loses_providers_without_a_sync(&state, &lead_id).await; - assert_eq!(error.code(), tonic::Code::FailedPrecondition); - assert!(error.message().contains("not attached")); - let providers = state + sync_all_children(&state).await.unwrap(); + + assert!(sandbox_spec(&state, &worker_id).await.providers.is_empty()); + } + + /// Wait for a background sync to reach the store. + async fn eventually(mut reached: F) + where + F: FnMut() -> Fut, + Fut: Future, + { + for _ in 0..500 { + if reached().await { + return; + } + tokio::time::sleep(std::time::Duration::from_millis(10)).await; + } + panic!("not reached within 5 seconds"); + } + + async fn sandbox_record(state: &ServerState, sandbox_id: &str) -> Sandbox { + state .store - .get_message_by_name::("default", "work") + .get_message::(sandbox_id) .await .unwrap() .unwrap() - .spec - .unwrap() - .providers; - assert_eq!(providers, vec!["work-gcp"]); + } + + async fn delivered_variables(state: &Arc, sandbox: &Sandbox) -> Vec { + super::super::policy::build_provider_environment_snapshot(state, sandbox, true, true) + .await + .expect("provider environment") + .values + .into_iter() + .map(|value| value.name) + .collect() + } + + /// Take a provider from the lead's record without any sync, as when the + /// sync after a detach is lost. + async fn lead_loses_providers_without_a_sync(state: &ServerState, lead_id: &str) { + let mut lead = sandbox_record(state, lead_id).await; + lead.spec.as_mut().unwrap().providers.clear(); + state.store.put_message(&lead).await.unwrap(); } #[tokio::test] - async fn list_sandbox_providers_returns_attached_provider_records() { - use openshell_core::proto::CreateWorkspaceRequest; + async fn a_child_loses_a_provider_its_parent_lost_at_its_next_build() { + let state = child_sandboxes_state().await; + let (lead_id, worker_id) = lead_and_child_sharing_a_provider(&state).await; + let worker = sandbox_record(&state, &worker_id).await; + assert!( + delivered_variables(&state, &worker) + .await + .contains(&"GITHUB_TOKEN".to_string()) + ); - let state = test_server_state().await; - state - .store - .put_message(&test_provider("work-github", "github")) + lead_loses_providers_without_a_sync(&state, &lead_id).await; + + // No sync ran: the child's record still names the provider, but its + // very next build serves none of it. + assert_eq!( + sandbox_spec(&state, &worker_id).await.providers, + vec!["work-github"] + ); + assert!(delivered_variables(&state, &worker).await.is_empty()); + let inputs = super::super::policy::load_sandbox_config_inputs(&state, worker.clone()) .await .unwrap(); - state - .store - .put_message(&test_provider("work-gitlab", "gitlab")) + assert!(inputs.sandbox().spec.as_ref().unwrap().providers.is_empty()); + let config = child_config(&state, &worker_id).await; + assert!(config.configuration_admitted); + assert!( + !provider_attached_for_delivery(&state, &worker, "work-github") + .await + .unwrap(), + "readiness reports the provider as not attached" + ); + } + + #[tokio::test] + async fn a_detach_rebuilds_a_push_mode_child_at_once_without_a_sync() { + use openshell_core::proto::{SupervisorMessage, gateway_message, supervisor_message}; + + let mut state = child_sandboxes_state().await; + Arc::get_mut(&mut state) + .unwrap() + .config + .config_delivery_mode = openshell_core::config::ConfigDeliveryMode::Push; + let (_, worker_id) = lead_and_child_sharing_a_provider(&state).await; + let mut harness = crate::grpc::test_support::connect_supervisor_stream( + &state, + &worker_id, + crate::grpc::test_support::StreamFeatures::Apply, + ) + .await + .unwrap(); + let accepted = harness.inbound.message().await.unwrap().unwrap(); + let Some(gateway_message::Payload::SessionAccepted(accepted)) = accepted.payload else { + panic!("expected SessionAccepted"); + }; + let bootstrap = accepted.bootstrap.expect("push bootstrap"); + assert!( + bootstrap + .provider_environment + .as_ref() + .unwrap() + .values + .iter() + .any(|value| value.name == "GITHUB_TOKEN") + ); + harness + .outbound + .send(SupervisorMessage { + payload: Some(supervisor_message::Payload::ConfigUpdateResult( + crate::config_delivery::session::applied_result(&bootstrap), + )), + }) .await .unwrap(); - state - .store - .put_message(&test_sandbox( - "work", - vec!["work-github".to_string(), "work-gitlab".to_string()], - )) + // The acknowledgement is recorded under the child's lock; live + // updates start once it is. + eventually(|| async { + !state + .supervisor_sessions + .config_update_in_flight(&worker_id, &accepted.session_id) + }) + .await; + // Holding the child's lock keeps the sync from reaching it. The + // detach runs as its own task, as a request would. + let _guard = state + .compute + .mutation_guard(MutationScope::sandbox("default", &worker_id)) .await .unwrap(); - state - .store - .put_message(&test_sandbox("other", vec!["work-github".to_string()])) + let detach_state = Arc::clone(&state); + tokio::spawn(async move { detach_from_lead(&detach_state, "work-github").await }) .await .unwrap(); - let first_page = handle_list_sandbox_providers( + // Acknowledge each update, as a supervisor does, until one without + // the credential arrives. Well under the 30 s re-check, so only the + // detach's own notification can explain it. + tokio::time::timeout(std::time::Duration::from_secs(5), async { + loop { + let message = harness.inbound.message().await.unwrap().unwrap(); + let Some(gateway_message::Payload::ConfigUpdate(update)) = message.payload else { + continue; + }; + harness + .outbound + .send(SupervisorMessage { + payload: Some(supervisor_message::Payload::ConfigUpdateResult( + crate::config_delivery::session::applied_result(&update), + )), + }) + .await + .unwrap(); + if update + .provider_environment + .unwrap() + .values + .iter() + .all(|value| value.name != "GITHUB_TOKEN") + { + break; + } + } + }) + .await + .expect("the child is rebuilt at once, not at its 30 s re-check"); + assert_eq!( + sandbox_spec(&state, &worker_id).await.providers, + vec!["work-github"], + "no sync has run" + ); + } + + #[tokio::test] + async fn a_connecting_childs_first_configuration_lacks_a_provider_its_parent_lost() { + let state = child_sandboxes_state().await; + let (lead_id, worker_id) = lead_and_child_sharing_a_provider(&state).await; + // The record read when the child connected, before any sync. + let read_at_connect = sandbox_record(&state, &worker_id).await; + lead_loses_providers_without_a_sync(&state, &lead_id).await; + + let bootstrap = crate::config_delivery::session::build_session_bootstrap( &state, - authed_request(ListSandboxProvidersRequest { - sandbox: "work".to_string(), - workspace_scope: Some(openshell_core::proto::workspace_selector( - "default".to_string(), - )), - page_size: 1, - page_token: String::new(), + &read_at_connect, + Vec::new(), + ) + .await + .unwrap(); + + assert!(bootstrap.config.sandbox_config.configuration_admitted); + assert!( + bootstrap + .config + .provider_environment + .values + .iter() + .all(|value| value.name != "GITHUB_TOKEN") + ); + } + + /// Replace the lead's policy through `UpdateConfig`, as a user does. + /// Returns the version written. + async fn update_lead_policy( + state: &Arc, + policy: openshell_core::proto::SandboxPolicy, + ) -> u32 { + super::super::policy::handle_update_config( + state, + authed_request(openshell_core::proto::UpdateConfigRequest { + sandbox: "lead".to_string(), + workspace_scope: Some(default_scope()), + policy: Some(policy), + ..Default::default() }), ) .await - .unwrap() - .into_inner(); + .expect("the lead's policy is updated") + .into_inner() + .version + } - assert_eq!(first_page.providers.len(), 1); - assert_eq!(first_page.providers[0].r#type, "github"); - assert_eq!( - first_page.providers[0].credentials.get("TOKEN"), - Some(&"REDACTED".to_string()) + #[tokio::test] + async fn a_root_policy_update_reaches_its_child_before_the_call_returns() { + let state = child_sandboxes_state().await; + let (lead_id, worker_id) = lead_with_copied_child(&state).await; + + update_lead_policy(&state, lead_policy(false)).await; + + assert!(holds_parent_latest(&state, &worker_id, &lead_id).await); + let (child_policy, _) = super::super::policy::canonical_policy_record_identity( + &latest_policy(&state, &worker_id).await, + ) + .unwrap(); + assert!(child_policy.network_policies.contains_key("api")); + } + + #[tokio::test] + async fn a_root_failing_to_load_its_policy_does_not_block_its_child() { + let state = child_sandboxes_state().await; + let (lead_id, worker_id) = lead_and_child_sharing_a_provider(&state).await; + let version = update_lead_policy(&state, lead_policy(false)).await; + + super::super::policy::record_policy_apply_result( + &state, + &lead_id, + version, + false, + Some("invalid"), + "test", + ) + .await + .unwrap(); + + let worker = sandbox_record(&state, &worker_id).await; + super::super::policy::load_sandbox_config_inputs(&state, worker.clone()) + .await + .expect("the child's configuration builds"); + let config = child_config(&state, &worker_id).await; + assert!( + config.configuration_admitted, + "{}", + config.configuration_error ); - assert!(!first_page.next_page_token.is_empty()); + assert!(config.policy.unwrap().network_policies.contains_key("api")); + assert!(holds_parent_latest(&state, &worker_id, &lead_id).await); + assert!( + delivered_variables(&state, &worker) + .await + .contains(&"GITHUB_TOKEN".to_string()) + ); + } + + #[tokio::test] + async fn a_child_behind_its_root_is_served_and_the_scan_catches_it_up() { + let state = child_sandboxes_state().await; + let (lead_id, worker_id) = lead_with_copied_child(&state).await; + // Written straight to the store, so no handler copies it. + put_policy_revision_with_status(&state, &lead_id, 2, &lead_policy(false), "loaded").await; + // A nested wait on the lead's lock would time out and fail the scan. + state + .compute + .set_mutation_lock_timeout_for_tests(std::time::Duration::from_millis(50)); + + let config = child_config(&state, &worker_id).await; + assert!( + config.configuration_admitted, + "{}", + config.configuration_error + ); + assert!(!config.policy.unwrap().network_policies.contains_key("api")); + + sync_all_children(&state).await.unwrap(); + + let config = child_config(&state, &worker_id).await; + assert!( + config.configuration_admitted, + "{}", + config.configuration_error + ); + assert!(config.policy.unwrap().network_policies.contains_key("api")); + } + + #[tokio::test] + async fn a_root_policy_that_cannot_be_copied_leaves_children_on_their_last_copy() { + let state = child_sandboxes_state().await; + let (lead_id, worker_id) = lead_with_copied_child(&state).await; + let mut uncopyable = lead_policy(false); + let rule = uncopyable.network_policies.remove("api").unwrap(); + uncopyable + .network_policies + .insert("_provider_github".to_string(), rule); + put_policy_revision_with_status(&state, &lead_id, 2, &uncopyable, "loaded").await; + + sync_children(&state, &lead_id).await.unwrap_err(); + + assert_eq!(latest_policy(&state, &worker_id).await.version, 1); + let config = child_config(&state, &worker_id).await; + assert!( + config.configuration_admitted, + "{}", + config.configuration_error + ); + } - crate::grpc::workspace::handle_create_workspace( - &state, - Request::new(CreateWorkspaceRequest { - request_id: String::new(), - name: "beta".to_string(), - labels: HashMap::new(), - }), - ) - .await - .expect("beta workspace should be created"); - let mut beta_provider = test_provider("work-github", "github"); - beta_provider.metadata.as_mut().unwrap().id = "provider-beta-work-github".to_string(); - beta_provider.metadata.as_mut().unwrap().workspace = "beta".to_string(); - state.store.put_message(&beta_provider).await.unwrap(); - let mut beta_sandbox = test_sandbox("work", vec!["work-github".to_string()]); - beta_sandbox.metadata.as_mut().unwrap().id = "sandbox-beta-work".to_string(); - beta_sandbox.metadata.as_mut().unwrap().workspace = "beta".to_string(); - state.store.put_message(&beta_sandbox).await.unwrap(); + #[tokio::test] + async fn setting_a_child_policy_is_refused_but_settings_are_allowed() { + let state = child_sandboxes_state().await; + put_lead_and_worker(&state).await; - let err = handle_list_sandbox_providers( + let err = super::super::policy::handle_update_config( &state, - authed_request(ListSandboxProvidersRequest { - sandbox: "work".to_string(), - workspace_scope: Some(openshell_core::proto::workspace_selector("beta")), - page_size: 1, - page_token: first_page.next_page_token.clone(), + authed_request(openshell_core::proto::UpdateConfigRequest { + sandbox: "worker1".to_string(), + workspace_scope: Some(default_scope()), + policy: Some(openshell_policy::restrictive_default_policy()), + ..Default::default() }), ) .await - .expect_err("a token for one workspace must not list a same-named sandbox elsewhere"); - assert_eq!(err.code(), tonic::Code::InvalidArgument); - - let mut sandbox = state - .store - .get_message_by_name::("default", "work") - .await - .unwrap() - .expect("sandbox exists"); - sandbox - .spec - .as_mut() - .expect("sandbox has a spec") - .providers - .retain(|name| name != "work-github"); - state.store.put_message(&sandbox).await.unwrap(); + .unwrap_err(); + assert_eq!(err.code(), tonic::Code::FailedPrecondition); + assert!( + err.message() + .contains("child sandboxes use their parent's policy"), + "{}", + err.message() + ); - let err = handle_list_sandbox_providers( + super::super::policy::handle_update_config( &state, - authed_request(ListSandboxProvidersRequest { - sandbox: "other".to_string(), - workspace_scope: Some(openshell_core::proto::workspace_selector("default")), - page_size: 1, - page_token: first_page.next_page_token.clone(), + authed_request(openshell_core::proto::UpdateConfigRequest { + sandbox: "worker1".to_string(), + workspace_scope: Some(default_scope()), + setting_key: openshell_core::settings::PROPOSAL_APPROVAL_MODE_KEY.to_string(), + setting_value: Some(openshell_core::proto::SettingValue { + value: Some(openshell_core::proto::setting_value::Value::StringValue( + "manual".to_string(), + )), + }), + ..Default::default() }), ) .await - .expect_err("a token for one sandbox must not list another sandbox"); - assert_eq!(err.code(), tonic::Code::InvalidArgument); + .expect("a child's settings can still be changed"); + } - let second_page = handle_list_sandbox_providers( - &state, - authed_request(ListSandboxProvidersRequest { - sandbox: "work".to_string(), - workspace_scope: Some(openshell_core::proto::workspace_selector("default")), - page_size: 100, - page_token: first_page.next_page_token, - }), + /// A sandbox's own supervisor writing back its policy with one extra + /// read-only path, as startup path enrichment does. + fn supervisor_write_back( + sandbox_id: &str, + name: &str, + ) -> Request { + let mut policy = openshell_policy::restrictive_default_policy(); + policy + .filesystem + .get_or_insert_with(Default::default) + .read_only + .push("/app".to_string()); + sandbox_request( + sandbox_id, + openshell_core::proto::UpdateConfigRequest { + sandbox: name.to_string(), + workspace_scope: Some(default_scope()), + policy: Some(policy), + ..Default::default() + }, ) - .await - .unwrap() - .into_inner(); - assert_eq!(second_page.providers.len(), 1); - assert_eq!(second_page.providers[0].r#type, "gitlab"); - assert!(second_page.next_page_token.is_empty()); + } + + /// A request made by a sandbox's own supervisor. + fn sandbox_request(sandbox_id: &str, inner: T) -> Request { + use crate::auth::principal::{Principal, SandboxIdentitySource, SandboxPrincipal}; + let mut request = Request::new(inner); + request + .extensions_mut() + .insert(Principal::Sandbox(SandboxPrincipal { + sandbox_id: sandbox_id.to_string(), + source: SandboxIdentitySource::BootstrapJwt { + issuer: "openshell-gateway:test".to_string(), + auth_epoch: None, + }, + trust_domain: Some("openshell".to_string()), + })); + request } #[tokio::test] - async fn attach_sandbox_provider_validates_provider_exists() { - let state = test_server_state().await; - state - .store - .put_message(&test_sandbox("work", Vec::new())) - .await - .unwrap(); + async fn a_child_supervisor_write_back_is_accepted_and_dropped() { + let state = child_sandboxes_state().await; + let worker_id = put_lead_and_worker(&state).await; + let before = latest_policy(&state, &worker_id).await; - let err = handle_attach_sandbox_provider( + let response = super::super::policy::handle_update_config( &state, - authed_request(AttachSandboxProviderRequest { - request_id: String::new(), - sandbox: "work".to_string(), - workspace_scope: Some(openshell_core::proto::workspace_selector( - "default".to_string(), - )), - provider: "missing".to_string(), - expected_resource_version: 0, - }), + supervisor_write_back(&worker_id, "worker1"), ) .await - .unwrap_err(); + .expect("the child's supervisor is answered OK") + .into_inner(); - assert_eq!(err.code(), tonic::Code::FailedPrecondition); + let after = latest_policy(&state, &worker_id).await; + assert_eq!(after.version, before.version, "no revision is written"); + assert_eq!(after.policy_payload, before.policy_payload); + assert_eq!(i64::from(response.version), before.version); + assert_eq!(response.policy_hash, before.policy_hash); } - // ---- validate_interactive_exec_start ---- + #[tokio::test] + async fn a_root_supervisor_write_back_is_still_stored() { + let state = child_sandboxes_state().await; + let lead_id = put_parent_record(&state, "lead", &[], None, false).await; + let before = latest_policy(&state, &lead_id).await; - #[test] - fn interactive_exec_rejects_empty_stream() { - let err = validate_interactive_exec_start(None).unwrap_err(); - assert_eq!(err.code(), tonic::Code::InvalidArgument); - assert!(err.message().contains("expected start message")); + super::super::policy::handle_update_config(&state, supervisor_write_back(&lead_id, "lead")) + .await + .expect("a root's supervisor write-back is stored"); + + assert_eq!( + latest_policy(&state, &lead_id).await.version, + before.version + 1 + ); } - #[test] - fn interactive_exec_rejects_stdin_as_first_message() { - use openshell_core::proto::exec_sandbox_input; - let msg = ExecSandboxInput { - payload: Some(exec_sandbox_input::Payload::Stdin(b"hello".to_vec())), - }; - let err = validate_interactive_exec_start(Some(msg)).unwrap_err(); - assert_eq!(err.code(), tonic::Code::InvalidArgument); - assert!(err.message().contains("start payload")); + /// A root `lead` with a child `worker1` created through the API, so the + /// child's v1 is a copy of the lead's v1. Returns both ids. + async fn lead_with_copied_child(state: &Arc) -> (String, String) { + let lead_id = put_parent_record(state, "lead", &[], None, false).await; + let worker = create_child(state, "worker1", "lead").await; + (lead_id, worker.object_id().to_string()) } - #[test] - fn interactive_exec_rejects_resize_as_first_message() { - use openshell_core::proto::{ExecSandboxWindowResize, exec_sandbox_input}; - let msg = ExecSandboxInput { - payload: Some(exec_sandbox_input::Payload::Resize( - ExecSandboxWindowResize { cols: 80, rows: 24 }, - )), - }; - let err = validate_interactive_exec_start(Some(msg)).unwrap_err(); - assert_eq!(err.code(), tonic::Code::InvalidArgument); - assert!(err.message().contains("start payload")); + /// Whether a child's latest revision is a copy of its parent's latest. + async fn holds_parent_latest(state: &ServerState, child_id: &str, parent_id: &str) -> bool { + let parent = ParentPolicyCopy::of(&latest_policy(state, parent_id).await).unwrap(); + let (_, child_hash) = super::super::policy::canonical_policy_record_identity( + &latest_policy(state, child_id).await, + ) + .unwrap(); + child_hash == parent.hash } - #[test] - fn interactive_exec_rejects_none_payload() { - let msg = ExecSandboxInput { payload: None }; - let err = validate_interactive_exec_start(Some(msg)).unwrap_err(); - assert_eq!(err.code(), tonic::Code::InvalidArgument); + #[tokio::test] + async fn sync_children_copies_the_root_latest_policy_once() { + let state = child_sandboxes_state().await; + let (lead_id, worker_id) = lead_with_copied_child(&state).await; + put_policy_revision_with_status(&state, &lead_id, 2, &lead_policy(false), "pending").await; + + sync_children(&state, &lead_id).await.unwrap(); + sync_children(&state, &lead_id).await.unwrap(); + + assert_eq!( + latest_policy(&state, &worker_id).await.version, + 2, + "two syncs write one revision" + ); + assert!(holds_parent_latest(&state, &worker_id, &lead_id).await); } - #[test] - fn interactive_exec_rejects_missing_sandbox_name() { - use openshell_core::proto::exec_sandbox_input; - let msg = ExecSandboxInput { - payload: Some(exec_sandbox_input::Payload::Start(ExecSandboxRequest { - command: vec!["bash".to_string()], - ..Default::default() - })), - }; - let err = validate_interactive_exec_start(Some(msg)).unwrap_err(); - assert_eq!(err.code(), tonic::Code::InvalidArgument); - assert!(err.message().contains("sandbox")); + #[tokio::test] + async fn the_scan_catches_up_the_children_of_every_root() { + let state = child_sandboxes_state().await; + let mut pairs = Vec::new(); + for (lead, worker) in [("lead", "worker1"), ("lead2", "worker2")] { + let lead_id = put_parent_record(&state, lead, &[], None, false).await; + let worker_id = create_child(&state, worker, lead) + .await + .object_id() + .to_string(); + put_policy_revision_with_status(&state, &lead_id, 2, &lead_policy(false), "loaded") + .await; + pairs.push((lead_id, worker_id)); + } + + sync_all_children(&state).await.unwrap(); + + for (lead_id, worker_id) in pairs { + assert!(holds_parent_latest(&state, &worker_id, &lead_id).await); + } } - #[test] - fn interactive_exec_rejects_missing_command() { - use openshell_core::proto::exec_sandbox_input; - let msg = ExecSandboxInput { - payload: Some(exec_sandbox_input::Payload::Start(ExecSandboxRequest { - sandbox: "test-id".to_string(), - workspace_scope: None, - ..Default::default() - })), + #[tokio::test] + async fn one_child_failing_to_sync_does_not_hold_back_its_siblings() { + let state = child_sandboxes_state().await; + let lead_id = put_parent_record(&state, "lead", &[], None, false).await; + let stuck_id = create_child(&state, "worker1", "lead") + .await + .object_id() + .to_string(); + let free_id = create_child(&state, "worker2", "lead") + .await + .object_id() + .to_string(); + put_policy_revision_with_status(&state, &lead_id, 2, &lead_policy(false), "loaded").await; + state + .compute + .set_mutation_lock_timeout_for_tests(std::time::Duration::from_millis(50)); + // Another task holds the stuck child's lock until the sync is done. + let (held_tx, held_rx) = oneshot::channel(); + let (release_tx, release_rx) = oneshot::channel::<()>(); + let holder = { + let state = Arc::clone(&state); + let stuck_id = stuck_id.clone(); + tokio::spawn(async move { + let _guard = state + .compute + .mutation_guard(MutationScope::sandbox("default", &stuck_id)) + .await + .unwrap(); + held_tx.send(()).unwrap(); + let _ = release_rx.await; + }) }; - let err = validate_interactive_exec_start(Some(msg)).unwrap_err(); - assert_eq!(err.code(), tonic::Code::InvalidArgument); - assert!(err.message().contains("command")); + held_rx.await.unwrap(); + + let err = sync_children(&state, &lead_id).await.unwrap_err(); + release_tx.send(()).unwrap(); + holder.await.unwrap(); + assert!( + err.message().contains("1 child sandbox"), + "{}", + err.message() + ); + + assert_eq!(latest_policy(&state, &stuck_id).await.version, 1); + assert!(holds_parent_latest(&state, &free_id, &lead_id).await); } - #[test] - fn interactive_exec_rejects_invalid_env_key() { - use openshell_core::proto::exec_sandbox_input; - let msg = ExecSandboxInput { - payload: Some(exec_sandbox_input::Payload::Start(ExecSandboxRequest { - sandbox: "test-id".to_string(), - workspace_scope: None, - command: vec!["bash".to_string()], - environment: std::iter::once(("bad key!".to_string(), "val".to_string())).collect(), - ..Default::default() - })), + #[tokio::test] + async fn a_synced_copy_matches_a_copy_made_at_create() { + let state = child_sandboxes_state().await; + let lead_id = put_parent_record(&state, "lead", &[], None, false).await; + // A marker the gateway stamps at delivery; a copy must clear it. + let mut policy = lead_policy(false); + policy.network_policies.get_mut("api").unwrap().endpoints[0].provider_credentialed = true; + put_policy_revision_with_status(&state, &lead_id, 2, &policy, "loaded").await; + let created_id = create_child(&state, "worker1", "lead") + .await + .object_id() + .to_string(); + // A child whose history was not copied from this parent. + let link = openshell_core::proto::SandboxParent { + name: "lead".to_string(), + id: lead_id.clone(), }; - let err = validate_interactive_exec_start(Some(msg)).unwrap_err(); - assert_eq!(err.code(), tonic::Code::InvalidArgument); - assert!(err.message().contains("environment")); + let synced_id = put_parent_record(&state, "worker2", &[], Some(link), false).await; + + sync_children(&state, &lead_id).await.unwrap(); + + let created = latest_policy(&state, &created_id).await; + let synced = latest_policy(&state, &synced_id).await; + assert_eq!(created.version, 1, "the sync leaves the current copy alone"); + assert_eq!(synced.version, 2); + assert_eq!(synced.policy_hash, created.policy_hash); + assert_eq!(synced.policy_payload, created.policy_payload); + } + + /// A parent policy the child cannot load: it binds a credential from a + /// provider the child does not have. + fn unloadable_on_child() -> openshell_core::proto::SandboxPolicy { + let mut policy = lead_policy(false); + let endpoint = &mut policy.network_policies.get_mut("api").unwrap().endpoints[0]; + endpoint.protocol = "rest".to_string(); + endpoint.access = openshell_core::proto::NetworkAccessPreset::Full as i32; + endpoint.credential_binding = Some(openshell_core::proto::NetworkCredentialBinding { + provider: "work-cloud".to_string(), + }); + policy } - #[test] - fn interactive_exec_accepts_valid_start() { - use openshell_core::proto::exec_sandbox_input; - let msg = ExecSandboxInput { - payload: Some(exec_sandbox_input::Payload::Start(ExecSandboxRequest { - sandbox: "test-id".to_string(), - workspace_scope: None, - command: vec!["bash".to_string()], - tty: true, - cols: 120, - rows: 40, - ..Default::default() - })), - }; - let req = validate_interactive_exec_start(Some(msg)).unwrap(); - assert_eq!(req.sandbox, "test-id"); - assert_eq!(req.command, vec!["bash"]); - assert!(req.tty); - assert_eq!(req.cols, 120); - assert_eq!(req.rows, 40); + /// The configuration a child's own supervisor receives. + async fn child_config( + state: &Arc, + child_id: &str, + ) -> openshell_core::proto::GetSandboxConfigResponse { + super::super::policy::handle_get_sandbox_config( + state, + sandbox_request( + child_id, + openshell_core::proto::GetSandboxConfigRequest { + name: "worker1".to_string(), + workspace_scope: Some(default_scope()), + supported_capabilities: Vec::new(), + }, + ), + ) + .await + .expect("the child receives a configuration, not an error") + .into_inner() } + /// A child copies its root's latest revision whatever its status, so a + /// revision must keep its policy when it is superseded or fails. #[tokio::test] - async fn interactive_exec_rejects_sandbox_not_found() { - let state = test_server_state().await; + async fn a_superseded_or_failed_revision_keeps_its_policy() { + let state = child_sandboxes_state().await; + let lead_id = put_parent_record(&state, "lead", &[], None, false).await; + put_policy_revision_with_status(&state, &lead_id, 2, &lead_policy(false), "failed").await; + state + .store + .supersede_older_policies(&lead_id, 3) + .await + .unwrap(); - let req = ExecSandboxRequest { - sandbox: "nonexistent".to_string(), - workspace_scope: None, - command: vec!["bash".to_string()], - tty: true, - ..Default::default() - }; - let sandbox_result = state + for (version, status) in [(1, "superseded"), (2, "failed")] { + let record = state + .store + .get_policy_by_version(&lead_id, version) + .await + .unwrap() + .unwrap(); + assert_eq!(record.status, status); + assert!( + ParentPolicyCopy::of(&record).is_ok(), + "v{version} still decodes" + ); + } + let failed = state .store - .get_message_by_name::("default", &req.sandbox) + .get_policy_by_version(&lead_id, 2) .await + .unwrap() .unwrap(); - assert!(sandbox_result.is_none()); + let (policy, _) = super::super::policy::canonical_policy_record_identity(&failed).unwrap(); + assert!(policy.network_policies.contains_key("api")); } #[tokio::test] - async fn interactive_exec_rejects_sandbox_not_ready() { - let state = test_server_state().await; - let mut sandbox = test_sandbox("not-ready", Vec::new()); - sandbox.set_phase(SandboxPhase::Provisioning as i32); - state.store.put_message(&sandbox).await.unwrap(); + async fn children_fail_closed_even_when_the_gateway_retains_the_last_valid_policy() { + let mut state = child_sandboxes_state().await; + Arc::get_mut(&mut state) + .unwrap() + .config + .policy_validation_failure_mode = + openshell_core::PolicyValidationFailureMode::RetainLastValid; + let (lead_id, worker_id) = lead_with_copied_child(&state).await; + put_policy_revision_with_status(&state, &lead_id, 2, &unloadable_on_child(), "loaded") + .await; + sync_children(&state, &lead_id).await.unwrap(); + + let config = child_config(&state, &worker_id).await; + assert!(!config.configuration_admitted); + assert!( + config + .configuration_error + .contains("repair credential bindings"), + "{}", + config.configuration_error + ); + assert_eq!(config.policy_validation_failure_mode, "fail_closed"); + + let lead_config = super::super::policy::handle_get_sandbox_config( + &state, + sandbox_request( + &lead_id, + openshell_core::proto::GetSandboxConfigRequest { + name: "lead".to_string(), + workspace_scope: Some(default_scope()), + supported_capabilities: Vec::new(), + }, + ), + ) + .await + .unwrap() + .into_inner(); + assert_eq!( + lead_config.policy_validation_failure_mode, + "retain_last_valid" + ); + } + + #[tokio::test] + async fn child_proposals_are_rejected_and_not_stored() { + let state = child_sandboxes_state().await; + let worker_id = put_lead_and_worker(&state).await; + + let response = super::super::policy::handle_submit_policy_analysis( + &state, + authed_request(openshell_core::proto::SubmitPolicyAnalysisRequest { + workspace_scope: Some(default_scope()), + name: "worker1".to_string(), + analysis_mode: "agent_authored".to_string(), + proposed_chunks: vec![openshell_core::proto::PolicyChunk { + rule_name: "api".to_string(), + proposed_rule: lead_policy(false).network_policies.remove("api"), + ..Default::default() + }], + ..Default::default() + }), + ) + .await + .expect("the submission itself succeeds") + .into_inner(); + assert_eq!(response.accepted_chunks, 0); + assert_eq!(response.rejected_chunks, 1); + assert!( + response.rejection_reasons[0].contains("child sandboxes use their parent's policy"), + "{:?}", + response.rejection_reasons + ); let stored = state .store - .get_message::("sandbox-not-ready") + .list_draft_chunks(&worker_id, None) .await - .unwrap() .unwrap(); - assert_ne!( - SandboxPhase::try_from(stored.phase()).ok(), - Some(SandboxPhase::Ready) + assert!(stored.is_empty(), "a child's proposal must not be stored"); + } + + #[tokio::test] + async fn approving_a_proposal_on_a_child_is_refused() { + let state = child_sandboxes_state().await; + put_lead_and_worker(&state).await; + + let err = super::super::policy::handle_approve_draft_chunk( + &state, + authed_request(openshell_core::proto::ApproveDraftChunkRequest { + sandbox: "worker1".to_string(), + workspace_scope: Some(default_scope()), + chunk_id: "chunk-1".to_string(), + ..Default::default() + }), + ) + .await + .unwrap_err(); + assert_eq!(err.code(), tonic::Code::FailedPrecondition); + assert!( + err.message() + .contains("child sandboxes use their parent's policy"), + "{}", + err.message() ); } #[tokio::test] - async fn create_sandbox_rejects_provider_credential_key_collisions() { - let state = test_server_state().await; - import_test_profile(&state, "outlook").await; - import_test_profile(&state, "google-drive").await; - state - .store - .put_message(&test_provider("provider-a", "outlook")) - .await - .unwrap(); - state - .store - .put_message(&test_provider("provider-b", "google-drive")) - .await - .unwrap(); + async fn attaching_a_provider_the_parent_lacks_to_a_child_is_refused() { + let state = child_sandboxes_state().await; + put_lead_and_worker(&state).await; - let err = handle_create_sandbox( + let err = handle_attach_sandbox_provider( &state, - authed_request(CreateSandboxRequest { + authed_request(AttachSandboxProviderRequest { request_id: String::new(), - name: "collision".to_string(), - spec: Some(SandboxSpec { - providers: vec!["provider-a".to_string(), "provider-b".to_string()], - ..Default::default() - }), - labels: HashMap::new(), - annotations: HashMap::new(), - workspace_scope: Some(openshell_core::proto::workspace_selector( - "default".to_string(), - )), - await_main_process_attachment: false, - workload_template: String::new(), - service_exposures: Vec::new(), + sandbox: "worker1".to_string(), + workspace_scope: Some(default_scope()), + provider: "work-github".to_string(), + expected_resource_version: 0, }), ) .await .unwrap_err(); - assert_eq!(err.code(), tonic::Code::FailedPrecondition); - assert!(err.message().contains("TOKEN")); - assert!(err.message().contains("provider-a")); - assert!(err.message().contains("provider-b")); + assert!( + err.message() + .contains("provider 'work-github' is not attached to parent 'lead'"), + "{}", + err.message() + ); } #[tokio::test] - async fn provider_create_failure_releases_global_guard_before_compensation() { - let state = test_server_state_with_compute_driver( - "test", - Arc::new(NoopTestDriver::authenticating_sandbox_with_runtime( - "unused", "", - )), - ) - .await; + async fn a_child_being_deleted_keeps_its_slot_until_its_record_is_gone() { + let state = child_sandboxes_state_with_limit(2).await; + let lead_id = put_parent_record(&state, "lead", &[], None, false).await; + let link = openshell_core::proto::SandboxParent { + name: "lead".to_string(), + id: lead_id, + }; + put_parent_record(&state, "worker1", &[], Some(link.clone()), false).await; + let leaving = put_parent_record(&state, "worker2", &[], Some(link), true).await; + let create = || { + handle_create_sandbox( + &state, + authed_request(child_request("worker3", "lead", SandboxSpec::default())), + ) + }; + + let err = create().await.unwrap_err(); + assert_eq!(err.code(), tonic::Code::ResourceExhausted); + assert_eq!( + err.message(), + "sandbox 'lead' has reached its limit of 2 children, \ + 1 of them still being deleted; try again shortly" + ); + + // The driver finished removing it, so its record is gone. state .store - .put_message(&test_provider("work-github", "github")) + .delete(Sandbox::object_type(), &leaving) .await .unwrap(); + create() + .await + .expect("the slot is free once the delete finishes"); + } - let result = tokio::time::timeout( - std::time::Duration::from_secs(1), + #[tokio::test] + async fn create_child_sandbox_stops_at_the_limit() { + let state = child_sandboxes_state_with_limit(2).await; + put_parent_record(&state, "lead", &[], None, false).await; + put_parent_record(&state, "other-lead", &[], None, false).await; + + for name in ["worker1", "worker2"] { handle_create_sandbox( &state, - authed_request(CreateSandboxRequest { - name: "provider-fail".to_string(), - spec: Some(SandboxSpec { - providers: vec!["work-github".to_string()], - ..Default::default() - }), - workspace_scope: Some(openshell_core::proto::workspace_selector( - "default".to_string(), - )), - ..Default::default() - }), - ), + authed_request(child_request(name, "lead", SandboxSpec::default())), + ) + .await + .expect("a child under the limit is created"); + } + let err = handle_create_sandbox( + &state, + authed_request(child_request("worker3", "lead", SandboxSpec::default())), ) .await - .expect("create compensation must not deadlock") - .expect_err("empty runtime identity must fail create"); + .unwrap_err(); + assert_eq!(err.code(), tonic::Code::ResourceExhausted); + assert!( + err.message() + .contains("sandbox 'lead' has reached its limit of 2 children"), + "{}", + err.message() + ); - assert_eq!(result.code(), tonic::Code::Internal, "{}", result.message()); - let retained = state - .store - .get_message_by_name::("default", "provider-fail") + // Each parent has its own limit. + handle_create_sandbox( + &state, + authed_request(child_request( + "worker4", + "other-lead", + SandboxSpec::default(), + )), + ) + .await + .expect("another parent's children do not count"); + } + + #[tokio::test] + async fn create_child_sandbox_with_zero_limit_is_refused() { + let state = child_sandboxes_state_with_limit(0).await; + put_parent_record(&state, "lead", &[], None, false).await; + + let err = handle_create_sandbox( + &state, + authed_request(child_request("worker1", "lead", SandboxSpec::default())), + ) + .await + .unwrap_err(); + assert_eq!(err.code(), tonic::Code::ResourceExhausted); + } + + #[tokio::test] + async fn concurrent_child_creates_never_exceed_the_limit() { + let state = child_sandboxes_state_with_limit(3).await; + put_parent_record(&state, "lead", &[], None, false).await; + + let creates = (0..8).map(|index| { + let state = state.clone(); + tokio::spawn(async move { + handle_create_sandbox( + &state, + authed_request(child_request( + &format!("worker{index}"), + "lead", + SandboxSpec::default(), + )), + ) + .await + }) + }); + let successes = future::join_all(creates) .await - .unwrap() - .expect("accepted asynchronous cleanup must retain the sandbox record"); - assert_eq!(retained.phase(), SandboxPhase::Deleting as i32); + .into_iter() + .filter_map(|joined| joined.expect("create task").ok()) + .count(); + assert_eq!(successes, 3); } #[tokio::test] - async fn create_sandbox_uses_configured_provider_profile_sources() { + async fn create_child_sandbox_is_refused_when_disabled() { let state = test_server_state().await; + put_parent_record(&state, "lead", &[], None, false).await; - let response = handle_create_sandbox( + let err = handle_create_sandbox( &state, - authed_request(CreateSandboxRequest { - request_id: String::new(), - name: "user-catalog".to_string(), - spec: Some(SandboxSpec::default()), - labels: HashMap::new(), - annotations: HashMap::new(), - workspace_scope: Some(openshell_core::proto::workspace_selector( - "default".to_string(), - )), - await_main_process_attachment: false, - workload_template: String::new(), - service_exposures: Vec::new(), - }), + authed_request(child_request("worker1", "lead", SandboxSpec::default())), ) .await - .expect("an imported github profile should resolve from the user source") - .into_inner(); + .unwrap_err(); - assert_eq!( - response.sandbox.expect("created sandbox").object_name(), - "user-catalog" - ); + assert_eq!(err.code(), tonic::Code::FailedPrecondition); + assert!(err.message().contains("child sandboxes are disabled")); + } + + #[tokio::test] + async fn listing_children_is_refused_when_disabled() { + let state = test_server_state().await; + put_parent_record(&state, "lead", &[], None, false).await; + + let err = handle_list_sandboxes( + &state, + authed_request(list_children_request("lead", 100, String::new())), + ) + .await + .unwrap_err(); + + assert_eq!(err.code(), tonic::Code::FailedPrecondition); + assert!(err.message().contains("child sandboxes are disabled")); + } + + #[tokio::test] + async fn create_child_sandbox_refuses_an_invalid_parent_or_request() { + let state = child_sandboxes_state().await; + let lead_id = put_parent_record(&state, "lead", &["work-github"], None, false).await; + put_parent_record( + &state, + "worker1", + &[], + Some(openshell_core::proto::SandboxParent { + name: "lead".to_string(), + id: lead_id, + }), + false, + ) + .await; + put_parent_record(&state, "leaving", &[], None, true).await; + + let cases = [ + ( + "missing", + SandboxSpec::default(), + tonic::Code::FailedPrecondition, + "parent sandbox 'missing' not found", + ), + ( + "leaving", + SandboxSpec::default(), + tonic::Code::FailedPrecondition, + "parent sandbox 'leaving' is being deleted", + ), + ( + "worker1", + SandboxSpec::default(), + tonic::Code::FailedPrecondition, + "only one level of child sandboxes is supported", + ), + ( + "lead", + SandboxSpec { + policy: Some(openshell_core::proto::SandboxPolicy::default()), + ..Default::default() + }, + tonic::Code::InvalidArgument, + "a child sandbox uses its parent's policy", + ), + ( + "lead", + SandboxSpec { + providers: vec!["work-slack".to_string()], + ..Default::default() + }, + tonic::Code::FailedPrecondition, + "provider 'work-slack' is not attached to parent 'lead'", + ), + ]; + for (parent, spec, code, message) in cases { + let err = handle_create_sandbox( + &state, + authed_request(child_request("nested", parent, spec)), + ) + .await + .unwrap_err(); + assert_eq!(err.code(), code, "{parent}: {}", err.message()); + assert!( + err.message().contains(message), + "{parent}: {}", + err.message() + ); + } } #[tokio::test] @@ -7661,6 +12012,7 @@ mod tests { let err = handle_create_sandbox( &state, authed_request(CreateSandboxRequest { + parent: String::new(), request_id: String::new(), name: "orphan-sandbox".to_string(), spec: Some(SandboxSpec { @@ -7743,6 +12095,7 @@ mod tests { let err = handle_create_sandbox( &state, authed_request(CreateSandboxRequest { + parent: String::new(), request_id: String::new(), name: "reserved-policy-key".to_string(), spec: Some(SandboxSpec { @@ -8143,6 +12496,7 @@ mod tests { let response = handle_create_sandbox( &state, authed_request(CreateSandboxRequest { + parent: String::new(), request_id: String::new(), name: "annotated".to_string(), spec: Some(SandboxSpec::default()), @@ -8203,6 +12557,7 @@ mod tests { let err = handle_create_sandbox( &state, authed_request(CreateSandboxRequest { + parent: String::new(), request_id: String::new(), name: "reserved".to_string(), spec: Some(SandboxSpec::default()), @@ -8528,6 +12883,7 @@ mod tests { let response = handle_create_sandbox( &state, authed_request(CreateSandboxRequest { + parent: String::new(), request_id: String::new(), name: "partial-id".to_string(), spec: Some(SandboxSpec { @@ -8599,6 +12955,7 @@ mod tests { let response = handle_create_sandbox( &state, authed_request(CreateSandboxRequest { + parent: String::new(), request_id: String::new(), name: "kube-partial-id".to_string(), spec: Some(SandboxSpec { @@ -8653,6 +13010,7 @@ mod tests { let err = handle_create_sandbox( &state, authed_request(CreateSandboxRequest { + parent: String::new(), request_id: String::new(), name: "bad-label".to_string(), spec: Some(SandboxSpec::default()), @@ -8694,6 +13052,7 @@ mod tests { handle_create_sandbox( &task_state, authed_request(CreateSandboxRequest { + parent: String::new(), request_id: String::new(), name: "guarded-create".to_string(), spec: Some(SandboxSpec { @@ -9351,6 +13710,7 @@ mod tests { let created = handle_create_sandbox( &state, authed_request(CreateSandboxRequest { + parent: String::new(), request_id: String::new(), name: "from-template".to_string(), spec: Some(SandboxSpec { @@ -9446,6 +13806,7 @@ mod tests { let created = handle_create_sandbox( &state, authed_request(CreateSandboxRequest { + parent: String::new(), request_id: String::new(), name: "from-template".to_string(), spec: Some(SandboxSpec::default()), @@ -9500,6 +13861,7 @@ mod tests { let created = handle_create_sandbox( &state, authed_request(CreateSandboxRequest { + parent: String::new(), request_id: String::new(), name: "from-template".to_string(), spec: Some(SandboxSpec::default()), @@ -9541,6 +13903,7 @@ mod tests { let err = handle_create_sandbox( &state, authed_request(CreateSandboxRequest { + parent: String::new(), request_id: String::new(), name: "from-corrupt".to_string(), spec: Some(SandboxSpec::default()), @@ -9580,6 +13943,7 @@ mod tests { let err = handle_create_sandbox( &state, authed_request(CreateSandboxRequest { + parent: String::new(), request_id: String::new(), name: "bad-template-create".to_string(), spec: Some(SandboxSpec { @@ -9610,6 +13974,7 @@ mod tests { let err = handle_create_sandbox( &state, authed_request(CreateSandboxRequest { + parent: String::new(), request_id: String::new(), name: "bad-template-create".to_string(), spec: Some(SandboxSpec::default()), @@ -9637,6 +14002,7 @@ mod tests { let err = handle_create_sandbox( &state, authed_request(CreateSandboxRequest { + parent: String::new(), request_id: String::new(), name: "bad-template-create".to_string(), spec: Some(SandboxSpec { @@ -9667,6 +14033,7 @@ mod tests { let err = handle_create_sandbox( &state, authed_request(CreateSandboxRequest { + parent: String::new(), request_id: String::new(), name: "bad-direct-create".to_string(), spec: Some(SandboxSpec { @@ -10660,6 +15027,7 @@ mod tests { page_size: 100, page_token: String::new(), label_selector: String::new(), + parent: String::new(), workspace_scope: Some(openshell_core::proto::workspace_selector( "default".to_string(), )), @@ -10678,6 +15046,7 @@ mod tests { page_size: 100, page_token: String::new(), label_selector: String::new(), + parent: String::new(), workspace_scope: Some(openshell_core::proto::workspace_selector( "beta".to_string(), )), @@ -10703,6 +15072,7 @@ mod tests { page_size: 100, page_token: String::new(), label_selector: String::new(), + parent: String::new(), workspace_scope: Some(openshell_core::proto::workspace_selector( "default".to_string(), )), @@ -10748,6 +15118,7 @@ mod tests { page_size: 100, page_token: String::new(), label_selector: String::new(), + parent: String::new(), workspace_scope: Some(openshell_core::proto::all_workspaces_selector()), }), ) @@ -10761,6 +15132,7 @@ mod tests { page_size: 1, page_token: String::new(), label_selector: String::new(), + parent: String::new(), workspace_scope: Some(openshell_core::proto::all_workspaces_selector()), }), ) @@ -10775,6 +15147,7 @@ mod tests { page_size: 100, page_token: first_page.next_page_token, label_selector: String::new(), + parent: String::new(), workspace_scope: Some(openshell_core::proto::all_workspaces_selector()), }), ) diff --git a/crates/openshell-server/src/http.rs b/crates/openshell-server/src/http.rs index 20fe4f88c5..a0e053e986 100644 --- a/crates/openshell-server/src/http.rs +++ b/crates/openshell-server/src/http.rs @@ -183,6 +183,11 @@ pub fn http_router(state: Arc) -> Router { if state.config.enable_websocket_tunnel { router = router.merge(crate::ws_tunnel::router(state.clone())); } + // Not registered while child sandboxes are off, for users and sandboxes + // alike. + if state.config.enable_child_sandboxes { + router = router.merge(crate::mcp::router()); + } router.layer(middleware::from_fn_with_state( state, sandbox_service_routing_first, diff --git a/crates/openshell-server/src/lib.rs b/crates/openshell-server/src/lib.rs index 8edc7adc6b..c5d5d25f1c 100644 --- a/crates/openshell-server/src/lib.rs +++ b/crates/openshell-server/src/lib.rs @@ -31,6 +31,7 @@ mod gateway_ocsf; mod gateway_ring; mod grpc; mod http; +mod mcp; mod middleware; mod multiplex; mod network_trust; @@ -471,6 +472,7 @@ fn is_benign_tls_handshake_failure(error: &std::io::Error) -> bool { } const METRICS_TLS_HANDSHAKE_WARNING_INTERVAL: Duration = Duration::from_mins(1); +const CHILD_SANDBOX_SYNC_INTERVAL: Duration = Duration::from_secs(30); #[derive(Default)] struct MetricsTlsHandshakeLogState { @@ -665,7 +667,9 @@ impl ServerState { let sandbox_identity = spiffe_broker::sandbox_identity_provider(&config).map_err(Error::config)?; let replica_id = compute::lease::replica_id(); - let compute = compute.with_sandbox_updates(config.enable_sandbox_updates); + let compute = compute + .with_sandbox_updates(config.enable_sandbox_updates) + .with_child_sandboxes(config.enable_child_sandboxes); compute.configure_ssh_identities(credentials.clone()); let service_route_index = Arc::new(service_routing::ServiceRouteIndex::new( config.service_routing_discriminator().map(str::to_string), @@ -1339,6 +1343,31 @@ pub(crate) async fn run_server( } startup_tx.send_replace(true); + // Bring children up to their roots now, for changes made while the + // gateway was down, and then every 30 seconds, for copies a failed or + // cancelled request or another replica left undone. + if config.enable_child_sandboxes { + let state = state.clone(); + let mut shutdown_rx = shutdown_rx.clone(); + tokio::spawn(async move { + let mut interval = tokio::time::interval(CHILD_SANDBOX_SYNC_INTERVAL); + interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); + loop { + tokio::select! { + _ = interval.tick() => {} + changed = shutdown_rx.changed() => { + if changed.is_err() || *shutdown_rx.borrow() { + return; + } + continue; + } + } + if let Err(error) = grpc::sync_all_children(&state).await { + warn!(error = %error, "child sandbox policy sync failed"); + } + } + }); + } // The poller and sweeper exist to observe writes made by other replicas. // Single-replica backends have none, so they would only add load. if !store.is_single_replica() { diff --git a/crates/openshell-server/src/mcp.rs b/crates/openshell-server/src/mcp.rs new file mode 100644 index 0000000000..0f3102800f --- /dev/null +++ b/crates/openshell-server/src/mcp.rs @@ -0,0 +1,2379 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! MCP endpoint for agents in root sandboxes (RFC 0021). +//! +//! `POST /mcp` carries one JSON-RPC message and gets one JSON reply; there are +//! no MCP sessions. Each tool is a thin wrapper over an existing RPC, sent +//! through the connection's own gRPC stack, so authentication, authorization, +//! rate limits and interceptors apply exactly as for a direct gRPC call. The +//! request carries [`McpOrigin`], which is the only way a sandbox caller can +//! reach the user-facing methods in [`SANDBOX_TOOL_METHODS`]. + +use crate::auth::audit::{self, RequestOrigin}; +use crate::auth::principal::Principal; +use crate::multiplex::CallerAuthenticator; +use axum::Extension; +use axum::Router; +use axum::body::Body; +use axum::http::{HeaderMap, StatusCode}; +use axum::response::{IntoResponse, Response}; +use axum::routing::post; +use openshell_core::proto::open_shell_client::OpenShellClient; +use openshell_core::proto::{ + CreateSandboxRequest, DeleteSandboxRequest, ExecSandboxRequest, ListSandboxTemplatesRequest, + ListSandboxesRequest, Sandbox, SandboxPhase, SandboxSpec, SandboxWorkloadTemplate, +}; +use openshell_core::{ObjectId, ObjectName}; +use serde_json::{Value, json}; +use std::fmt::Write as _; +use std::sync::Arc; +use tower::util::BoxCloneSyncService; +use tracing::warn; + +type BoxError = Box; +type GrpcStack = BoxCloneSyncService< + http::Request, + http::Response, + BoxError, +>; + +const MCP_PATH: &str = "/mcp"; +const SUPPORTED_PROTOCOL_VERSIONS: &[&str] = &["2025-11-25", "2025-06-18"]; +/// Largest request body read, checked only after the caller is authenticated. +const MAX_REQUEST_BYTES: usize = 2 * 1024 * 1024; + +/// Methods a sandbox caller may reach, and only with [`McpOrigin`]. +const SANDBOX_TOOL_METHODS: [&str; 6] = [ + "/openshell.v1.OpenShell/CreateSandbox", + "/openshell.v1.OpenShell/ListSandboxes", + "/openshell.v1.OpenShell/ListSandboxTemplates", + "/openshell.v1.OpenShell/ExecSandbox", + "/openshell.v1.OpenShell/DeleteSandbox", + "/openshell.v1.OpenShell/GetSandboxLogs", +]; + +/// Marks a gRPC request the `/mcp` endpoint built in process. Only Rust code +/// can set request extensions, so a network caller can never carry it. +#[derive(Clone, Copy, Debug)] +pub struct McpOrigin; + +pub fn is_sandbox_tool_method(path: &str) -> bool { + SANDBOX_TOOL_METHODS.contains(&path) +} + +/// One gateway connection's caller resolution and gRPC stack. +#[derive(Clone)] +pub struct McpConnection { + auth: CallerAuthenticator, + grpc: GrpcStack, + create_wait: CreateWait, + /// Read only to record, in audit events, the user a sandbox caller acts for. + store: Option>, +} + +/// How long `create_sandbox` waits for a child to become ready, and how often +/// it looks. +#[derive(Clone, Copy)] +struct CreateWait { + limit: std::time::Duration, + first_poll: std::time::Duration, + poll: std::time::Duration, +} + +impl Default for CreateWait { + fn default() -> Self { + Self { + limit: std::time::Duration::from_secs(45), + first_poll: std::time::Duration::from_secs(1), + poll: std::time::Duration::from_secs(2), + } + } +} + +impl McpConnection { + pub fn new(auth: CallerAuthenticator, grpc: S) -> Self + where + S: tower::Service< + http::Request, + Response = http::Response, + > + Clone + + Send + + Sync + + 'static, + S::Error: Into, + S::Future: Send + 'static, + { + use tower::ServiceExt; + Self { + auth, + grpc: BoxCloneSyncService::new(grpc.map_err(Into::into)), + create_wait: CreateWait::default(), + store: None, + } + } + + /// Let audit events record the user each sandbox caller acts for. + #[must_use] + pub fn with_store(mut self, store: Arc) -> Self { + self.store = Some(store); + self + } + + /// Shorten the create wait so tests need not sleep for real. + #[cfg(test)] + pub fn with_short_create_wait(mut self) -> Self { + self.create_wait = CreateWait { + limit: std::time::Duration::from_millis(50), + first_poll: std::time::Duration::from_millis(5), + poll: std::time::Duration::from_millis(10), + }; + self + } +} + +pub fn router() -> Router { + Router::new().route( + MCP_PATH, + post(handle).get(|| async { StatusCode::METHOD_NOT_ALLOWED }), + ) +} + +async fn handle( + Extension(connection): Extension, + headers: HeaderMap, + body: Body, +) -> Response { + // Browsers always send Origin on a cross-site POST; the CLI bridge and the + // sandbox door never do. So no web page can drive /mcp with a user's + // session (DNS rebinding included). + if headers.contains_key(http::header::ORIGIN) { + return ( + StatusCode::FORBIDDEN, + "requests with an Origin header are refused", + ) + .into_response(); + } + if let Some(version) = headers.get("mcp-protocol-version") + && !version + .to_str() + .is_ok_and(|v| SUPPORTED_PROTOCOL_VERSIONS.contains(&v)) + { + return (StatusCode::BAD_REQUEST, "unsupported MCP-Protocol-Version").into_response(); + } + // Authenticate from the headers before reading the body. + let Ok(principal) = connection.auth.authenticate(&headers, MCP_PATH).await else { + return StatusCode::UNAUTHORIZED.into_response(); + }; + // A user acts in the workspace the bridge names, like the CLI; a sandbox + // always acts in its own, which its handlers read from its record. + let workspace = match &principal { + Principal::Sandbox(_) => None, + Principal::User(_) => match headers.get(WORKSPACE_HEADER).map(|value| value.to_str()) { + None => Some(DEFAULT_WORKSPACE.to_string()), + Some(Ok(workspace)) => Some(workspace.to_string()), + Some(Err(_)) => { + return (StatusCode::BAD_REQUEST, "invalid workspace header").into_response(); + } + }, + Principal::Anonymous => return StatusCode::UNAUTHORIZED.into_response(), + _ => { + return ( + StatusCode::FORBIDDEN, + "MCP is available to users and sandboxes only", + ) + .into_response(); + } + }; + let Ok(body) = axum::body::to_bytes(body, MAX_REQUEST_BYTES).await else { + return ( + StatusCode::PAYLOAD_TOO_LARGE, + "request body is larger than the 2 MiB /mcp accepts", + ) + .into_response(); + }; + + let Ok(message) = serde_json::from_slice::(&body) else { + return rpc_error(&Value::Null, -32700, "parse error"); + }; + if message.is_array() { + return rpc_error(&Value::Null, -32600, "batch requests are not supported"); + } + // Notifications (no id) get no response body. + let Some(id) = message.get("id").cloned() else { + return StatusCode::ACCEPTED.into_response(); + }; + let params = message.get("params").cloned().unwrap_or(Value::Null); + match message + .get("method") + .and_then(Value::as_str) + .unwrap_or_default() + { + "initialize" => rpc_ok( + &id, + json!({ + "protocolVersion": negotiate_protocol_version( + params.get("protocolVersion").and_then(Value::as_str), + ), + "capabilities": {"tools": {"listChanged": false}}, + "serverInfo": {"name": "openshell-gateway", "version": openshell_core::VERSION}, + "instructions": "Create and manage OpenShell sandboxes: a sandbox manages its own child sandboxes, a user the sandboxes in their workspace.", + }), + ), + "ping" => rpc_ok(&id, json!({})), + "tools/list" => { + let templates = match &principal { + Principal::Sandbox(_) => { + let call = Call { + connection: &connection, + headers: &headers, + workspace, + }; + match agent_templates(&call).await { + Ok(templates) => templates, + Err(ToolError::Unauthenticated) => { + return StatusCode::UNAUTHORIZED.into_response(); + } + // The tools still work without the list; a create + // names its template either way. + Err(ToolError::Refused(error)) => { + warn!(error = %error.message, "could not list templates for the MCP tool list"); + Vec::new() + } + } + } + _ => Vec::new(), + }; + let user = !matches!(principal, Principal::Sandbox(_)); + rpc_ok(&id, json!({"tools": tool_definitions(&templates, user)})) + } + "tools/call" => { + let name = params + .get("name") + .and_then(Value::as_str) + .unwrap_or_default(); + if !TOOLS.iter().any(|tool| tool.name == name) { + return rpc_error(&id, -32602, &format!("unknown tool '{name}'")); + } + let arguments = params.get("arguments").cloned().unwrap_or(Value::Null); + let call = Call { + connection: &connection, + headers: &headers, + workspace, + }; + let result = match name { + "create_sandbox" => create_child(&call, &arguments).await, + "exec" => exec_in_child(&call, &arguments).await, + "delete" => delete_child(&call, &arguments).await, + "logs" => child_logs(&call, &arguments).await, + "list" => list_sandboxes(&call, &arguments).await, + _ => unreachable!("tool names are checked against TOOLS above"), + }; + let origin = RequestOrigin::new(connection.auth.connection_source(), &headers); + let mut details = tool_call_details(name, &arguments, &result); + if let Principal::Sandbox(sandbox) = &principal { + details.push(( + "acting_for", + acting_for(&connection, &sandbox.sandbox_id).await, + )); + } + let details = capped_audit_details(details); + match result { + Ok(content) => { + audit::emit_mcp_tool_call( + &origin, + &principal, + name, + audit::McpOutcome::Allowed, + &details, + ); + rpc_ok(&id, tool_result(&content, false)) + } + Err(ToolError::Unauthenticated) => StatusCode::UNAUTHORIZED.into_response(), + Err(ToolError::Refused(error)) => { + audit::emit_mcp_tool_call( + &origin, + &principal, + name, + audit_outcome(error.code), + &details, + ); + rpc_ok(&id, tool_result(&error.to_json(), true)) + } + } + } + _ => rpc_error(&id, -32601, "method not found"), + } +} + +/// The `exec` tool's text. The gateway has no background jobs: the text +/// tells the caller to detach long work in the sandbox and check on it with +/// later `exec` calls. +const EXEC_DESCRIPTION: &str = concat!( + "Run a command in a sandbox (from a sandbox: one of its children) and return its output. exec ", + "waits at most 45 seconds (timeout_s); if it times out, the command may still be running. For ", + "longer work, start the command detached inside the sandbox and check on it with later exec ", + "calls: run it in its own session, with its input from /dev/null and its output in files, and ", + "write its exit code to a file when it ends. For example: setsid sh -c 'cmd > /tmp/job/out ", + "2> /tmp/job/err; echo $? > /tmp/job/exit' < /dev/null > /dev/null 2>&1 & echo $! . Then use ", + "exec to read /tmp/job/exit and tail /tmp/job/out. Delete the sandbox to stop everything in it.", +); + +struct Tool { + name: &'static str, + description: &'static str, +} + +const TOOLS: &[Tool] = &[ + Tool { + name: "create_sandbox", + description: "Create a sandbox. Called from a sandbox, it creates a child of that sandbox; called by a user, a root, or a child of `parent`. A child never contacts its parent on its own: results come only from exec. Delete a child when its work is done.", + }, + Tool { + name: "list", + description: "List sandboxes: a sandbox's own children, or the sandboxes in a user's workspace.", + }, + Tool { + name: "exec", + description: EXEC_DESCRIPTION, + }, + Tool { + name: "delete", + description: "Delete a sandbox (from a sandbox: one of its children) and everything running in it. Deletion finishes in the background; a later not_found for the same name means it is gone.", + }, + Tool { + name: "logs", + description: "Read a sandbox's own recent log lines (its output and policy denials), newest kept. From a sandbox: one of its children.", + }, +]; + +/// The templates a sandbox caller may create children from, as the gateway +/// lists them for it: only those made available to agents, in its workspace. +async fn agent_templates(call: &Call<'_>) -> Result, ToolError> { + let mut client = OpenShellClient::new(call.connection.grpc.clone()); + // Boxed so the handler future is provably `Send`, as in `caller_children`. + let pending: futures::future::BoxFuture<'_, _> = Box::pin( + client.list_sandbox_templates(call.request(ListSandboxTemplatesRequest::default())), + ); + Ok(pending + .await + .map_err(ToolError::from_status)? + .into_inner() + .templates) +} + +/// The tool list for one caller role: a `user` sees the arguments only users +/// may pass, a sandbox those only sandboxes may pass. `templates` are the +/// ones a sandbox caller may use; they are offered on `create_sandbox` so an +/// agent need not be told their names. +fn tool_definitions(templates: &[SandboxWorkloadTemplate], user: bool) -> Vec { + TOOLS + .iter() + .map(|tool| { + let mut description = tool.description.to_string(); + let schema = match tool.name { + "create_sandbox" => { + let mut template = json!({"type": "string", "description": "Sandbox template made available to agents."}); + if !templates.is_empty() { + let names: Vec<&str> = + templates.iter().map(ObjectName::object_name).collect(); + template["enum"] = json!(names); + let offered: Vec = templates + .iter() + .map(|template| { + let image = template + .spec + .as_ref() + .and_then(|spec| spec.workload.as_ref()) + .map(|workload| workload.image.as_str()) + .filter(|image| !image.is_empty()) + .unwrap_or("the gateway default"); + format!("{} (image {image})", template.object_name()) + }) + .collect(); + let _ = write!( + description, + " Templates you may create a child from: {}. Without a template the child copies your image.", + offered.join(", ") + ); + } + let mut properties = json!({ + "name": {"type": "string", "description": "Name of the new sandbox."}, + "providers": {"type": "array", "items": {"type": "string"}, "description": "Providers to attach; for a child, a subset of its parent's, all of them when omitted."}, + }); + if user { + properties["parent"] = json!({"type": "string", "description": "Root sandbox to create a child of; a root when omitted."}); + properties["image"] = json!({"type": "string", "description": "Container image; the gateway default when omitted."}); + } else { + properties["template"] = template; + } + json!({ + "type": "object", + "properties": properties, + "required": ["name"], + "additionalProperties": false, + }) + } + "exec" => json!({ + "type": "object", + "properties": { + "name": {"type": "string", "description": "Sandbox to run in."}, + "command": {"type": "array", "items": {"type": "string"}, "description": "Program and arguments; not a shell string."}, + "workdir": {"type": "string"}, + "stdin": {"type": "string", "description": "Text passed on stdin."}, + "stdin_base64": {"type": "string", "description": "Bytes passed on stdin, base64-encoded."}, + "timeout_s": {"type": "integer", "minimum": 1, "maximum": MAX_EXEC_TIMEOUT_S, "description": "Seconds to wait for the command, 30 when omitted."}, + }, + "required": ["name", "command"], + "additionalProperties": false, + }), + "delete" => json!({ + "type": "object", + "properties": {"name": {"type": "string", "description": "Sandbox to delete."}}, + "required": ["name"], + "additionalProperties": false, + }), + "logs" => json!({ + "type": "object", + "properties": { + "name": {"type": "string", "description": "Sandbox to read."}, + "lines": {"type": "integer", "minimum": 1, "maximum": MAX_LOG_LINES}, + "since": {"type": "string", "description": "Only lines at or after this RFC 3339 time."}, + }, + "required": ["name"], + "additionalProperties": false, + }), + "list" if user => json!({ + "type": "object", + "properties": {"parent": {"type": "string", "description": "List only this root's children."}}, + "additionalProperties": false, + }), + "list" => json!({ + "type": "object", + "properties": {}, + "additionalProperties": false, + }), + _ => json!({"type": "object"}), + }; + json!({ + "name": tool.name, + "description": description, + "inputSchema": schema, + "outputSchema": output_schema(tool.name), + }) + }) + .collect() +} + +/// What a tool's successful `structuredContent` holds. A refused call +/// (`isError: true`) carries `error`, `message` and `retryable` instead. +fn output_schema(tool: &str) -> Value { + let summary = json!({ + "type": "object", + "properties": { + "id": {"type": "string"}, + "name": {"type": "string"}, + "state": {"type": "string", "description": "Lifecycle phase, such as provisioning, ready or error."}, + "created_at": {"type": ["string", "null"]}, + "parent": {"type": "string", "description": "The parent's name; absent on a root."}, + }, + "required": ["id", "name", "state"], + }); + match tool { + "create_sandbox" => { + let mut schema = summary; + let properties = &mut schema["properties"]; + properties["already_existed"] = + json!({"type": "boolean", "description": "The sandbox existed before this call."}); + properties["ready"] = json!({"type": "boolean", "description": "False when the wait ended before the sandbox was ready."}); + properties["timed_out"] = json!({"type": "boolean", "description": "The wait ended first; call again with the same name to keep waiting."}); + properties["message"] = json!({"type": "string"}); + schema["required"] = json!(["id", "name", "state", "already_existed"]); + schema + } + "list" => json!({ + "type": "object", + "properties": {"sandboxes": {"type": "array", "items": summary}}, + "required": ["sandboxes"], + }), + "exec" => json!({ + "type": "object", + "properties": { + "exit_code": {"type": ["integer", "null"], "description": "Null when the command timed out."}, + "stdout": {"type": "string"}, + "stderr": {"type": "string"}, + "stdout_truncated": {"type": "boolean"}, + "stderr_truncated": {"type": "boolean"}, + "binary_output": {"type": "boolean"}, + "timed_out": {"type": "boolean"}, + "message": {"type": "string"}, + }, + "required": ["exit_code", "stdout", "stderr", "stdout_truncated", "stderr_truncated", "binary_output", "timed_out"], + }), + "delete" => json!({ + "type": "object", + "properties": { + "name": {"type": "string"}, + "deleting": {"type": "boolean"}, + }, + "required": ["name", "deleting"], + }), + "logs" => json!({ + "type": "object", + "properties": { + "lines": { + "type": "array", + "items": { + "type": "object", + "properties": { + "time": {"type": ["string", "null"]}, + "level": {"type": "string"}, + "message": {"type": "string"}, + }, + "required": ["level", "message"], + }, + }, + "truncated": {"type": "boolean"}, + }, + "required": ["lines", "truncated"], + }), + _ => json!({"type": "object"}), + } +} + +const DEFAULT_EXEC_TIMEOUT_S: u64 = 30; +const MAX_EXEC_TIMEOUT_S: u64 = 45; +/// How long past `timeout_s` the tool waits for the gateway's exit event. +const EXEC_EXIT_GRACE: std::time::Duration = std::time::Duration::from_secs(5); +const MAX_STDIN_BYTES: usize = 512 * 1024; +/// Bytes kept from each end of each output stream. +const OUTPUT_EDGE_BYTES: usize = 16 * 1024; +/// Exit code the gateway reports when `execution_timeout` fires. +const GATEWAY_TIMEOUT_EXIT_CODE: i32 = 124; +/// Largest argument list recorded in the audit event. +const MAX_AUDIT_ARGV_BYTES: usize = 1024; +/// Largest working directory an audit event records. +const MAX_AUDIT_WORKDIR_BYTES: usize = 512; +/// Largest value of any other audit field. +const MAX_AUDIT_FIELD_BYTES: usize = 256; + +struct ExecArgs { + name: String, + command: Vec, + workdir: String, + stdin: Vec, + timeout: std::time::Duration, +} + +fn parse_exec_args(arguments: &Value) -> Result { + let args = arguments_object(arguments)?; + for key in args.keys() { + if key == "env" { + return Err(cli_only("env")); + } + if ![ + "name", + "command", + "workdir", + "stdin", + "stdin_base64", + "timeout_s", + ] + .contains(&key.as_str()) + { + return Err(ToolError::invalid(&format!("unknown argument '{key}'"))); + } + } + let name = args + .get("name") + .and_then(Value::as_str) + .filter(|name| !name.is_empty()) + .ok_or_else(|| ToolError::invalid("'name' is required"))?; + let command = args + .get("command") + .and_then(Value::as_array) + .and_then(|items| { + items + .iter() + .map(|item| item.as_str().map(str::to_string)) + .collect::>>() + }) + .filter(|command| !command.is_empty()) + .ok_or_else(|| ToolError::invalid("'command' must be a nonempty list of strings"))?; + let workdir = args + .get("workdir") + .and_then(Value::as_str) + .unwrap_or_default(); + let stdin = match (args.get("stdin"), args.get("stdin_base64")) { + (Some(_), Some(_)) => { + return Err(ToolError::invalid( + "send 'stdin' or 'stdin_base64', not both", + )); + } + (Some(text), None) => text + .as_str() + .ok_or_else(|| ToolError::invalid("'stdin' must be a string"))? + .as_bytes() + .to_vec(), + (None, Some(encoded)) => { + use base64::Engine; + encoded + .as_str() + .and_then(|encoded| { + base64::engine::general_purpose::STANDARD + .decode(encoded) + .ok() + }) + .ok_or_else(|| ToolError::invalid("'stdin_base64' must be base64"))? + } + (None, None) => Vec::new(), + }; + if stdin.len() > MAX_STDIN_BYTES { + return Err(ToolError::invalid("stdin is larger than 512 KiB")); + } + let timeout_s = match args.get("timeout_s") { + None => DEFAULT_EXEC_TIMEOUT_S, + Some(value) => value + .as_u64() + .filter(|timeout| (1..=MAX_EXEC_TIMEOUT_S).contains(timeout)) + .ok_or_else(|| ToolError::invalid("'timeout_s' must be between 1 and 45"))?, + }; + Ok(ExecArgs { + name: name.to_string(), + command, + workdir: workdir.to_string(), + stdin, + timeout: std::time::Duration::from_secs(timeout_s), + }) +} + +/// Run a command in one of the caller's children and collect its output, for +/// at most `timeout_s` plus a short grace for the gateway's exit event. +async fn exec_in_child(call: &Call<'_>, arguments: &Value) -> Result { + let args = parse_exec_args(arguments)?; + let request = ExecSandboxRequest { + sandbox: args.name, + command: args.command, + workdir: args.workdir, + stdin: args.stdin, + ..Default::default() + }; + let ExecOutcome { + stdout, + stderr, + exit, + } = run_in_child(call, request, args.timeout, EXEC_EXIT_GRACE).await?; + let exit_code = command_exit_code(exit, args.timeout); + let (stdout, stdout_truncated, stdout_binary) = stdout.render(); + let (stderr, stderr_truncated, stderr_binary) = stderr.render(); + let mut reply = json!({ + "exit_code": exit_code, + "stdout": stdout, + "stderr": stderr, + "stdout_truncated": stdout_truncated, + "stderr_truncated": stderr_truncated, + "binary_output": stdout_binary || stderr_binary, + "timed_out": exit_code.is_none(), + }); + if exit_code.is_none() { + reply["message"] = json!( + "the command may still be running in the child; start long work detached as the exec description shows, or delete the child to stop everything" + ); + } + Ok(reply) +} + +/// What one exec in a child produced. +struct ExecOutcome { + stdout: CapturedOutput, + stderr: CapturedOutput, + /// The exit code and when it came, or `None` if none came in time. + exit: Option<(i32, std::time::Duration)>, +} + +/// Send one `ExecSandbox` with `timeout` and collect its output until it +/// exits, or until `timeout` plus `grace` has passed. +async fn run_in_child( + call: &Call<'_>, + mut request: ExecSandboxRequest, + timeout: std::time::Duration, + grace: std::time::Duration, +) -> Result { + use openshell_core::proto::exec_sandbox_event::Payload; + + request.execution_timeout = Some(prost_types::Duration { + seconds: i64::try_from(timeout.as_secs()).unwrap_or(i64::MAX), + nanos: 0, + }); + let started = tokio::time::Instant::now(); + let deadline = started + timeout + grace; + let mut client = OpenShellClient::new(call.connection.grpc.clone()); + let pending: futures::future::BoxFuture<'_, _> = + Box::pin(client.exec_sandbox(call.request(request))); + let mut events = pending.await.map_err(ToolError::from_status)?.into_inner(); + let (mut stdout, mut stderr) = (CapturedOutput::default(), CapturedOutput::default()); + let mut exit = None; + loop { + let next: futures::future::BoxFuture<'_, _> = Box::pin(events.message()); + let Ok(event) = tokio::time::timeout_at(deadline, next).await else { + warn!("mcp: exec did not end at its timeout"); + break; + }; + match event.map_err(ToolError::from_status)? { + None => break, + Some(event) => match event.payload { + Some(Payload::Stdout(out)) => stdout.push(&out.data), + Some(Payload::Stderr(err)) => stderr.push(&err.data), + Some(Payload::Exit(code)) => { + exit = Some((code.exit_code, started.elapsed())); + break; + } + None => {} + }, + } + } + Ok(ExecOutcome { + stdout, + stderr, + exit, + }) +} + +/// The command's own exit code, or `None` when it timed out. The gateway +/// reports its timeout as 124; a command can exit 124 too, but only earlier +/// than one second before the timeout. +fn command_exit_code( + exit: Option<(i32, std::time::Duration)>, + timeout: std::time::Duration, +) -> Option { + match exit { + Some((GATEWAY_TIMEOUT_EXIT_CODE, elapsed)) + if elapsed + std::time::Duration::from_secs(1) >= timeout => + { + None + } + Some((code, _)) => Some(code), + None => None, + } +} + +/// One output stream: its first and last bytes, and how many there were. +#[derive(Default)] +struct CapturedOutput { + head: Vec, + tail: Vec, + total: usize, +} + +impl CapturedOutput { + fn push(&mut self, data: &[u8]) { + self.total += data.len(); + let into_head = OUTPUT_EDGE_BYTES + .saturating_sub(self.head.len()) + .min(data.len()); + self.head.extend_from_slice(&data[..into_head]); + self.tail.extend_from_slice(&data[into_head..]); + if self.tail.len() > OUTPUT_EDGE_BYTES { + self.tail.drain(..self.tail.len() - OUTPUT_EDGE_BYTES); + } + } + + /// The kept text, whether bytes were omitted, and whether the kept bytes + /// held invalid UTF-8. Cuts fall on character boundaries. + fn render(&self) -> (String, bool, bool) { + if self.head.len() + self.tail.len() == self.total { + let mut all = self.head.clone(); + all.extend_from_slice(&self.tail); + let text = String::from_utf8_lossy(&all); + let binary = matches!(text, std::borrow::Cow::Owned(_)); + return (text.into_owned(), false, binary); + } + let head = &self.head[..utf8_end_before_partial(&self.head)]; + let tail = &self.tail[utf8_start_after_partial(&self.tail)..]; + let omitted = self.total - head.len() - tail.len(); + let (head, tail) = (String::from_utf8_lossy(head), String::from_utf8_lossy(tail)); + let binary = matches!(head, std::borrow::Cow::Owned(_)) + || matches!(tail, std::borrow::Cow::Owned(_)); + ( + format!("{head}\n… [{omitted} bytes omitted] …\n{tail}"), + true, + binary, + ) + } +} + +/// Length of `bytes` without a multi-byte character cut off at its end. +fn utf8_end_before_partial(bytes: &[u8]) -> usize { + let len = bytes.len(); + for back in 1..=len.min(4) { + let byte = bytes[len - back]; + if byte & 0xC0 == 0x80 { + continue; + } + let width = match byte { + 0xF0..=0xF7 => 4, + 0xE0..=0xEF => 3, + 0xC0..=0xDF => 2, + _ => 1, + }; + return if width > back { len - back } else { len }; + } + len +} + +/// Offset past continuation bytes left at the start of `bytes` by a cut. +fn utf8_start_after_partial(bytes: &[u8]) -> usize { + bytes + .iter() + .take(3) + .take_while(|byte| *byte & 0xC0 == 0x80) + .count() +} + +/// A refusal is a policy or request decision; anything else the call could +/// not finish is a failure, not a denial. +fn audit_outcome(code: &str) -> audit::McpOutcome<'_> { + match code { + "internal" | "unavailable" | "timed_out" => audit::McpOutcome::Failed(code), + _ => audit::McpOutcome::Refused(code), + } +} + +/// The user a sandbox caller acts for: the user its record was created on +/// behalf of. A failed read is recorded as `unknown` and never fails the call. +pub async fn acting_for(connection: &McpConnection, sandbox_id: &str) -> String { + let Some(store) = connection.store.as_ref() else { + return "unknown".to_string(); + }; + let user = match store.get_message::(sandbox_id).await { + Ok(Some(sandbox)) => sandbox.created_on_behalf_of, + _ => None, + }; + user.map(|user| user.subject) + .filter(|subject| !subject.is_empty()) + .unwrap_or_else(|| "unknown".to_string()) +} + +/// Every field the audit event records about a tool call beyond its caller +/// and outcome: fields of the arguments, then of the reply. Never stdin, +/// environment values, output, log lines or any reply body. +fn tool_call_details( + tool: &str, + arguments: &Value, + result: &Result, +) -> Vec<(&'static str, String)> { + let mut details = audit_details(tool, arguments); + let content = match result { + Ok(content) => content, + Err(ToolError::Refused(Refusal { + withheld: Some(withheld), + .. + })) => { + details.push(("request_id", withheld.request_id.clone())); + details.push(("error_detail", withheld.detail.clone())); + return details; + } + Err(_) => return details, + }; + let flag = |key: &str| content.get(key).and_then(Value::as_bool); + match tool { + "create_sandbox" => { + details.push(("sandbox_id", json_text(&content["id"]))); + if let Some(already_existed) = flag("already_existed") { + details.push(("already_existed", already_existed.to_string())); + } + if let Some(timed_out) = flag("timed_out") { + details.push(("timed_out", timed_out.to_string())); + } + } + "list" => { + let count = content["sandboxes"].as_array().map_or(0, Vec::len); + details.push(("count", count.to_string())); + } + "exec" => { + details.push(("exit_code", json_text(&content["exit_code"]))); + details.push(("timed_out", flag("timed_out").unwrap_or(false).to_string())); + } + _ => {} + } + details +} + +/// What the audit event records from a tool call's arguments. +fn audit_details(tool: &str, arguments: &Value) -> Vec<(&'static str, String)> { + let text = |key| arguments.get(key).map(json_text).unwrap_or_default(); + let given = |key: &'static str| { + arguments + .get(key) + .filter(|value| !value.is_null()) + .map(|value| (key, json_text(value))) + }; + match tool { + "create_sandbox" => { + let mut details = vec![("target", text("name"))]; + details.extend( + ["template", "parent", "image"] + .into_iter() + .filter_map(given), + ); + if let Some(providers) = arguments.get("providers").and_then(Value::as_array) { + let names: Vec<_> = providers.iter().map(json_text).collect(); + details.push(("providers", names.join(","))); + } + details + } + "list" => given("parent").into_iter().collect(), + "delete" => vec![("target", text("name"))], + "logs" => { + let lines = arguments + .get("lines") + .and_then(Value::as_u64) + .unwrap_or(DEFAULT_LOG_LINES); + vec![("target", text("name")), ("lines", lines.to_string())] + } + "exec" => { + let argv = arguments + .get("command") + .and_then(Value::as_array) + .map(|items| { + items + .iter() + .filter_map(Value::as_str) + .collect::>() + .join(" ") + }) + .unwrap_or_default(); + let mut details = vec![ + ("target", text("name")), + ("argv", argv), + ("workdir", text("workdir")), + ]; + details.extend(given("timeout_s")); + details + } + _ => Vec::new(), + } +} + +/// A JSON value as audit text: a string as is, anything else encoded. +fn json_text(value: &Value) -> String { + match value { + Value::String(text) => text.clone(), + Value::Null => String::new(), + other => other.to_string(), + } +} + +/// Marks a value cut at its cap. +const AUDIT_CUT_MARKER: &str = "…[cut]"; + +/// Cut every field to its cap on a character boundary, marking a cut. With +/// the fixed field set this keeps an event's details under 4 KiB. +fn capped_audit_details(details: Vec<(&'static str, String)>) -> Vec<(&'static str, String)> { + details + .into_iter() + .map(|(key, value)| { + let cap = match key { + "argv" => MAX_AUDIT_ARGV_BYTES, + "workdir" => MAX_AUDIT_WORKDIR_BYTES, + _ => MAX_AUDIT_FIELD_BYTES, + }; + if value.len() <= cap { + return (key, value); + } + let kept = truncate_at_char_boundary(&value, cap - AUDIT_CUT_MARKER.len()); + (key, format!("{kept}{AUDIT_CUT_MARKER}")) + }) + .collect() +} + +fn truncate_at_char_boundary(text: &str, max_bytes: usize) -> &str { + let mut end = text.len().min(max_bytes); + while !text.is_char_boundary(end) { + end -= 1; + } + &text[..end] +} + +fn arguments_object(arguments: &Value) -> Result, ToolError> { + match arguments { + Value::Null => Ok(serde_json::Map::new()), + Value::Object(args) => Ok(args.clone()), + _ => Err(ToolError::invalid("arguments must be an object")), + } +} + +/// Delete one of the caller's children. Returns at once; deletion finishes in +/// the background. +async fn delete_child(call: &Call<'_>, arguments: &Value) -> Result { + let name = required_name(&arguments_object(arguments)?, &["name"])?; + let request = DeleteSandboxRequest { + name: name.clone(), + ..Default::default() + }; + let mut client = OpenShellClient::new(call.connection.grpc.clone()); + let pending: futures::future::BoxFuture<'_, _> = + Box::pin(client.delete_sandbox(call.request(request))); + pending.await.map_err(ToolError::from_status)?; + Ok(json!({"name": name, "deleting": true})) +} + +const DEFAULT_LOG_LINES: u64 = 200; +const MAX_LOG_LINES: u64 = 2000; +/// Largest log reply; the newest lines are kept. +const MAX_LOG_BYTES: usize = 64 * 1024; + +/// A child's own recent output, newest lines kept within the reply cap. +async fn child_logs(call: &Call<'_>, arguments: &Value) -> Result { + let args = arguments_object(arguments)?; + let name = required_name(&args, &["name", "lines", "since"])?; + let lines = match args.get("lines") { + None => DEFAULT_LOG_LINES, + Some(value) => value + .as_u64() + .filter(|lines| (1..=MAX_LOG_LINES).contains(lines)) + .ok_or_else(|| ToolError::invalid("'lines' must be between 1 and 2000"))?, + }; + let since_time = match args.get("since") { + None => None, + Some(value) => Some( + value + .as_str() + .and_then(|since| since.parse::().ok()) + .ok_or_else(|| ToolError::invalid("'since' must be an RFC 3339 time"))?, + ), + }; + let request = openshell_core::proto::GetSandboxLogsRequest { + sandbox: name, + lines: u32::try_from(lines).unwrap_or(u32::MAX), + since_time, + ..Default::default() + }; + let mut client = OpenShellClient::new(call.connection.grpc.clone()); + let pending: futures::future::BoxFuture<'_, _> = + Box::pin(client.get_sandbox_logs(call.request(request))); + let logs = pending + .await + .map_err(ToolError::from_status)? + .into_inner() + .logs; + let (lines, truncated) = newest_log_lines(&logs); + Ok(json!({"lines": lines, "truncated": truncated})) +} + +/// The newest lines that fit in the reply cap, oldest first. A single line +/// over the cap keeps its start, cut on a character boundary. +fn newest_log_lines(logs: &[openshell_core::proto::SandboxLogLine]) -> (Vec, bool) { + let mut kept = Vec::new(); + let mut bytes = 0; + let mut truncated = false; + for log in logs.iter().rev() { + let room = MAX_LOG_BYTES.saturating_sub(bytes); + if room == 0 { + truncated = true; + break; + } + let message = truncate_at_char_boundary(&log.message, room); + truncated |= message.len() < log.message.len(); + bytes += message.len(); + let time = log.event_time.as_ref().map(ToString::to_string); + kept.push(json!({"time": time, "level": log.level, "message": message})); + } + kept.reverse(); + (kept, truncated) +} + +/// Refuse arguments outside `allowed`, and return the required `name`. +fn required_name( + args: &serde_json::Map, + allowed: &[&str], +) -> Result { + if let Some(key) = args.keys().find(|key| !allowed.contains(&key.as_str())) { + return Err(ToolError::invalid(&format!("unknown argument '{key}'"))); + } + args.get("name") + .and_then(Value::as_str) + .filter(|name| !name.is_empty()) + .map(str::to_string) + .ok_or_else(|| ToolError::invalid("'name' is required")) +} + +/// `create_sandbox` arguments only a user may send. +const USER_CREATE_ARGUMENTS: [&str; 2] = ["parent", "image"]; +/// `create_sandbox` arguments only a sandbox may send. +const SANDBOX_CREATE_ARGUMENTS: [&str; 1] = ["template"]; +/// Create options of the CLI that MCP does not take yet. +const CLI_ONLY_CREATE_ARGUMENTS: [&str; 6] = + ["cpu", "memory", "env", "labels", "command", "policy"]; + +struct CreateArgs { + name: String, + parent: String, + image: String, + template: String, + providers: Vec, +} + +fn parse_create_args(arguments: &Value, user: bool) -> Result { + let args = arguments_object(arguments)?; + for key in args.keys().map(String::as_str) { + if CLI_ONLY_CREATE_ARGUMENTS.contains(&key) + || (user && SANDBOX_CREATE_ARGUMENTS.contains(&key)) + { + return Err(cli_only(key)); + } + if !user && USER_CREATE_ARGUMENTS.contains(&key) { + return Err(ToolError::invalid(&format!( + "'{key}' is only available to users" + ))); + } + if !["name", "providers"].contains(&key) + && !USER_CREATE_ARGUMENTS.contains(&key) + && !SANDBOX_CREATE_ARGUMENTS.contains(&key) + { + return Err(ToolError::invalid(&format!("unknown argument '{key}'"))); + } + } + let name = args + .get("name") + .and_then(Value::as_str) + .filter(|name| !name.is_empty()) + .ok_or_else(|| ToolError::invalid("'name' is required"))?; + let text = |key: &str| match args.get(key) { + None => Ok(String::new()), + Some(Value::String(value)) => Ok(value.clone()), + Some(_) => Err(ToolError::invalid(&format!("'{key}' must be a string"))), + }; + let (parent, image, template) = (text("parent")?, text("image")?, text("template")?); + let providers = match args.get("providers") { + None => Vec::new(), + Some(Value::Array(items)) => items + .iter() + .map(|item| item.as_str().map(str::to_string)) + .collect::>>() + .ok_or_else(|| ToolError::invalid("'providers' must be a list of names"))?, + Some(_) => return Err(ToolError::invalid("'providers' must be a list of names")), + }; + Ok(CreateArgs { + name: name.to_string(), + parent, + image, + template, + providers, + }) +} + +/// Refuse a create or exec option that only the CLI offers for now. +fn cli_only(key: &str) -> ToolError { + ToolError::invalid(&format!( + "'{key}' is not available over MCP; users can set it with the CLI" + )) +} + +/// Create a sandbox, or return the caller's existing one of that name, then +/// wait for it. The name is looked up first so a retry still works when the +/// parent is at its child limit. +async fn create_child(call: &Call<'_>, arguments: &Value) -> Result { + let args = parse_create_args(arguments, call.is_user())?; + if find_child(call, &args.name).await?.is_some() { + return wait_until_ready(call, &args.name, true).await; + } + let template = (!args.image.is_empty()).then(|| openshell_core::proto::SandboxTemplate { + image: args.image, + ..Default::default() + }); + let request = CreateSandboxRequest { + name: args.name.clone(), + parent: args.parent, + workload_template: args.template, + spec: Some(SandboxSpec { + providers: args.providers, + template, + ..Default::default() + }), + ..Default::default() + }; + let mut client = OpenShellClient::new(call.connection.grpc.clone()); + let pending: futures::future::BoxFuture<'_, _> = + Box::pin(client.create_sandbox(call.request(request))); + match pending.await { + Ok(_) => wait_until_ready(call, &args.name, false).await, + // A create racing the lookup above. + Err(status) if status.code() == tonic::Code::AlreadyExists => { + if find_child(call, &args.name).await?.is_some() { + wait_until_ready(call, &args.name, true).await + } else { + Err(ToolError::Refused(Refusal { + code: "already_exists", + message: format!( + "a sandbox named '{}' already exists in this workspace", + args.name + ), + retryable: false, + withheld: None, + })) + } + } + Err(status) => Err(ToolError::from_status(status)), + } +} + +/// Poll the caller's children until `name` is ready or failed, for at most +/// the create wait. Still provisioning at the end is not an error. +async fn wait_until_ready( + call: &Call<'_>, + name: &str, + already_existed: bool, +) -> Result { + let wait = call.connection.create_wait; + let deadline = tokio::time::Instant::now() + wait.limit; + let mut pause = wait.first_poll; + loop { + let Some(child) = find_child(call, name).await? else { + return Err(ToolError::Refused(Refusal { + code: "not_found", + message: format!("sandbox '{name}' not found"), + retryable: false, + withheld: None, + })); + }; + let mut reply = child_summary(&child); + reply["already_existed"] = json!(already_existed); + match SandboxPhase::try_from(child.phase()).unwrap_or(SandboxPhase::Unknown) { + SandboxPhase::Ready => return Ok(reply), + SandboxPhase::Error => { + return Err(ToolError::Refused(Refusal { + code: "failed_precondition", + message: format!("sandbox '{name}' failed: {}", failure_message(&child)), + retryable: false, + withheld: None, + })); + } + _ => {} + } + let now = tokio::time::Instant::now(); + if now >= deadline { + reply["ready"] = json!(false); + reply["timed_out"] = json!(true); + reply["message"] = + json!("call create_sandbox again with the same name to keep waiting"); + return Ok(reply); + } + tokio::time::sleep(pause.min(deadline - now)).await; + pause = wait.poll; + } +} + +fn failure_message(sandbox: &Sandbox) -> String { + sandbox + .status + .as_ref() + .and_then(|status| { + status + .conditions + .iter() + .find(|condition| condition.r#type == "Ready") + }) + .map(|condition| condition.message.clone()) + .filter(|message| !message.is_empty()) + .unwrap_or_else(|| "no reason was recorded".to_string()) +} + +/// The caller's sandbox of this name: a sandbox's child, or for a user any +/// sandbox in the workspace. +async fn find_child(call: &Call<'_>, name: &str) -> Result, ToolError> { + Ok(caller_children(call, "") + .await? + .into_iter() + .find(|child| child.object_name() == name)) +} + +async fn list_sandboxes(call: &Call<'_>, arguments: &Value) -> Result { + let args = arguments_object(arguments)?; + if let Some(key) = args.keys().find(|key| key.as_str() != "parent") { + return Err(ToolError::invalid(&format!("unknown argument '{key}'"))); + } + let parent = match args.get("parent") { + None => "", + Some(_) if !call.is_user() => { + return Err(ToolError::invalid("'parent' is only available to users")); + } + Some(Value::String(parent)) => parent, + Some(_) => return Err(ToolError::invalid("'parent' must be a string")), + }; + let sandboxes = caller_children(call, parent).await?; + Ok(json!({"sandboxes": sandboxes.iter().map(child_summary).collect::>()})) +} + +/// Every sandbox the caller lists, following page tokens to the end: a +/// sandbox's own children, or the user's workspace, narrowed to `parent`'s +/// children when it is set. +async fn caller_children(call: &Call<'_>, parent: &str) -> Result, ToolError> { + let mut client = OpenShellClient::new(call.connection.grpc.clone()); + let mut children = Vec::new(); + let mut page_token = String::new(); + loop { + let request = ListSandboxesRequest { + page_size: i32::try_from(crate::pagination::MAX_PAGE_SIZE).unwrap_or(i32::MAX), + page_token, + parent: parent.to_string(), + ..Default::default() + }; + // Boxed so the handler future is provably `Send`; tonic's generic + // error bound otherwise trips a higher-ranked lifetime check. + let pending: futures::future::BoxFuture<'_, _> = + Box::pin(client.list_sandboxes(call.request(request))); + let page = pending.await.map_err(ToolError::from_status)?.into_inner(); + children.extend(page.sandboxes); + if page.next_page_token.is_empty() { + break; + } + page_token = page.next_page_token; + } + Ok(children) +} + +fn child_summary(sandbox: &Sandbox) -> Value { + let phase = SandboxPhase::try_from(sandbox.phase()).unwrap_or(SandboxPhase::Unknown); + let created_at = sandbox + .metadata + .as_ref() + .and_then(|metadata| metadata.created_time.as_ref()) + .map(ToString::to_string); + let mut summary = json!({ + "id": sandbox.object_id(), + "name": sandbox.object_name(), + "state": phase.as_str_name().trim_start_matches("SANDBOX_PHASE_").to_ascii_lowercase(), + "created_at": created_at, + }); + if let Some(parent) = &sandbox.parent { + summary["parent"] = json!(parent.name); + } + summary +} + +/// The workspace a user's bridge names; sandboxes never send it. +const WORKSPACE_HEADER: &str = "x-openshell-workspace"; +/// A user's workspace when the bridge names none, as in the CLI. +const DEFAULT_WORKSPACE: &str = "default"; + +/// One tool call: the connection, the caller's headers and, for a user, the +/// workspace to act in. A sandbox caller has no workspace here; its handlers +/// read it from the caller's own record. +struct Call<'a> { + connection: &'a McpConnection, + headers: &'a HeaderMap, + workspace: Option, +} + +impl Call<'_> { + fn is_user(&self) -> bool { + self.workspace.is_some() + } + + /// A gRPC request for the in-process stack: the caller's own credential, + /// the `/mcp` marker and, for a user, the workspace. + fn request(&self, mut message: T) -> tonic::Request { + if let Some(workspace) = &self.workspace { + *message.workspace_scope() = + Some(openshell_core::proto::workspace_selector(workspace.clone())); + } + mcp_request(message, self.headers) + } +} + +/// The requests the tools send, each with its workspace selector. +trait WorkspaceScoped { + fn workspace_scope(&mut self) -> &mut Option; +} + +macro_rules! workspace_scoped { + ($($request:ty),*) => {$( + impl WorkspaceScoped for $request { + fn workspace_scope( + &mut self, + ) -> &mut Option { + &mut self.workspace_scope + } + } + )*}; +} + +workspace_scoped!( + CreateSandboxRequest, + ListSandboxesRequest, + ListSandboxTemplatesRequest, + ExecSandboxRequest, + DeleteSandboxRequest, + openshell_core::proto::GetSandboxLogsRequest +); + +/// A gRPC request for the in-process stack: the caller's own credential and +/// the `/mcp` marker. +fn mcp_request(message: T, headers: &HeaderMap) -> tonic::Request { + let mut request = tonic::Request::new(message); + for name in [http::header::AUTHORIZATION.as_str(), "x-request-id"] { + if let Some(value) = headers + .get(name) + .and_then(|value| tonic::metadata::AsciiMetadataValue::try_from(value.as_bytes()).ok()) + { + request.metadata_mut().insert(name, value); + } + } + request.extensions_mut().insert(McpOrigin); + request +} + +enum ToolError { + /// The caller's credential stopped working mid-call; answered with HTTP 401. + Unauthenticated, + Refused(Refusal), +} + +struct Refusal { + code: &'static str, + message: String, + retryable: bool, + /// What the agent is not shown, for the gateway log and the audit event. + withheld: Option, +} + +/// An error's own text, withheld from the agent, and the request id that +/// matches the agent's message to the gateway log and the audit event. +struct Withheld { + request_id: String, + detail: String, +} + +impl Refusal { + fn to_json(&self) -> Value { + json!({"error": self.code, "message": self.message, "retryable": self.retryable}) + } +} + +impl ToolError { + fn invalid(message: &str) -> Self { + Self::Refused(Refusal { + code: "invalid_argument", + message: message.to_string(), + retryable: false, + withheld: None, + }) + } + + /// A retryable error whose text is logged and audited, not returned: + /// internal and unavailable errors can carry store or driver detail. + fn withheld(code: &'static str, summary: &str, status: &tonic::Status) -> Self { + let request_id = uuid::Uuid::new_v4().to_string(); + warn!(%request_id, code, error = %status.message(), "mcp: tool call failed"); + Self::Refused(Refusal { + code, + message: format!( + "{summary} (request {request_id}); the operator can find it in the gateway logs" + ), + retryable: true, + withheld: Some(Withheld { + request_id, + detail: status.message().to_string(), + }), + }) + } + + /// Map a gRPC status to the agent-facing error. Internal, unknown and + /// unavailable errors are withheld; the rest are written for agents. + fn from_status(status: tonic::Status) -> Self { + use tonic::Code; + let (code, retryable) = match status.code() { + Code::Unauthenticated => return Self::Unauthenticated, + Code::InvalidArgument => ("invalid_argument", false), + Code::NotFound => ("not_found", false), + Code::AlreadyExists => ("already_exists", false), + Code::FailedPrecondition => ("failed_precondition", false), + Code::PermissionDenied => ("permission_denied", false), + Code::ResourceExhausted if is_rate_limit(&status) => ("rate_limited", true), + Code::ResourceExhausted => ("limit_reached", false), + Code::Aborted => ("unavailable", true), + Code::DeadlineExceeded => ("timed_out", true), + Code::Unavailable => { + return Self::withheld("unavailable", "gateway unavailable", &status); + } + _ => return Self::withheld("internal", "internal error", &status), + }; + Self::Refused(Refusal { + code, + message: status.message().to_string(), + retryable, + withheld: None, + }) + } +} + +/// Whether the gateway's rate limiter refused the call, the one +/// `ResourceExhausted` worth retrying. +fn is_rate_limit(status: &tonic::Status) -> bool { + openshell_core::rpc_error::decode_details(status) + .and_then(|details| details.error_info().cloned()) + .is_some_and(|info| { + info.reason == "RATE_LIMITED" && info.domain == openshell_core::rpc_error::ERROR_DOMAIN + }) +} + +fn tool_result(content: &Value, is_error: bool) -> Value { + let text = content + .get("message") + .filter(|_| is_error) + .and_then(Value::as_str) + .map_or_else(|| content.to_string(), str::to_string); + json!({ + "content": [{"type": "text", "text": text}], + "structuredContent": content, + "isError": is_error, + }) +} + +/// Echo a supported protocol version, otherwise offer the newest one. +fn negotiate_protocol_version(requested: Option<&str>) -> &'static str { + requested + .and_then(|v| SUPPORTED_PROTOCOL_VERSIONS.iter().find(|s| **s == v)) + .copied() + .unwrap_or(SUPPORTED_PROTOCOL_VERSIONS[0]) +} + +fn rpc_ok(id: &Value, result: Value) -> Response { + axum::Json(json!({"jsonrpc": "2.0", "id": id, "result": result})).into_response() +} + +fn rpc_error(id: &Value, code: i64, message: &str) -> Response { + axum::Json(json!({"jsonrpc": "2.0", "id": id, "error": {"code": code, "message": message}})) + .into_response() +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::auth::authenticator::test_support::MockAuthenticator; + use crate::auth::authenticator::{Authentication, AuthenticatorChain}; + use crate::auth::identity::Identity; + use crate::auth::identity::IdentityProvider; + use crate::auth::principal::{SandboxIdentitySource, SandboxPrincipal, UserPrincipal}; + use std::sync::Arc; + use tower::ServiceExt; + + fn sandbox_principal(sandbox_id: &str) -> Principal { + Principal::Sandbox(SandboxPrincipal { + sandbox_id: sandbox_id.to_string(), + source: SandboxIdentitySource::BootstrapJwt { + issuer: "openshell-gateway:test".to_string(), + auth_epoch: None, + }, + trust_domain: Some("openshell".to_string()), + }) + } + + fn user(provider: IdentityProvider) -> Principal { + Principal::User(UserPrincipal { + identity: Identity { + subject: "user".to_string(), + display_name: None, + roles: vec!["openshell-user".to_string()], + scopes: Vec::new(), + provider, + }, + }) + } + + /// A connection whose callers resolve to `caller` (or are refused) and + /// whose gRPC stack must never be reached. + fn connection(caller: Option) -> McpConnection { + let outcome = caller.map_or(Ok(Authentication::NotApplicable), |principal| { + Ok(Authentication::Accepted(principal)) + }); + let chain = AuthenticatorChain::new(vec![Arc::new(MockAuthenticator::returning(outcome))]); + let unreachable = tower::service_fn(|_: http::Request| async { + panic!("the gRPC stack must not be called"); + #[allow(unreachable_code)] + Ok::<_, std::convert::Infallible>(http::Response::new(tonic::body::Body::empty())) + }); + let auth = crate::multiplex::AuthGrpcRouter::new(unreachable, Some(chain), None) + .caller_authenticator(); + McpConnection::new(auth, unreachable) + } + + async fn post_mcp( + connection: McpConnection, + headers: &[(&str, &str)], + body: Vec, + ) -> (StatusCode, Option) { + let mut request = http::Request::post(MCP_PATH).header("content-type", "application/json"); + for (name, value) in headers { + request = request.header(*name, *value); + } + let response = router() + .layer(Extension(connection)) + .oneshot(request.body(Body::from(body)).unwrap()) + .await + .unwrap(); + let status = response.status(); + let bytes = axum::body::to_bytes(response.into_body(), usize::MAX) + .await + .unwrap(); + (status, serde_json::from_slice(&bytes).ok()) + } + + fn rpc(method: &str, params: Value) -> Vec { + serde_json::to_vec(&json!({"jsonrpc": "2.0", "id": 1, "method": method, "params": params})) + .unwrap() + } + + #[tokio::test] + async fn users_and_sandboxes_are_served_and_anonymous_callers_are_not() { + let initialize = || rpc("initialize", json!({"protocolVersion": "2025-06-18"})); + for (caller, expected) in [ + (None, StatusCode::UNAUTHORIZED), + (Some(Principal::Anonymous), StatusCode::UNAUTHORIZED), + (Some(user(IdentityProvider::LocalDev)), StatusCode::OK), + (Some(user(IdentityProvider::Oidc)), StatusCode::OK), + (Some(user(IdentityProvider::Mtls)), StatusCode::OK), + (Some(sandbox_principal("lead")), StatusCode::OK), + ] { + let (status, _) = post_mcp(connection(caller), &[], initialize()).await; + assert_eq!(status, expected); + } + } + + #[tokio::test] + async fn any_origin_header_is_refused_from_every_caller() { + for caller in [user(IdentityProvider::Oidc), sandbox_principal("lead")] { + for origin in [ + "http://attacker.example", + "http://localhost:8080", + "http://openshell.local", + "null", + ] { + let (status, _) = post_mcp( + connection(Some(caller.clone())), + &[("origin", origin)], + rpc("ping", json!({})), + ) + .await; + assert_eq!(status, StatusCode::FORBIDDEN, "{origin}"); + } + } + } + + fn tool<'a>(tools: &'a [Value], name: &str) -> &'a Value { + tools.iter().find(|tool| tool["name"] == name).unwrap() + } + + fn argument_names(tool: &Value) -> Vec<&str> { + let mut names: Vec<&str> = tool["inputSchema"]["properties"] + .as_object() + .unwrap() + .keys() + .map(String::as_str) + .collect(); + names.sort_unstable(); + names + } + + #[tokio::test] + async fn a_users_tool_list_offers_only_user_arguments() { + // The connection's gRPC stack panics if called. + let (status, reply) = post_mcp( + connection(Some(user(IdentityProvider::Oidc))), + &[], + rpc("tools/list", json!({})), + ) + .await; + assert_eq!(status, StatusCode::OK); + let reply = reply.unwrap(); + let tools = reply["result"]["tools"].as_array().unwrap(); + assert_eq!( + argument_names(tool(tools, "create_sandbox")), + ["image", "name", "parent", "providers"] + ); + assert_eq!(argument_names(tool(tools, "list")), ["parent"]); + } + + #[test] + fn a_sandboxs_tool_list_offers_only_sandbox_arguments() { + let tools = tool_definitions(&[], false); + assert_eq!( + argument_names(tool(&tools, "create_sandbox")), + ["name", "providers", "template"] + ); + assert!(argument_names(tool(&tools, "list")).is_empty()); + } + + #[test] + fn every_tool_reply_matches_its_output_schema() { + let tools = tool_definitions(&[], true); + let validator = |name: &str| { + jsonschema::validator_for(&tool(&tools, name)["outputSchema"]) + .unwrap_or_else(|error| panic!("{name}: {error}")) + }; + let mut sandbox = Sandbox { + metadata: Some(openshell_core::proto::datamodel::v1::ObjectMeta { + id: "id-1".to_string(), + name: "w1".to_string(), + ..Default::default() + }), + parent: Some(openshell_core::proto::SandboxParent { + name: "lead".to_string(), + id: "id-0".to_string(), + }), + ..Default::default() + }; + sandbox.set_phase(SandboxPhase::Provisioning as i32); + let summary = child_summary(&sandbox); + + let mut created = summary.clone(); + created["already_existed"] = json!(false); + created["ready"] = json!(false); + created["timed_out"] = json!(true); + created["message"] = json!("call again"); + let (lines, truncated) = newest_log_lines(&[openshell_core::proto::SandboxLogLine { + level: "INFO".to_string(), + message: "started".to_string(), + ..Default::default() + }]); + let replies = [ + ("create_sandbox", created), + ("list", json!({"sandboxes": [summary]})), + ( + "exec", + json!({ + "exit_code": null, "stdout": "", "stderr": "", "stdout_truncated": false, + "stderr_truncated": false, "binary_output": false, "timed_out": true, + "message": "still running", + }), + ), + ("delete", json!({"name": "w1", "deleting": true})), + ("logs", json!({"lines": lines, "truncated": truncated})), + ]; + for (name, reply) in replies { + let errors: Vec = validator(name) + .iter_errors(&reply) + .map(|error| error.to_string()) + .collect(); + assert!(errors.is_empty(), "{name}: {errors:?} for {reply}"); + } + assert!( + !validator("delete").is_valid(&json!({"name": "w1"})), + "a reply missing a required field must not validate" + ); + assert_eq!(tools.len(), TOOLS.len()); + } + + #[tokio::test] + async fn initialize_negotiates_a_supported_version() { + for (requested, answered) in [("2025-06-18", "2025-06-18"), ("1999-01-01", "2025-11-25")] { + let (status, reply) = post_mcp( + connection(Some(sandbox_principal("lead"))), + &[], + rpc("initialize", json!({"protocolVersion": requested})), + ) + .await; + assert_eq!(status, StatusCode::OK); + assert_eq!(reply.unwrap()["result"]["protocolVersion"], answered); + } + } + + #[tokio::test] + async fn the_endpoint_refuses_what_it_does_not_serve() { + let lead = || connection(Some(sandbox_principal("lead"))); + // A foreign browser origin, before anything else. + let (status, _) = post_mcp( + connection(None), + &[("origin", "http://attacker.example")], + rpc("ping", json!({})), + ) + .await; + assert_eq!(status, StatusCode::FORBIDDEN); + + let (status, _) = post_mcp(lead(), &[], vec![b' '; MAX_REQUEST_BYTES + 1]).await; + assert_eq!(status, StatusCode::PAYLOAD_TOO_LARGE); + + let (_, reply) = post_mcp(lead(), &[], b"[]".to_vec()).await; + assert_eq!(reply.unwrap()["error"]["code"], -32600); + + let (_, reply) = post_mcp(lead(), &[], rpc("tools/call", json!({"name": "rm"}))).await; + assert_eq!(reply.unwrap()["error"]["code"], -32602); + } + + #[test] + fn the_audit_event_is_valid_and_carries_no_token_or_stdin() { + let headers = HeaderMap::from_iter([( + http::header::AUTHORIZATION, + "Bearer canary-secret-token-7d1e".parse().unwrap(), + )]); + let details = audit_details( + "exec", + &json!({"name": "w1", "command": ["ls", "-l"], "workdir": "/tmp", "stdin": "secret-stdin"}), + ); + let event = audit::mcp_tool_call_event( + &RequestOrigin::new(None, &headers), + &sandbox_principal("lead"), + "exec", + audit::McpOutcome::Refused("not_found"), + &details, + ); + let event = serde_json::to_value(event).unwrap(); + assert_eq!(event["api"]["operation"], "exec"); + assert_eq!(event["status_detail"], "not_found"); + assert_eq!(event["unmapped"]["argv"], "ls -l"); + assert_eq!(event["unmapped"]["workdir"], "/tmp"); + let text = event.to_string(); + assert!(!text.contains("canary-secret-token") && !text.contains("secret-stdin")); + openshell_ocsf_validate::validate_event(&event).unwrap_or_else(|e| panic!("{e}")); + } + + fn recorded( + tool: &str, + arguments: Value, + result: Result, + ) -> std::collections::HashMap<&'static str, String> { + capped_audit_details(tool_call_details(tool, &arguments, &result)) + .into_iter() + .collect() + } + + #[test] + fn each_tool_records_its_fields_and_keeps_the_existing_keys() { + let create = recorded( + "create_sandbox", + json!({"name": "w1", "parent": "lead", "image": "img:1", "providers": ["gh", "oa"]}), + Ok(json!({"id": "id-1", "name": "w1", "already_existed": false})), + ); + assert_eq!(create["target"], "w1"); + assert_eq!(create["parent"], "lead"); + assert_eq!(create["image"], "img:1"); + assert_eq!(create["providers"], "gh,oa"); + assert_eq!(create["sandbox_id"], "id-1"); + assert_eq!(create["already_existed"], "false"); + assert!(!create.contains_key("template") && !create.contains_key("timed_out")); + + let list = recorded( + "list", + json!({"parent": "lead"}), + Ok(json!({"sandboxes": [{}, {}]})), + ); + assert_eq!(list["parent"], "lead"); + assert_eq!(list["count"], "2"); + + let exec = recorded( + "exec", + json!({"name": "w1", "command": ["ls"], "timeout_s": 10, "stdin": "secret"}), + Ok(json!({"exit_code": 0, "timed_out": false, "stdout": "out"})), + ); + assert_eq!(exec["target"], "w1"); + assert_eq!(exec["argv"], "ls"); + assert_eq!(exec["timeout_s"], "10"); + assert_eq!(exec["exit_code"], "0"); + assert_eq!(exec["timed_out"], "false"); + + assert_eq!( + recorded("delete", json!({"name": "w1"}), Ok(json!({})))["target"], + "w1" + ); + let logs = recorded("logs", json!({"name": "w1"}), Ok(json!({"lines": ["l"]}))); + assert_eq!(logs["lines"], DEFAULT_LOG_LINES.to_string()); + + // Nothing from stdin, output, log lines or reply bodies. + for fields in [&create, &list, &exec, &logs] { + for value in fields.values() { + assert!(!value.contains("secret") && value != "out" && value != "x"); + } + } + } + + #[test] + fn long_values_are_cut_at_their_cap_with_a_marker() { + let long = "é".repeat(4096); + let fields = recorded( + "exec", + json!({"name": long, "command": [long], "workdir": long, "timeout_s": 1}), + Ok(json!({"exit_code": 0, "timed_out": false})), + ); + for (key, cap) in [ + ("argv", MAX_AUDIT_ARGV_BYTES), + ("workdir", MAX_AUDIT_WORKDIR_BYTES), + ("target", MAX_AUDIT_FIELD_BYTES), + ] { + assert!(fields[key].len() <= cap, "{key}"); + assert!(fields[key].ends_with(AUDIT_CUT_MARKER), "{key}"); + assert!(fields[key].starts_with("éé"), "{key}"); + } + + // The largest event any tool can produce stays under 4 KiB. + let mut worst = capped_audit_details(tool_call_details( + "exec", + &json!({"name": long, "command": [long], "workdir": long, "timeout_s": long}), + &Ok(json!({"exit_code": long, "timed_out": false})), + )); + worst.push(("acting_for", long.clone())); + let worst = capped_audit_details(worst); + let total: usize = worst + .iter() + .map(|(key, value)| key.len() + value.len()) + .sum(); + assert!(total <= 4096, "{total}"); + + // So does a failed call, which records the withheld error instead. + let mut worst = capped_audit_details(tool_call_details( + "exec", + &json!({"name": long, "command": [long], "workdir": long, "timeout_s": long}), + &Err(ToolError::from_status(tonic::Status::internal( + long.clone(), + ))), + )); + worst.push(("acting_for", long)); + let worst = capped_audit_details(worst); + let total: usize = worst + .iter() + .map(|(key, value)| key.len() + value.len()) + .sum(); + assert!(total <= 4096, "{total}"); + } + + #[test] + fn a_failure_is_not_recorded_as_a_denial() { + let event = |code| { + serde_json::to_value(audit::mcp_tool_call_event( + &RequestOrigin::new(None, &HeaderMap::new()), + &sandbox_principal("lead"), + "exec", + audit_outcome(code), + &[], + )) + .unwrap() + }; + for code in ["internal", "unavailable", "timed_out"] { + let failed = event(code); + assert_eq!(failed["action_id"], 1, "{code}: allowed, not denied"); + assert_eq!(failed["status_id"], 2, "{code}"); + assert_eq!(failed["status_detail"], code); + assert_eq!( + failed["message"], + format!("mcp tool call exec: failed ({code})") + ); + openshell_ocsf_validate::validate_event(&failed).unwrap_or_else(|e| panic!("{e}")); + } + for code in ["not_found", "failed_precondition", "limit_reached"] { + let refused = event(code); + assert_eq!(refused["action_id"], 2, "{code}: denied"); + assert_eq!(refused["disposition_id"], 2, "{code}: blocked"); + assert_eq!( + refused["message"], + format!("mcp tool call exec: refused ({code})") + ); + } + } + + /// Internal, unknown and unavailable errors can carry store or driver + /// detail: the agent gets a request id instead, and keeps its retry hint. + #[test] + fn internal_detail_never_reaches_the_agent() { + let detail = "store pool exhausted at 10.0.0.3:5432"; + for (status, code) in [ + (tonic::Status::internal(detail), "internal"), + (tonic::Status::unknown(detail), "internal"), + (tonic::Status::unavailable(detail), "unavailable"), + ] { + let ToolError::Refused(refusal) = ToolError::from_status(status) else { + panic!("not a refusal"); + }; + assert_eq!((refusal.code, refusal.retryable), (code, true)); + assert!(!refusal.message.contains("10.0.0.3"), "{}", refusal.message); + // The audit event keeps the detail, under the id the agent sees. + let message = refusal.message.clone(); + let fields = recorded("list", json!({}), Err(ToolError::Refused(refusal))); + assert_eq!(fields["error_detail"], detail); + assert!( + message.contains(&format!("(request {})", fields["request_id"])), + "{message}" + ); + } + let fields = recorded( + "list", + json!({}), + Err(ToolError::from_status(tonic::Status::internal( + "é".repeat(400), + ))), + ); + assert!(fields["error_detail"].len() <= MAX_AUDIT_FIELD_BYTES); + assert!(fields["error_detail"].ends_with(AUDIT_CUT_MARKER)); + // Messages written for agents are kept. + for status in [ + tonic::Status::failed_precondition("parent sandbox 'lead' is being deleted"), + tonic::Status::invalid_argument("name must be at most 63 characters"), + ] { + let message = status.message().to_string(); + let ToolError::Refused(refusal) = ToolError::from_status(status) else { + panic!("not a refusal"); + }; + assert_eq!(refusal.message, message); + } + } + + /// Only a rate limit is worth retrying: a full child limit, even one + /// waiting on deletes, and an oversized message are not. + #[test] + fn only_a_rate_limit_is_retryable() { + use openshell_core::rpc_error::{ERROR_DOMAIN, ErrorDetails, StatusExt}; + let refusal = |status| match ToolError::from_status(status) { + ToolError::Refused(refusal) => refusal, + ToolError::Unauthenticated => panic!("not a refusal"), + }; + let rate_limited = refusal(tonic::Status::with_error_details( + tonic::Code::ResourceExhausted, + "gRPC rate limit exceeded", + ErrorDetails::with_error_info( + "RATE_LIMITED", + ERROR_DOMAIN, + std::collections::HashMap::new(), + ), + )); + assert_eq!( + (rate_limited.code, rate_limited.retryable), + ("rate_limited", true) + ); + assert_eq!(rate_limited.message, "gRPC rate limit exceeded"); + for message in [ + "sandbox 'lead' has reached its limit of 2 children, 1 of them still being deleted; try again shortly", + "gRPC message exceeds u32", + ] { + let other = refusal(tonic::Status::resource_exhausted(message)); + assert_eq!((other.code, other.retryable), ("limit_reached", false)); + } + } + + #[test] + fn a_late_124_is_a_timeout_and_an_early_one_is_the_commands() { + let timeout = std::time::Duration::from_secs(10); + let at = std::time::Duration::from_millis; + assert_eq!(command_exit_code(Some((124, at(9_000))), timeout), None); + assert_eq!(command_exit_code(Some((124, at(10_200))), timeout), None); + assert_eq!( + command_exit_code(Some((124, at(8_900))), timeout), + Some(124) + ); + assert_eq!(command_exit_code(Some((0, at(10_200))), timeout), Some(0)); + assert_eq!(command_exit_code(None, timeout), None); + } + + #[tokio::test] + async fn create_sandbox_refuses_user_only_and_unknown_arguments() { + for (arguments, message) in [ + ( + json!({"name": "w", "image": "x"}), + "'image' is only available to users", + ), + ( + json!({"name": "w", "parent": "x"}), + "'parent' is only available to users", + ), + (json!({"name": "w", "size": 3}), "unknown argument 'size'"), + (json!({}), "'name' is required"), + ] { + let (_, reply) = post_mcp( + connection(Some(sandbox_principal("lead"))), + &[], + rpc( + "tools/call", + json!({"name": "create_sandbox", "arguments": arguments}), + ), + ) + .await; + let result = &reply.unwrap()["result"]; + assert_eq!(result["isError"], true); + assert_eq!(result["structuredContent"]["error"], "invalid_argument"); + assert_eq!(result["structuredContent"]["message"], message); + } + } + + #[test] + fn create_arguments_depend_on_the_caller() { + let refusal = |arguments: Value, user: bool| match parse_create_args(&arguments, user) { + Ok(_) => String::new(), + Err(ToolError::Refused(refusal)) => refusal.message, + Err(ToolError::Unauthenticated) => unreachable!(), + }; + let user_args = json!({"name": "w", "parent": "lead", "image": "img", "providers": ["p"]}); + let args = parse_create_args(&user_args, true).ok().unwrap(); + assert_eq!( + ( + args.parent.as_str(), + args.image.as_str(), + args.providers.len() + ), + ("lead", "img", 1) + ); + let sandbox_args = json!({"name": "w", "template": "t", "providers": ["p"]}); + assert_eq!(refusal(sandbox_args, false), ""); + for (arguments, user, message) in [ + ( + json!({"name": "w", "parent": "x"}), + false, + "'parent' is only available to users", + ), + ( + json!({"name": "w", "image": "x"}), + false, + "'image' is only available to users", + ), + ( + json!({"name": "w", "template": "t"}), + true, + "'template' is not available over MCP; users can set it with the CLI", + ), + ( + json!({"name": "w", "policy": "x"}), + true, + "'policy' is not available over MCP; users can set it with the CLI", + ), + ( + json!({"name": "w", "env": {}}), + false, + "'env' is not available over MCP; users can set it with the CLI", + ), + ( + json!({"name": "w", "size": 3}), + true, + "unknown argument 'size'", + ), + ] { + assert_eq!(refusal(arguments, user), message); + } + } + + #[tokio::test] + async fn only_users_may_list_by_parent() { + let (_, reply) = post_mcp( + connection(Some(sandbox_principal("lead"))), + &[], + rpc( + "tools/call", + json!({"name": "list", "arguments": {"parent": "other"}}), + ), + ) + .await; + let result = &reply.unwrap()["result"]; + assert_eq!( + result["structuredContent"]["message"], + "'parent' is only available to users" + ); + } + + #[test] + fn output_keeps_both_ends_and_cuts_on_character_boundaries() { + let mut small = CapturedOutput::default(); + small.push(b"hello"); + assert_eq!(small.render(), ("hello".to_string(), false, false)); + + // "é" is two bytes; one straddles the head's 16 KiB edge and one the + // tail's, so neither may turn into a replacement character. + let mut text = "a".repeat(OUTPUT_EDGE_BYTES - 1); + text.push('é'); + text.push_str(&"b".repeat(40_000)); + text.push('é'); + text.push_str(&"c".repeat(OUTPUT_EDGE_BYTES - 2)); + let mut output = CapturedOutput::default(); + for chunk in text.as_bytes().chunks(1000) { + output.push(chunk); + } + let (rendered, truncated, binary) = output.render(); + assert!(truncated); + assert!(!binary, "a cut character is not binary output"); + assert!(!rendered.contains('\u{FFFD}')); + assert!(rendered.starts_with(&"a".repeat(OUTPUT_EDGE_BYTES - 1))); + assert!(rendered.ends_with(&"c".repeat(OUTPUT_EDGE_BYTES - 2))); + assert!(rendered.contains("bytes omitted")); + + let mut binary = CapturedOutput::default(); + binary.push(&[0xff, 0xfe, b'x']); + assert!(binary.render().2); + } + + #[test] + fn the_audit_argument_list_is_capped_on_a_character_boundary() { + let details = capped_audit_details(audit_details( + "exec", + &json!({"name": "w", "command": ["echo", "é".repeat(1000)], "stdin": "secret"}), + )); + let argv = &details.iter().find(|(key, _)| *key == "argv").unwrap().1; + assert!(argv.len() <= MAX_AUDIT_ARGV_BYTES); + assert!(argv.starts_with("echo é")); + assert!(details.iter().all(|(_, value)| !value.contains("secret"))); + } + + #[tokio::test] + async fn exec_refuses_bad_arguments_before_calling_the_gateway() { + let big = "x".repeat(MAX_STDIN_BYTES + 1); + let invalid = "invalid_argument"; + for (arguments, error, message) in [ + ( + json!({"name": "w", "command": ["ls"], "background": true}), + invalid, + "unknown argument 'background'", + ), + ( + json!({"name": "w", "command": ["ls"], "stdin": big}), + invalid, + "stdin is larger than 512 KiB", + ), + ( + json!({"name": "w", "command": ["ls"], "stdin": "a", "stdin_base64": "YQ=="}), + invalid, + "send 'stdin' or 'stdin_base64', not both", + ), + ( + json!({"name": "w", "command": ["ls"], "timeout_s": 46}), + invalid, + "'timeout_s' must be between 1 and 45", + ), + ( + json!({"name": "w", "command": ["ls"], "env": {}}), + invalid, + "'env' is not available over MCP; users can set it with the CLI", + ), + ( + json!({"name": "w", "command": ["ls"], "size": 3}), + invalid, + "unknown argument 'size'", + ), + ( + json!({"name": "w", "command": "ls"}), + invalid, + "'command' must be a nonempty list of strings", + ), + ] { + let (_, reply) = post_mcp( + connection(Some(sandbox_principal("lead"))), + &[], + rpc( + "tools/call", + json!({"name": "exec", "arguments": arguments}), + ), + ) + .await; + let result = &reply.unwrap()["result"]; + assert_eq!(result["isError"], true); + assert_eq!(result["structuredContent"]["error"], error); + assert_eq!(result["structuredContent"]["message"], message); + } + } + + #[tokio::test] + async fn delete_refuses_unknown_arguments() { + for (arguments, message) in [ + ( + json!({"name": "w", "force": true}), + "unknown argument 'force'", + ), + (json!({}), "'name' is required"), + ] { + let (_, reply) = post_mcp( + connection(Some(sandbox_principal("lead"))), + &[], + rpc( + "tools/call", + json!({"name": "delete", "arguments": arguments}), + ), + ) + .await; + let result = &reply.unwrap()["result"]; + assert_eq!(result["structuredContent"]["error"], "invalid_argument"); + assert_eq!(result["structuredContent"]["message"], message); + } + } + + #[test] + fn logs_keep_the_newest_lines_within_the_cap() { + let line = |message: String| openshell_core::proto::SandboxLogLine { + message, + ..Default::default() + }; + let small: Vec<_> = (0..3).map(|i| line(format!("line {i}"))).collect(); + let (kept, truncated) = newest_log_lines(&small); + assert_eq!(kept.len(), 3); + assert!(!truncated); + + // Three 30 KiB lines: only the newest two fit, the second-newest cut. + let big: Vec<_> = (0..3) + .map(|i| line(format!("{i}{}", "x".repeat(30 * 1024)))) + .collect(); + let (kept, truncated) = newest_log_lines(&big); + assert!(truncated); + assert_eq!(kept.len(), 3); + assert!( + kept.last().unwrap()["message"] + .as_str() + .unwrap() + .starts_with('2') + ); + let total: usize = kept + .iter() + .map(|l| l["message"].as_str().unwrap().len()) + .sum(); + assert!(total <= MAX_LOG_BYTES); + + // One line over the cap made of two-byte characters is cut on a + // character boundary. + let (kept, truncated) = newest_log_lines(&[line("é".repeat(MAX_LOG_BYTES))]); + assert!(truncated); + let message = kept[0]["message"].as_str().unwrap(); + assert!(message.len() <= MAX_LOG_BYTES && message.chars().all(|c| c == 'é')); + } + + #[tokio::test] + async fn logs_refuses_unknown_arguments() { + for (arguments, message) in [ + ( + json!({"name": "w", "sources": ["gateway"]}), + "unknown argument 'sources'", + ), + ( + json!({"name": "w", "lines": 2001}), + "'lines' must be between 1 and 2000", + ), + ( + json!({"name": "w", "since": "yesterday"}), + "'since' must be an RFC 3339 time", + ), + ] { + let (_, reply) = post_mcp( + connection(Some(sandbox_principal("lead"))), + &[], + rpc( + "tools/call", + json!({"name": "logs", "arguments": arguments}), + ), + ) + .await; + let result = &reply.unwrap()["result"]; + assert_eq!(result["structuredContent"]["error"], "invalid_argument"); + assert_eq!(result["structuredContent"]["message"], message); + } + } + + #[test] + fn internal_errors_do_not_reach_the_agent() { + let ToolError::Refused(refusal) = + ToolError::from_status(tonic::Status::internal("fetch parent sandbox failed: db")) + else { + panic!("an internal error is a tool error"); + }; + assert_eq!(refusal.code, "internal"); + // The request id is random hex, so check for the hidden text itself. + assert!( + !refusal.message.contains("fetch parent sandbox failed"), + "{}", + refusal.message + ); + assert!(matches!( + ToolError::from_status(tonic::Status::unauthenticated("expired")), + ToolError::Unauthenticated + )); + } +} diff --git a/crates/openshell-server/src/multiplex.rs b/crates/openshell-server/src/multiplex.rs index 6b8a4d1406..1c331e1f73 100644 --- a/crates/openshell-server/src/multiplex.rs +++ b/crates/openshell-server/src/multiplex.rs @@ -349,10 +349,31 @@ impl MultiplexService { .with_operator(operator) .with_connection_source(source) .with_logons(self.state.logons.clone()); + let caller_authenticator = self + .state + .config + .enable_child_sandboxes + .then(|| grpc_service.caller_authenticator()); let mut grpc_service = GrpcRateLimitService::new(grpc_service, self.state.grpc_rate_limiter.clone()); grpc_service.provider_token_limiter = self.state.provider_token_rate_limiter.clone(); - let http_service = http_router(self.state.clone()); + let mut http_service = http_router(self.state.clone()); + // `/mcp` is routed only with child sandboxes on. It re-enters this + // connection's gRPC stack, so its tool calls are authenticated, rate + // limited and intercepted like any other request. + if let Some(caller_authenticator) = caller_authenticator { + let mcp_connection = crate::mcp::McpConnection::new( + caller_authenticator, + grpc_service + .clone() + .map_request(|req: Request| { + let (parts, body) = req.into_parts(); + Request::from_parts(parts, BoxBody(body.map_err(Into::into).boxed_unsync())) + }), + ) + .with_store(self.state.store.clone()); + http_service = http_service.layer(axum::Extension(mcp_connection)); + } let grpc_service = request_id_middleware!(grpc_service); let http_service = request_id_middleware!(http_service); @@ -853,7 +874,7 @@ fn unknown_gateway_principal() -> BTreeMap { BTreeMap::from([("kind".to_string(), "unknown".to_string())]) } -fn identity_provider_name(provider: crate::auth::identity::IdentityProvider) -> &'static str { +pub fn identity_provider_name(provider: crate::auth::identity::IdentityProvider) -> &'static str { match provider { crate::auth::identity::IdentityProvider::Oidc => "oidc", crate::auth::identity::IdentityProvider::Mtls => "mtls", @@ -953,6 +974,21 @@ impl GrpcRateLimitService { } } +/// The refusal for a call over the gRPC rate limit, tagged `RATE_LIMITED` so +/// clients can tell it from other `ResourceExhausted` errors and retry later. +fn rate_limit_exceeded() -> tonic::Status { + use openshell_core::rpc_error::StatusExt; + tonic::Status::with_error_details( + tonic::Code::ResourceExhausted, + "gRPC rate limit exceeded", + openshell_core::rpc_error::ErrorDetails::with_error_info( + "RATE_LIMITED", + openshell_core::rpc_error::ERROR_DOMAIN, + std::collections::HashMap::new(), + ), + ) +} + impl tower::Service> for GrpcRateLimitService where S: tower::Service, Response = Response>, @@ -997,8 +1033,7 @@ where // Tower contract forbids forwarding to an inner service that did not // report readiness. if std::mem::take(&mut self.rate_limited) { - let response = - tonic::Status::resource_exhausted("gRPC rate limit exceeded").into_http(); + let response = rate_limit_exceeded().into_http(); return Box::pin(async move { Ok(response) }); } let limiter = if req.uri().path() == "/openshell.v1.OpenShell/GetSandboxProviderAccessToken" @@ -1010,8 +1045,7 @@ where self.limiter.as_ref() }; if limiter.is_some_and(|limiter| !limiter.allow()) { - let response = - tonic::Status::resource_exhausted("gRPC rate limit exceeded").into_http(); + let response = rate_limit_exceeded().into_http(); return Box::pin(async move { Ok(response) }); } let future = self.inner.call(req); @@ -1202,7 +1236,7 @@ pub struct AuthGrpcRouter { impl AuthGrpcRouter { #[cfg(test)] - fn new( + pub(crate) fn new( inner: S, authenticator_chain: Option, authz_policy: Option, @@ -1254,12 +1288,133 @@ impl AuthGrpcRouter { self.logons = logons; self } + + /// The caller resolution this router applies, for the HTTP `/mcp` endpoint. + pub(crate) fn caller_authenticator(&self) -> CallerAuthenticator { + CallerAuthenticator { + authenticator_chain: self.authenticator_chain.clone(), + peer_identity: self.peer_identity.clone(), + mtls_auth_enabled: self.mtls_auth_enabled, + allow_unauthenticated_users: self.allow_unauthenticated_users, + operator: self.operator.clone(), + connection_source: self.connection_source, + } + } +} + +/// Who is calling: the connection's credentials and settings that the gateway +/// authenticates every request against. Shared by the gRPC auth router and +/// the HTTP `/mcp` endpoint so both resolve callers the same way. +#[derive(Clone)] +pub struct CallerAuthenticator { + authenticator_chain: Option, + peer_identity: Option, + mtls_auth_enabled: bool, + allow_unauthenticated_users: bool, + operator: Option, + connection_source: Option, +} + +impl CallerAuthenticator { + /// Where this connection came from, for audit events. + pub const fn connection_source(&self) -> Option { + self.connection_source + } + + /// Resolve the caller of `path` from `headers` and the connection, or the + /// status to refuse it with. Authentication failures are audited here. + pub async fn authenticate( + &self, + headers: &http::HeaderMap, + path: &str, + ) -> Result { + let chain = self.authenticator_chain.clone(); + let peer_identity = self.peer_identity.clone(); + let mtls_auth_enabled = self.mtls_auth_enabled; + let allow_unauthenticated_users = self.allow_unauthenticated_users; + let operator = self.operator.clone(); + let connection_source = self.connection_source; + let origin = |headers: &http::HeaderMap| RequestOrigin::new(connection_source, headers); + let principal = if let Some(operator) = operator { + if headers.contains_key(http::header::AUTHORIZATION) { + audit::emit_authentication_failure( + path, + &origin(headers), + Some(AuthMechanism::Mtls), + AuthFailureReason::ConflictingCredentials, + ); + return Err(tonic::Status::unauthenticated( + "operator certificates must not be combined with authorization headers", + )); + } + Principal::Operator(operator) + } else if let Some(chain) = chain { + match chain.authenticate(headers, path).await { + Ok(Authentication::Accepted(p)) => p, + Ok(outcome) => match (mtls_auth_enabled, peer_identity) { + (true, Some(identity)) => Principal::User(UserPrincipal { identity }), + _ if allow_unauthenticated_users => unauthenticated_dev_user_principal(), + _ => { + let (mechanism, reason) = match outcome { + Authentication::Declined(decline) => { + (Some(decline.mechanism), decline.reason) + } + _ => (None, AuthFailureReason::MissingCredential), + }; + audit::emit_authentication_failure( + path, + &origin(headers), + mechanism, + reason, + ); + return Err(tonic::Status::unauthenticated( + "missing authorization header", + )); + } + }, + Err(rejection) => { + audit::emit_authentication_failure( + path, + &origin(headers), + Some(rejection.mechanism), + rejection.reason, + ); + return Err(rejection.status); + } + } + } else if mtls_auth_enabled { + let Some(identity) = peer_identity else { + audit::emit_authentication_failure( + path, + &origin(headers), + Some(AuthMechanism::Mtls), + AuthFailureReason::MissingCredential, + ); + return Err(tonic::Status::unauthenticated("missing client certificate")); + }; + Principal::User(UserPrincipal { identity }) + } else if allow_unauthenticated_users { + unauthenticated_dev_user_principal() + } else { + audit::emit_authentication_failure( + path, + &origin(headers), + None, + AuthFailureReason::MissingCredential, + ); + return Err(tonic::Status::unauthenticated("authentication required")); + }; + Ok(principal) + } } +/// Subject of the built-in user on gateways that allow unauthenticated users. +pub const UNAUTHENTICATED_DEV_SUBJECT: &str = "unauthenticated-local-dev"; + fn unauthenticated_dev_user_principal() -> Principal { Principal::User(UserPrincipal { identity: Identity { - subject: "unauthenticated-local-dev".to_string(), + subject: UNAUTHENTICATED_DEV_SUBJECT.to_string(), display_name: Some("Unauthenticated Local Dev".to_string()), roles: vec!["openshell-user".to_string(), "openshell-admin".to_string()], scopes: vec!["openshell:all".to_string()], @@ -1288,12 +1443,10 @@ where } fn call(&mut self, req: Request) -> Self::Future { - let chain = self.authenticator_chain.clone(); + let caller_authenticator = self.caller_authenticator(); + // Service discovery rechecks a bearer token later with the same chain. + let chain = caller_authenticator.authenticator_chain.clone(); let authz_policy = self.authz_policy.clone(); - let peer_identity = self.peer_identity.clone(); - let mtls_auth_enabled = self.mtls_auth_enabled; - let allow_unauthenticated_users = self.allow_unauthenticated_users; - let operator = self.operator.clone(); let connection_source = self.connection_source; let logons = self.logons.clone(); let peer_certificate_sha256 = self.peer_certificate_sha256.clone(); @@ -1307,84 +1460,21 @@ where let path = req.uri().path().to_string(); let origin = |headers: &http::HeaderMap| RequestOrigin::new(connection_source, headers); + // Set only by the in-process `/mcp` dispatch; tonic never fills + // request extensions from the network. + let mcp_origin = req.extensions().get::().is_some(); // Health probes and reflection — truly unauthenticated. if oidc::is_unauthenticated_method(&path) { return inner.ready().await?.call(req).await; } - let principal = if let Some(operator) = operator { - if req.headers().contains_key(http::header::AUTHORIZATION) { - audit::emit_authentication_failure( - &path, - &origin(req.headers()), - Some(AuthMechanism::Mtls), - AuthFailureReason::ConflictingCredentials, - ); - return Ok(status_response(tonic::Status::unauthenticated( - "operator certificates must not be combined with authorization headers", - ))); - } - Principal::Operator(operator) - } else if let Some(chain) = &chain { - match chain.authenticate(req.headers(), &path).await { - Ok(Authentication::Accepted(p)) => p, - Ok(outcome) => match (mtls_auth_enabled, peer_identity) { - (true, Some(identity)) => Principal::User(UserPrincipal { identity }), - _ if allow_unauthenticated_users => unauthenticated_dev_user_principal(), - _ => { - let (mechanism, reason) = match outcome { - Authentication::Declined(decline) => { - (Some(decline.mechanism), decline.reason) - } - _ => (None, AuthFailureReason::MissingCredential), - }; - audit::emit_authentication_failure( - &path, - &origin(req.headers()), - mechanism, - reason, - ); - return Ok(status_response(tonic::Status::unauthenticated( - "missing authorization header", - ))); - } - }, - Err(rejection) => { - audit::emit_authentication_failure( - &path, - &origin(req.headers()), - Some(rejection.mechanism), - rejection.reason, - ); - return Ok(status_response(rejection.status)); - } - } - } else if mtls_auth_enabled { - let Some(identity) = peer_identity else { - audit::emit_authentication_failure( - &path, - &origin(req.headers()), - Some(AuthMechanism::Mtls), - AuthFailureReason::MissingCredential, - ); - return Ok(status_response(tonic::Status::unauthenticated( - "missing client certificate", - ))); - }; - Principal::User(UserPrincipal { identity }) - } else if allow_unauthenticated_users { - unauthenticated_dev_user_principal() - } else { - audit::emit_authentication_failure( - &path, - &origin(req.headers()), - None, - AuthFailureReason::MissingCredential, - ); - return Ok(status_response(tonic::Status::unauthenticated( - "authentication required", - ))); + let principal = match caller_authenticator + .authenticate(req.headers(), &path) + .await + { + Ok(principal) => principal, + Err(status) => return Ok(status_response(status)), }; let origin = origin(req.headers()); audit::emit_logon( @@ -1418,7 +1508,8 @@ where .and_then(|policy| policy.check(&user.identity, &path).err()) .map(|rbac| (rbac.denial, rbac.status)), Principal::Sandbox(_) - if !crate::auth::sandbox_methods::is_sandbox_callable(&path) => + if !(crate::auth::sandbox_methods::is_sandbox_callable(&path) + || (mcp_origin && crate::mcp::is_sandbox_tool_method(&path))) => { method_denied("sandbox principals may not call this method") } @@ -2581,6 +2672,13 @@ mod tests { .await .unwrap(); assert_eq!(grpc_status_from_response(&second), "8"); + let status = tonic::Status::from_header_map(second.headers()).expect("grpc status"); + let details = openshell_core::rpc_error::decode_details(&status).expect("error details"); + let info = details.error_info().expect("error info"); + assert_eq!( + (info.reason.as_str(), info.domain.as_str()), + ("RATE_LIMITED", openshell_core::rpc_error::ERROR_DOMAIN) + ); assert_eq!(calls.load(Ordering::Relaxed), 1); } @@ -4346,6 +4444,51 @@ mod tests { } } + #[tokio::test] + async fn sandbox_principal_reaches_mcp_methods_only_with_the_mcp_marker() { + for (path, tool_method) in [ + ("/openshell.v1.OpenShell/CreateSandbox", true), + ("/openshell.v1.OpenShell/ListSandboxes", true), + ("/openshell.v1.OpenShell/ExecSandbox", true), + ("/openshell.v1.OpenShell/DeleteSandbox", true), + ("/openshell.v1.OpenShell/GetSandboxLogs", true), + ("/openshell.v1.OpenShell/ListSandboxTemplates", true), + ("/openshell.v1.OpenShell/GetSandboxTemplate", false), + ("/openshell.v1.OpenShell/CreateProvider", false), + ] { + // Without the marker is a direct gRPC call with a sandbox token. + for marked in [true, false] { + let mock = Arc::new(MockAuthenticator::returning(Ok( + Authentication::Accepted(sandbox("sandbox-a")), + ))); + let (recorder, seen) = PrincipalRecorder::new(); + let mut router = AuthGrpcRouter::new( + recorder, + Some(AuthenticatorChain::new(vec![mock])), + None, + ); + let mut request = empty_request(path); + if marked { + request.extensions_mut().insert(crate::mcp::McpOrigin); + } + + let res = router.call(request).await.unwrap(); + + if tool_method && marked { + assert!(grpc_status(&res).is_none(), "{path}"); + assert!(matches!(*seen.lock().unwrap(), Some(Principal::Sandbox(_)))); + } else { + assert!(seen.lock().unwrap().is_none(), "{path} marked={marked}"); + assert_eq!( + grpc_status(&res).as_deref(), + Some("7"), + "{path} marked={marked}" + ); + } + } + } + } + fn assert_authorization_denial(event: &serde_json::Value, operation: &str, reason: &str) { assert_denial( event, diff --git a/crates/openshell-server/src/persistence/mod.rs b/crates/openshell-server/src/persistence/mod.rs index cb8ee48173..1974ae25bc 100644 --- a/crates/openshell-server/src/persistence/mod.rs +++ b/crates/openshell-server/src/persistence/mod.rs @@ -337,7 +337,7 @@ pub fn generate_name() -> String { /// Extracted to avoid repeating the identical decode-and-hydrate block across /// `get_message`, `get_message_by_name`, `list_messages`, and /// `list_messages_with_selector`. -fn decode_record( +pub fn decode_record( record: ObjectRecord, ) -> PersistenceResult { let payload = legacy_time_wire::migrate(T::object_type(), &record.payload)?; diff --git a/crates/openshell-server/src/storage_proto.rs b/crates/openshell-server/src/storage_proto.rs index 4c452c7cf3..6cdc96244f 100644 --- a/crates/openshell-server/src/storage_proto.rs +++ b/crates/openshell-server/src/storage_proto.rs @@ -252,13 +252,13 @@ mod tests { // The service backend HTTP version is part of both schemas. Legacy // endpoint records omit it and continue to use HTTP/1.1. const PUBLIC_RPC_SCHEMA_SHA256: &str = - "edfc80ad192e77e1a9d1e1d6e3342280e4438f8bf7cb49969f580060df9a056a"; + "1b5705561cec3a6598dc3c9223caf6a59a4004b455835c17ae1cf6843d60026b"; // 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 = - "ca31950286327bc385fae933bbb9e34d3c9191214f9b549c558bba40957fcc65"; + "447e39c8066d982abb276f6cf1e4eb619940f5af8dda4329eb1713cd55526672"; const PUBLIC_DURABLE_OVERLAP_SHA256: &str = - "d0eead2cd403f6f52ecd9b7df73ca7db15e84dd847e11bc9d50469970204e589"; + "6452a7aa7fe216fb51fef796a63ce4c0dab60ff065ae178ace9cdabff6e65c42"; // Encoded with the schema that omitted stable_placeholder. Keep these // bytes fixed so the current encoder cannot hide a compatibility change. const LEGACY_STATIC_PROFILE: &str = "0a240a116c65676163792d70726f66696c652d6964120d6c65676163792d737461746963280712510a0d6c65676163792d73746174696312184c6567616379207374617469632063726564656e7469616c2a260a076170695f6b65791a1153594e5448455449435f4150495f4b455920012a06626561726572"; @@ -817,9 +817,9 @@ mod tests { overlap_hash.as_str(), ), ( - (369, 32), - (104, 23), - (88, 23), + (371, 32), + (106, 23), + (90, 23), PUBLIC_RPC_SCHEMA_SHA256, DURABLE_SCHEMA_SHA256, PUBLIC_DURABLE_OVERLAP_SHA256 @@ -910,6 +910,16 @@ mod tests { assert!(!credential.stable_placeholder); } + #[test] + fn sandbox_payload_without_parent_decodes_as_root() { + use openshell_core::proto::Sandbox; + + let sandbox = Sandbox::decode(legacy_bytes(SANDBOX_WITHOUT_ENDPOINT_STATUS).as_slice()) + .expect("stored sandbox without a parent must decode"); + assert!(sandbox.parent.is_none()); + assert!(sandbox.created_on_behalf_of.is_none()); + } + #[test] fn sandbox_payload_without_endpoint_status_decodes() { use openshell_core::proto::{Sandbox, SandboxPhase}; diff --git a/crates/openshell-supervisor-network/Cargo.toml b/crates/openshell-supervisor-network/Cargo.toml index d1d4435072..c6d054228d 100644 --- a/crates/openshell-supervisor-network/Cargo.toml +++ b/crates/openshell-supervisor-network/Cargo.toml @@ -31,6 +31,7 @@ aws-sigv4 = { version = "1", features = ["sign-http", "http1"] } aws-credential-types = { version = "1", features = ["hardcoded-credentials"] } aws-smithy-runtime-api = { version = "1", features = ["client"] } http = { workspace = true } +http-body-util = { workspace = true } base64 = { workspace = true } bytes = { workspace = true } flate2 = "1" @@ -58,6 +59,7 @@ thiserror = { workspace = true } tokio = { workspace = true } tokio-rustls = { workspace = true } tonic = { workspace = true } +tower = { workspace = true } tower-mcp-types = { workspace = true } tracing = { workspace = true } tracing-opentelemetry = { workspace = true } @@ -74,6 +76,8 @@ bundled-ca-roots = ["dep:webpki-roots"] experimental = ["openshell-policy/experimental"] [dev-dependencies] +hyper = { workspace = true } +hyper-util = { workspace = true } openshell-policy-cedar-runtime = { path = "../openshell-policy-cedar-runtime" } openshell-sandbox-backend = { path = "../openshell-sandbox-backend", features = ["test-support"] } diff --git a/crates/openshell-supervisor-network/src/gateway_mcp_door.rs b/crates/openshell-supervisor-network/src/gateway_mcp_door.rs new file mode 100644 index 0000000000..d28890b48f --- /dev/null +++ b/crates/openshell-supervisor-network/src/gateway_mcp_door.rs @@ -0,0 +1,705 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Sandbox-local door to the gateway's MCP endpoint. +//! +//! The workload reaches `http://openshell.local/mcp`. The supervisor forwards +//! the request body to the gateway's `/mcp` over one gateway connection the +//! door opens on first use and then reuses, with the sandbox's own +//! credentials attached to each request. The workload never holds a gateway +//! credential. + +use crate::policy_local::PolicyLocalContext; +use bytes::Bytes; +use http_body_util::BodyExt; +use miette::{IntoDiagnostic, Result}; +use openshell_ocsf::{ActivityId, HttpActivityBuilder, HttpRequest, SeverityId, StatusId}; +use tokio::io::{AsyncRead, AsyncWrite, AsyncWriteExt}; +use tower::ServiceExt; + +pub const DOOR_HOST: &str = "openshell.local"; +const DOOR_PATH: &str = "/mcp"; +/// Largest request body the door forwards. +const MAX_REQUEST_BYTES: usize = 2 * 1024 * 1024; +/// Largest gateway reply the door holds in memory. +const MAX_RESPONSE_BYTES: usize = 4 * 1024 * 1024; +/// Covers the gateway's 45 second tool limit with margin. +const GATEWAY_TIMEOUT: std::time::Duration = std::time::Duration::from_mins(1); +/// Door requests one sandbox may have open at once, so a workload cannot +/// flood the gateway through its supervisor. +const MAX_CONCURRENT_REQUESTS: usize = 8; +/// Request headers copied from the workload. Identity headers are never copied. +const FORWARDED_HEADERS: [&str; 3] = ["content-type", "accept", "mcp-protocol-version"]; + +/// Whether `host` (a Host header or proxy target, with optional `:80`) names the door. +pub fn is_door_host(host: &str) -> bool { + host.eq_ignore_ascii_case(DOOR_HOST) || host.eq_ignore_ascii_case("openshell.local:80") +} + +/// The single Host header of a raw HTTP request, when there is exactly one. +pub fn request_host(initial_request: &[u8]) -> Option { + let mut hosts = header_values(initial_request, "host"); + let host = hosts.next()?; + hosts.next().is_none().then_some(host) +} + +/// Serve one door request. The caller has already matched the door host. +pub async fn handle( + ctx: &PolicyLocalContext, + method: &str, + target: &str, + initial_request: &[u8], + client: &mut S, +) -> Result<()> +where + S: AsyncRead + AsyncWrite + Unpin, +{ + // A browser in the sandbox attaches Origin; only the door's own origin is + // accepted. Agents send none. + if let Some(origin) = header_values(initial_request, "origin").next() + && !is_door_host( + origin + .trim_end_matches('/') + .strip_prefix("http://") + .unwrap_or(""), + ) + { + return refuse(client, method, 403, "origin not allowed").await; + } + let path = target.split('?').next().unwrap_or(target); + if path != DOOR_PATH { + return refuse( + client, + method, + 404, + "only /mcp is served at openshell.local", + ) + .await; + } + if method != "POST" { + return refuse(client, method, 405, "openshell.local/mcp accepts POST only").await; + } + if crate::policy_local::declared_body_len(initial_request).unwrap_or(0) > MAX_REQUEST_BYTES { + return refuse( + client, + method, + 413, + "request body is larger than the 2 MiB openshell.local/mcp accepts", + ) + .await; + } + let door = ctx.mcp_door(); + let Ok(_slot) = door.slots.try_acquire() else { + return refuse( + client, + method, + 503, + "too many gateway requests at once; try again", + ) + .await; + }; + let body = + crate::policy_local::read_request_body(initial_request, client, MAX_REQUEST_BYTES).await?; + let Some(gateway) = ctx.gateway() else { + return refuse( + client, + method, + 503, + "this sandbox has no gateway connection", + ) + .await; + }; + + let mut request = http::Request::builder().method("POST").uri(DOOR_PATH); + for name in FORWARDED_HEADERS { + if let Some(value) = header_values(initial_request, name).next() { + request = request.header(name, value); + } + } + let request = request + .body(tonic::body::Body::new(http_body_util::Full::new( + Bytes::from(body), + ))) + .into_diagnostic()?; + + match tokio::time::timeout(GATEWAY_TIMEOUT, forward(door, gateway, request)).await { + Ok(Ok((status, content_type, reply))) => { + emit_door_event( + method, + status, + SeverityId::Informational, + StatusId::Success, + "forwarded to the gateway", + ); + respond(client, status, &content_type, &reply).await + } + Ok(Err(Forward::TooLarge)) => { + refuse( + client, + method, + 502, + "the gateway reply is larger than the door accepts", + ) + .await + } + Ok(Err(Forward::Refused(error))) => { + tracing::warn!(%error, "openshell.local: gateway request refused locally"); + refuse( + client, + method, + 502, + "this sandbox's gateway credentials are not available", + ) + .await + } + Ok(Err(Forward::Unreachable(error))) => { + tracing::warn!(%error, "openshell.local: gateway request failed"); + refuse(client, method, 502, "gateway unreachable").await + } + Err(_) => refuse(client, method, 504, "the gateway did not answer in time").await, + } +} + +enum Forward { + Unreachable(String), + TooLarge, + /// The request was refused before it reached `/mcp`, such as by the + /// credential interceptor once the sandbox's token is revoked. + Refused(String), +} + +/// The door's gateway connection and request slots, shared by every door +/// request of one sandbox. +pub struct DoorConnection { + /// Opened on first use and reused: one HTTP/2 connection carries every + /// request. The interceptor reads the sandbox's token slot on each + /// request, so a renewed token is used without reconnecting. + channel: tokio::sync::Mutex>, + slots: tokio::sync::Semaphore, +} + +impl Default for DoorConnection { + fn default() -> Self { + Self { + channel: tokio::sync::Mutex::new(None), + slots: tokio::sync::Semaphore::new(MAX_CONCURRENT_REQUESTS), + } + } +} + +impl DoorConnection { + async fn channel( + &self, + gateway: &openshell_core::grpc_client::GatewayEndpoint, + ) -> std::result::Result { + let mut cached = self.channel.lock().await; + if let Some(channel) = cached.as_ref() { + return Ok(channel.clone()); + } + let channel = openshell_core::grpc_client::connect_channel_pub(gateway) + .await + .map_err(|e| Forward::Unreachable(e.to_string()))?; + *cached = Some(channel.clone()); + Ok(channel) + } + + /// Drop the cached connection after a transport failure, so the next + /// request connects again. + async fn discard(&self) { + *self.channel.lock().await = None; + } +} + +/// POST to the gateway's `/mcp` over the door's gateway connection, which +/// shares TLS settings, the gateway address and the token slot with gRPC. +async fn forward( + door: &DoorConnection, + gateway: &openshell_core::grpc_client::GatewayEndpoint, + request: http::Request, +) -> std::result::Result<(u16, String, Vec), Forward> { + let channel = door.channel(gateway).await?; + let response = match channel.oneshot(request).await { + Ok(response) => response, + Err(error) => { + door.discard().await; + return Err(Forward::Unreachable(error.to_string())); + } + }; + // `/mcp` never answers with gRPC status. One here comes from the channel + // itself, which reports a refusal as an empty gRPC reply, not as an error. + if let Some(code) = response + .headers() + .get("grpc-status") + .filter(|code| code.as_bytes() != b"0") + { + let message = response + .headers() + .get("grpc-message") + .and_then(|message| message.to_str().ok()) + .unwrap_or_default(); + return Err(Forward::Refused(format!( + "grpc-status {}: {message}", + String::from_utf8_lossy(code.as_bytes()) + ))); + } + let status = response.status().as_u16(); + let content_type = response + .headers() + .get(http::header::CONTENT_TYPE) + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/json") + .to_string(); + let mut body = response.into_body(); + let mut reply = Vec::new(); + while let Some(frame) = body.frame().await { + let frame = match frame { + Ok(frame) => frame, + Err(error) => { + door.discard().await; + return Err(Forward::Unreachable(error.to_string())); + } + }; + if let Some(data) = frame.data_ref() { + if reply.len() + data.len() > MAX_RESPONSE_BYTES { + return Err(Forward::TooLarge); + } + reply.extend_from_slice(data); + } + } + Ok((status, content_type, reply)) +} + +/// Refuse a CONNECT to the door, which only speaks plain HTTP. +pub async fn refuse_connect(client: &mut S) -> Result<()> { + refuse( + client, + "CONNECT", + 400, + "openshell.local is plain HTTP on port 80", + ) + .await +} + +/// Answer with `status` and a plain-text `message`, logged as a refusal. +pub(crate) async fn refuse( + client: &mut S, + method: &str, + status: u16, + message: &str, +) -> Result<()> { + emit_door_event(method, status, SeverityId::Low, StatusId::Failure, message); + respond(client, status, "text/plain", message.as_bytes()).await +} + +async fn respond( + client: &mut S, + status: u16, + content_type: &str, + body: &[u8], +) -> Result<()> { + let reason = http::StatusCode::from_u16(status) + .ok() + .and_then(|code| code.canonical_reason()) + .unwrap_or(""); + let head = format!( + "HTTP/1.1 {status} {reason}\r\nContent-Type: {content_type}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", + body.len() + ); + client.write_all(head.as_bytes()).await.into_diagnostic()?; + client.write_all(body).await.into_diagnostic()?; + client.flush().await.into_diagnostic() +} + +fn header_values<'a>( + initial_request: &'a [u8], + wanted: &'a str, +) -> impl Iterator + 'a { + let head_end = initial_request + .windows(4) + .position(|window| window == b"\r\n\r\n") + .unwrap_or(initial_request.len()); + std::str::from_utf8(&initial_request[..head_end]) + .unwrap_or("") + .split("\r\n") + .skip(1) + .filter_map(|line| line.split_once(':')) + .filter(move |(name, _)| name.trim().eq_ignore_ascii_case(wanted)) + .map(|(_, value)| value.trim().to_string()) +} + +fn emit_door_event( + method: &str, + response_code: u16, + severity: SeverityId, + status: StatusId, + message: &str, +) { + crate::telemetry::egress_emit!(build_door_event( + method, + response_code, + severity, + status, + message + )); +} + +fn build_door_event( + method: &str, + response_code: u16, + severity: SeverityId, + status: StatusId, + message: &str, +) -> openshell_ocsf::OcsfEvent { + HttpActivityBuilder::new(openshell_ocsf::ctx::ctx()) + .activity(ActivityId::for_http_method(method)) + .http_request(HttpRequest { + http_method: method.parse().expect("HTTP method parsing is infallible"), + url: None, + }) + .http_response(openshell_ocsf::HttpResponse { + code: response_code, + }) + .severity(severity) + .status(status) + .message(format!("openshell.local: {message}")) + .build() +} + +#[cfg(test)] +mod tests { + use super::*; + use openshell_core::grpc_client::{GatewayCredentials, GatewayEndpoint}; + use std::sync::{Arc, Mutex}; + use tokio::io::AsyncReadExt; + + fn context(gateway: Option) -> PolicyLocalContext { + PolicyLocalContext::new( + None, + gateway, + None, + openshell_core::proposals::AgentProposals::new(false), + tokio::sync::watch::channel(String::new()).1, + ) + } + + /// Run one request through the door and return the raw response. + async fn door(ctx: &PolicyLocalContext, request: &[u8]) -> String { + let head = std::str::from_utf8(request).unwrap(); + let mut line = head.split_whitespace(); + let (method, target) = (line.next().unwrap(), line.next().unwrap()); + let (mut client, mut workload) = tokio::io::duplex(8 * 1024 * 1024); + handle(ctx, method, target, request, &mut client) + .await + .unwrap(); + drop(client); + let mut response = Vec::new(); + workload.read_to_end(&mut response).await.unwrap(); + String::from_utf8_lossy(&response).into_owned() + } + + #[test] + fn only_openshell_local_on_port_80_is_the_door() { + assert!(is_door_host("openshell.local")); + assert!(is_door_host("OpenShell.Local:80")); + assert!(!is_door_host("policy.local")); + assert!(!is_door_host("openshell.local:8080")); + assert!(!is_door_host("attacker.example")); + } + + #[test] + fn door_events_are_valid_ocsf_and_carry_no_body_or_token() { + for (method, code, severity, status) in [ + ("POST", 200, SeverityId::Informational, StatusId::Success), + ("GET", 405, SeverityId::Low, StatusId::Failure), + ("CONNECT", 400, SeverityId::Low, StatusId::Failure), + ] { + let json = serde_json::to_value(build_door_event(method, code, severity, status, "x")) + .unwrap(); + assert_eq!(json["http_response"]["code"], code); + assert!(json["http_request"].get("url").is_none()); + openshell_ocsf_validate::validate_event(&json).unwrap_or_else(|e| panic!("{e}")); + } + } + + #[test] + fn a_request_needs_exactly_one_host() { + let one = b"POST /mcp HTTP/1.1\r\nHost: openshell.local\r\n\r\n"; + let none = b"POST /mcp HTTP/1.1\r\n\r\n"; + let two = b"POST /mcp HTTP/1.1\r\nHost: openshell.local\r\nHost: evil\r\n\r\n"; + assert_eq!(request_host(one).as_deref(), Some("openshell.local")); + assert_eq!(request_host(none), None); + assert_eq!(request_host(two), None); + } + + #[tokio::test] + async fn the_door_refuses_what_it_does_not_serve() { + let ctx = context(None); + let cases: [(&[u8], &str); 5] = [ + (b"POST /other HTTP/1.1\r\nHost: openshell.local\r\n\r\n", "404"), + (b"GET /mcp HTTP/1.1\r\nHost: openshell.local\r\n\r\n", "405"), + ( + b"POST /mcp HTTP/1.1\r\nHost: openshell.local\r\nOrigin: http://evil.example\r\n\r\n", + "403", + ), + ( + b"POST /mcp HTTP/1.1\r\nHost: openshell.local\r\nContent-Length: 3000000\r\n\r\n", + "413", + ), + (b"POST /mcp HTTP/1.1\r\nHost: openshell.local\r\nContent-Length: 2\r\n\r\n{}", "503"), + ]; + for (request, status) in cases { + let response = door(&ctx, request).await; + assert!( + response.starts_with(&format!("HTTP/1.1 {status}")), + "{response}" + ); + } + } + + type Seen = Arc>>; + + /// A plaintext HTTP/2 server that records one request and answers with `reply`. + async fn fake_gateway(reply: Vec) -> (GatewayEndpoint, Seen) { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let seen: Seen = Arc::default(); + let recorder = seen.clone(); + tokio::spawn(async move { + loop { + let (stream, _) = listener.accept().await.unwrap(); + let (recorder, reply) = (recorder.clone(), reply.clone()); + tokio::spawn(async move { + let service = hyper::service::service_fn( + move |request: http::Request| { + let (recorder, reply) = (recorder.clone(), reply.clone()); + async move { + let (parts, body) = request.into_parts(); + let body = body.collect().await.unwrap().to_bytes(); + *recorder.lock().unwrap() = Some((parts.headers, body)); + Ok::<_, std::convert::Infallible>( + http::Response::builder() + .header("content-type", "application/json") + .body(http_body_util::Full::new(Bytes::from(reply))) + .unwrap(), + ) + } + }, + ); + let _ = hyper_util::server::conn::auto::Builder::new( + hyper_util::rt::TokioExecutor::new(), + ) + .serve_connection(hyper_util::rt::TokioIo::new(stream), service) + .await; + }); + } + }); + let credentials = GatewayCredentials::from_gateway_token("sandbox-token").unwrap(); + ( + GatewayEndpoint::new(format!("http://{address}"), credentials), + seen, + ) + } + + #[tokio::test] + async fn the_door_forwards_with_the_sandbox_token_and_only_mcp_headers() { + let (gateway, seen) = + fake_gateway(br#"{"jsonrpc":"2.0","id":1,"result":{}}"#.to_vec()).await; + let ctx = context(Some(gateway)); + let body = r#"{"jsonrpc":"2.0","id":1,"method":"ping","params":{"q":"a b $HOME"}}"#; + let request = format!( + "POST /mcp HTTP/1.1\r\nHost: openshell.local\r\nAuthorization: Bearer agent-token\r\nCookie: a=b\r\nContent-Type: application/json\r\nMcp-Protocol-Version: 2025-11-25\r\nMcp-Session-Id: s1\r\nContent-Length: {}\r\n\r\n{body}", + body.len() + ); + let response = door(&ctx, request.as_bytes()).await; + assert!(response.starts_with("HTTP/1.1 200"), "{response}"); + assert!(response.ends_with(r#"{"jsonrpc":"2.0","id":1,"result":{}}"#)); + + let (headers, forwarded) = seen + .lock() + .unwrap() + .take() + .expect("gateway saw the request"); + assert_eq!(forwarded, body.as_bytes()); + assert_eq!(headers["authorization"], "Bearer sandbox-token"); + assert_eq!(headers["mcp-protocol-version"], "2025-11-25"); + assert_eq!(headers["content-type"], "application/json"); + assert!(headers.get("cookie").is_none()); + assert!(headers.get("mcp-session-id").is_none()); + } + + #[tokio::test] + async fn the_door_refuses_an_oversized_gateway_reply() { + let (gateway, _) = fake_gateway(vec![b'x'; MAX_RESPONSE_BYTES + 1]).await; + let ctx = context(Some(gateway)); + let response = door( + &ctx, + b"POST /mcp HTTP/1.1\r\nHost: openshell.local\r\nContent-Length: 2\r\n\r\n{}", + ) + .await; + assert!(response.starts_with("HTTP/1.1 502"), "{response}"); + } + + const PING: &[u8] = + b"POST /mcp HTTP/1.1\r\nHost: openshell.local\r\nContent-Length: 2\r\n\r\n{}"; + + /// A plaintext HTTP/2 gateway that counts the connections it accepts, + /// can drop them all, and answers each request only once `replies` + /// grants a permit. + struct CountingGateway { + endpoint: GatewayEndpoint, + connections: Arc, + requests: Arc, + replies: Arc, + open: Arc>>, + } + + impl CountingGateway { + async fn start(replies: usize) -> Self { + use std::sync::atomic::Ordering; + + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let connections = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let requests = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let replies = Arc::new(tokio::sync::Semaphore::new(replies)); + let open: Arc>> = Arc::default(); + let (counted, seen, gate, tasks) = ( + connections.clone(), + requests.clone(), + replies.clone(), + open.clone(), + ); + tokio::spawn(async move { + loop { + let (stream, _) = listener.accept().await.unwrap(); + counted.fetch_add(1, Ordering::SeqCst); + let (seen, gate) = (seen.clone(), gate.clone()); + let task = tokio::spawn(async move { + let service = hyper::service::service_fn( + move |_: http::Request| { + let (seen, gate) = (seen.clone(), gate.clone()); + async move { + seen.fetch_add(1, Ordering::SeqCst); + gate.acquire().await.unwrap().forget(); + Ok::<_, std::convert::Infallible>( + http::Response::builder() + .header("content-type", "application/json") + .body(http_body_util::Full::new(Bytes::from_static( + b"{}", + ))) + .unwrap(), + ) + } + }, + ); + let _ = hyper_util::server::conn::auto::Builder::new( + hyper_util::rt::TokioExecutor::new(), + ) + .serve_connection(hyper_util::rt::TokioIo::new(stream), service) + .await; + }); + tasks.lock().unwrap().push(task.abort_handle()); + } + }); + let credentials = GatewayCredentials::from_gateway_token("sandbox-token").unwrap(); + Self { + endpoint: GatewayEndpoint::new(format!("http://{address}"), credentials), + connections, + requests, + replies, + open, + } + } + + fn connections(&self) -> usize { + self.connections.load(std::sync::atomic::Ordering::SeqCst) + } + + /// Close every connection the gateway holds, as a restart would. + fn drop_connections(&self) { + for task in self.open.lock().unwrap().drain(..) { + task.abort(); + } + } + } + + #[tokio::test] + async fn door_requests_share_one_gateway_connection() { + let gateway = CountingGateway::start(usize::MAX >> 4).await; + let ctx = context(Some(gateway.endpoint.clone())); + + for _ in 0..5 { + let response = door(&ctx, PING).await; + assert!(response.starts_with("HTTP/1.1 200"), "{response}"); + } + + assert_eq!(gateway.connections(), 1); + } + + #[tokio::test] + async fn the_door_reconnects_after_the_gateway_drops_its_connection() { + let gateway = CountingGateway::start(usize::MAX >> 4).await; + let ctx = context(Some(gateway.endpoint.clone())); + assert!(door(&ctx, PING).await.starts_with("HTTP/1.1 200")); + + gateway.drop_connections(); + + // The request on the dropped connection may fail once; the next one + // must reach the gateway on a new connection. + let mut response = door(&ctx, PING).await; + if !response.starts_with("HTTP/1.1 200") { + response = door(&ctx, PING).await; + } + assert!(response.starts_with("HTTP/1.1 200"), "{response}"); + assert_eq!(gateway.connections(), 2); + } + + #[tokio::test] + async fn the_door_refuses_at_once_when_every_slot_is_busy() { + let gateway = CountingGateway::start(0).await; + let ctx = Arc::new(context(Some(gateway.endpoint.clone()))); + let busy: Vec<_> = (0..MAX_CONCURRENT_REQUESTS) + .map(|_| { + let ctx = ctx.clone(); + tokio::spawn(async move { door(&ctx, PING).await }) + }) + .collect(); + while gateway.requests.load(std::sync::atomic::Ordering::SeqCst) < MAX_CONCURRENT_REQUESTS { + tokio::time::sleep(std::time::Duration::from_millis(5)).await; + } + + let response = tokio::time::timeout(std::time::Duration::from_secs(1), door(&ctx, PING)) + .await + .expect("refused at once, not queued"); + assert!(response.starts_with("HTTP/1.1 503"), "{response}"); + assert!(response.ends_with("too many gateway requests at once; try again")); + + // Finished requests free their slots. + gateway.replies.add_permits(MAX_CONCURRENT_REQUESTS + 1); + for request in busy { + assert!(request.await.unwrap().starts_with("HTTP/1.1 200")); + } + assert!(door(&ctx, PING).await.starts_with("HTTP/1.1 200")); + } + + #[tokio::test] + async fn a_reused_connection_reads_the_token_slot_on_every_request() { + let gateway = CountingGateway::start(usize::MAX >> 4).await; + let ctx = context(Some(gateway.endpoint.clone())); + assert!(door(&ctx, PING).await.starts_with("HTTP/1.1 200")); + + // Renewal and revocation write the same slot. Revoking shows the + // cached connection does not keep the token it was opened with. + gateway.endpoint.credentials().revoke(); + let before = gateway.requests.load(std::sync::atomic::Ordering::SeqCst); + let response = door(&ctx, PING).await; + + assert!(response.starts_with("HTTP/1.1 502"), "{response}"); + assert!(response.ends_with("this sandbox's gateway credentials are not available")); + assert_eq!( + gateway.requests.load(std::sync::atomic::Ordering::SeqCst), + before, + "the request never reached the gateway" + ); + } +} diff --git a/crates/openshell-supervisor-network/src/lib.rs b/crates/openshell-supervisor-network/src/lib.rs index 9073ce732a..4bab79f409 100644 --- a/crates/openshell-supervisor-network/src/lib.rs +++ b/crates/openshell-supervisor-network/src/lib.rs @@ -15,6 +15,7 @@ mod binary_resolution; #[cfg(feature = "test-support")] pub mod conformance_support; +pub mod gateway_mcp_door; #[cfg(all(test, feature = "experimental"))] use openshell_policy_cedar_runtime::cedar_only; mod google_cloud_metadata; diff --git a/crates/openshell-supervisor-network/src/policy_dns/mod.rs b/crates/openshell-supervisor-network/src/policy_dns/mod.rs index df40c208d1..1b421fdb2e 100644 --- a/crates/openshell-supervisor-network/src/policy_dns/mod.rs +++ b/crates/openshell-supervisor-network/src/policy_dns/mod.rs @@ -213,7 +213,9 @@ impl PolicyDnsService { let started = Instant::now(); let normalized_name = NormalizedName::parse(raw_name).map_err(|_| PolicyDnsError::InvalidName)?; - if normalized_name.as_str() == crate::policy_local::POLICY_LOCAL_HOST { + if normalized_name.as_str() == crate::policy_local::POLICY_LOCAL_HOST + || normalized_name.as_str() == crate::gateway_mcp_door::DOOR_HOST + { return if family == AddressFamily::Ipv4 { Ok(SyntheticAnswer { address: POLICY_LOCAL_ADDRESS.into(), @@ -863,6 +865,17 @@ mod tests { )); } + #[tokio::test] + async fn the_gateway_door_resolves_to_the_sandbox_local_address() { + let service = service("network_policies: {}\n", vec![]); + let answer = service + .answer_query("openshell.local", AddressFamily::Ipv4, Instant::now()) + .await + .expect("sandbox-local address"); + assert_eq!(answer.address, IpAddr::V4(POLICY_LOCAL_ADDRESS)); + assert_eq!(service.resolver.calls.load(Ordering::SeqCst), 0); + } + const BASE_POLICY: &str = r" network_policies: database: diff --git a/crates/openshell-supervisor-network/src/policy_local.rs b/crates/openshell-supervisor-network/src/policy_local.rs index bdf8898986..06b0b4144c 100644 --- a/crates/openshell-supervisor-network/src/policy_local.rs +++ b/crates/openshell-supervisor-network/src/policy_local.rs @@ -161,6 +161,7 @@ pub struct PolicyLocalContext { denials: DenialLogSource, token_grants: Option>, workspace_rx: tokio::sync::watch::Receiver, + mcp_door: crate::gateway_mcp_door::DoorConnection, } impl std::fmt::Debug for PolicyLocalContext { @@ -191,6 +192,7 @@ impl PolicyLocalContext { denials: DenialLogSource::default(), token_grants: None, workspace_rx, + mcp_door: crate::gateway_mcp_door::DoorConnection::default(), } } @@ -213,6 +215,16 @@ impl PolicyLocalContext { .with_denial_log(DenialLogSource::ShorthandFiles(shorthand_log_dir)) } + /// This sandbox instance's gateway address and credentials. + pub(crate) fn gateway(&self) -> Option<&GatewayEndpoint> { + self.gateway.as_ref() + } + + /// The gateway connection and request slots `openshell.local/mcp` shares. + pub(crate) fn mcp_door(&self) -> &crate::gateway_mcp_door::DoorConnection { + &self.mcp_door + } + /// Serve `/v1/denials` from `denials` instead of the process log files. #[must_use] pub fn with_denial_log(mut self, denials: DenialLogSource) -> Self { @@ -265,7 +277,7 @@ pub async fn handle_forward_request( where S: AsyncRead + AsyncWrite + Unpin, { - let body = read_request_body(initial_request, client).await?; + let body = read_request_body(initial_request, client, MAX_POLICY_LOCAL_BODY_BYTES).await?; let (status, payload) = route_request(ctx, method, path, &body).await; write_json_response(client, status, payload).await } @@ -1343,7 +1355,17 @@ fn network_endpoint_from_json( }) } -async fn read_request_body(initial_request: &[u8], client: &mut S) -> Result> +/// The body length a request declares in `Content-Length`, when it can be read. +pub(crate) fn declared_body_len(initial_request: &[u8]) -> Option { + let header_end = find_header_end(initial_request)?; + parse_content_length(&initial_request[..header_end]).ok() +} + +pub(crate) async fn read_request_body( + initial_request: &[u8], + client: &mut S, + max_body_bytes: usize, +) -> Result> where S: AsyncRead + Unpin, { @@ -1351,9 +1373,9 @@ where return Ok(Vec::new()); }; let content_length = parse_content_length(&initial_request[..header_end])?; - if content_length > MAX_POLICY_LOCAL_BODY_BYTES { + if content_length > max_body_bytes { return Err(miette::miette!( - "policy.local request body exceeds {MAX_POLICY_LOCAL_BODY_BYTES} bytes" + "sandbox-local request body exceeds {max_body_bytes} bytes" )); } @@ -1367,7 +1389,7 @@ where let mut chunk = vec![0u8; remaining.min(8192)]; let n = client.read(&mut chunk).await.into_diagnostic()?; if n == 0 { - return Err(miette::miette!("policy.local request body ended early")); + return Err(miette::miette!("sandbox-local request body ended early")); } body.extend_from_slice(&chunk[..n]); } @@ -1375,7 +1397,7 @@ where }; tokio::time::timeout(POLICY_LOCAL_BODY_READ_TIMEOUT, read_loop) .await - .map_err(|_| miette::miette!("policy.local request body read timed out"))??; + .map_err(|_| miette::miette!("sandbox-local request body read timed out"))??; Ok(body) } @@ -1390,7 +1412,7 @@ fn parse_content_length(headers: &[u8]) -> Result { .trim() .parse::() .into_diagnostic() - .map_err(|_| miette::miette!("invalid policy.local Content-Length")); + .map_err(|_| miette::miette!("invalid sandbox-local Content-Length")); } } Ok(0) diff --git a/crates/openshell-supervisor-network/src/proxy.rs b/crates/openshell-supervisor-network/src/proxy.rs index 46709329b6..5bd5253030 100644 --- a/crates/openshell-supervisor-network/src/proxy.rs +++ b/crates/openshell-supervisor-network/src/proxy.rs @@ -2983,6 +2983,19 @@ async fn handle_mediated_connection( } if policy_local_transparent { + // policy.local and openshell.local share one address; only the Host + // header tells them apart, and it is checked on every request. + if method != "CONNECT" + && target.starts_with('/') + && crate::gateway_mcp_door::request_host(&buf[..used]) + .is_some_and(|host| crate::gateway_mcp_door::is_door_host(&host)) + { + let ctx = policy_local_ctx + .as_ref() + .ok_or_else(|| miette::miette!("sandbox-local gateway context is unavailable"))?; + return crate::gateway_mcp_door::handle(ctx, method, target, &buf[..used], &mut client) + .await; + } if !valid_policy_local_request(method, target, request) { respond(&mut client, b"HTTP/1.1 400 Bad Request\r\n\r\n").await?; return Ok(()); @@ -3028,6 +3041,9 @@ async fn handle_mediated_connection( let (raw_host, port) = parse_target(target)?; let host = normalize_host(&raw_host); let (host_lc, raw_host_lc) = (host.to_ascii_lowercase(), raw_host.to_ascii_lowercase()); + if crate::gateway_mcp_door::is_door_host(&host_lc) { + return crate::gateway_mcp_door::refuse_connect(&mut client).await; + } let workload_addr = socket_addrs.map_or_else( || SocketAddr::from(([0, 0, 0, 0], 0)), |(workload, _)| workload, @@ -5856,6 +5872,23 @@ async fn handle_forward_proxy_inner( .await; } + if crate::gateway_mcp_door::is_door_host(&host_lc) { + if scheme != "http" || port != 80 { + return crate::gateway_mcp_door::refuse_connect(client).await; + } + if let Some(ctx) = policy_local_ctx { + return crate::gateway_mcp_door::handle(&ctx, method, &path, &buf[..used], client) + .await; + } + return crate::gateway_mcp_door::refuse( + client, + method, + 503, + "openshell.local is not configured", + ) + .await; + } + if host_lc == POLICY_LOCAL_HOST { if scheme != "http" || port != 80 { respond( @@ -10137,15 +10170,8 @@ process: { run_as_user: sandbox, run_as_group: sandbox } ); } - #[tokio::test] - async fn staged_policy_local_open_reaches_the_sandbox_scoped_api() { - let addr = crate::policy_dns::POLICY_LOCAL_ADDRESS; - for ip in [IpAddr::V4(addr), IpAddr::V6(addr.to_ipv6_mapped())] { - assert_policy_local_open_served(SocketAddr::new(ip, 80)).await; - } - } - - async fn assert_policy_local_open_served(destination: SocketAddr) { + /// Send one request over a transparent open to the sandbox-local address. + async fn staged_sandbox_local_request(destination: SocketAddr, request: &[u8]) -> String { let engine = Arc::new( native_identity_engine( include_str!("../data/sandbox-policy.rego"), @@ -10230,8 +10256,72 @@ process: { run_as_user: sandbox, run_as_group: sandbox } None, None, )); + workload.write_all(request).await.unwrap(); + let mut response = Vec::new(); + tokio::time::timeout( + std::time::Duration::from_secs(5), + workload.read_to_end(&mut response), + ) + .await + .expect("sandbox-local response timed out") + .unwrap(); + handler.await.unwrap().unwrap(); + String::from_utf8(response).unwrap() + } + + #[tokio::test] + async fn staged_policy_local_open_reaches_the_sandbox_scoped_api() { + let addr = crate::policy_dns::POLICY_LOCAL_ADDRESS; + for ip in [IpAddr::V4(addr), IpAddr::V6(addr.to_ipv6_mapped())] { + let response = staged_sandbox_local_request( + SocketAddr::new(ip, 80), + b"GET /v1/policy/current HTTP/1.1\r\nHost: policy.local\r\nConnection: close\r\n\r\n", + ) + .await; + assert!(response.starts_with("HTTP/1.1 200 "), "{response}"); + assert!(response.contains("\"format\":\"yaml\""), "{response}"); + } + } + + fn sandbox_local_destination() -> SocketAddr { + SocketAddr::new(IpAddr::V4(crate::policy_dns::POLICY_LOCAL_ADDRESS), 80) + } + + #[tokio::test] + async fn connect_to_the_gateway_door_is_refused_as_plain_http_only() { + let engine = Arc::new( + native_identity_engine( + include_str!("../data/sandbox-policy.rego"), + "network_policies: {}\n", + ) + .unwrap(), + ); + let (stream, mut workload) = tokio::io::duplex(4096); + let stream: BoundaryDuplexStream = Box::new(stream); + let handler = tokio::spawn(handle_mediated_connection( + tokio::io::BufReader::new(stream), + None, + None, + None, + None, + PolicyEngine::from(engine), + Arc::new(BinaryIdentityCache::new()), + Arc::new(AtomicU32::new(0)), + None, + None, + AgentProposals::new(false), + Arc::new(None), + Arc::new(None), + Arc::new(None), + None, + None, + None, + None, + None, + None, + )); workload - .write_all(b"GET /v1/policy/current HTTP/1.1\r\nHost: policy.local\r\nConnection: close\r\n\r\n") + .write_all(b"CONNECT openshell.local:443 HTTP/1.1\r\nHost: openshell.local:443\r\n\r\n") .await .unwrap(); let mut response = Vec::new(); @@ -10240,12 +10330,118 @@ process: { run_as_user: sandbox, run_as_group: sandbox } workload.read_to_end(&mut response), ) .await - .expect("policy.local response timed out") + .expect("door CONNECT response timed out") .unwrap(); handler.await.unwrap().unwrap(); let response = String::from_utf8(response).unwrap(); - assert!(response.starts_with("HTTP/1.1 200 "), "{response}"); - assert!(response.contains("\"format\":\"yaml\""), "{response}"); + assert!(response.starts_with("HTTP/1.1 400 "), "{response}"); + assert!( + response.contains("openshell.local is plain HTTP on port 80"), + "{response}" + ); + } + + /// Send one explicit-proxy request (no transparent open) and return the response. + async fn proxied_request(context: Option>, request: &[u8]) -> String { + let engine = Arc::new( + native_identity_engine( + include_str!("../data/sandbox-policy.rego"), + "network_policies: {}\n", + ) + .unwrap(), + ); + let (stream, mut workload) = tokio::io::duplex(4096); + let stream: BoundaryDuplexStream = Box::new(stream); + let handler = tokio::spawn(handle_mediated_connection( + tokio::io::BufReader::new(stream), + None, + None, + None, + None, + PolicyEngine::from(engine), + Arc::new(BinaryIdentityCache::new()), + Arc::new(AtomicU32::new(0)), + None, + context, + AgentProposals::new(false), + Arc::new(None), + Arc::new(None), + Arc::new(None), + None, + None, + None, + None, + None, + None, + )); + workload.write_all(request).await.unwrap(); + let mut response = Vec::new(); + tokio::time::timeout( + std::time::Duration::from_secs(5), + workload.read_to_end(&mut response), + ) + .await + .expect("proxied response timed out") + .unwrap(); + handler.await.unwrap().unwrap(); + String::from_utf8(response).unwrap() + } + + fn assert_complete_body(response: &str) { + let (head, body) = response.split_once("\r\n\r\n").expect("response head"); + let length: usize = head + .lines() + .find_map(|line| line.strip_prefix("Content-Length: ")) + .expect("Content-Length") + .parse() + .unwrap(); + assert_eq!(length, body.len(), "{response}"); + } + + #[tokio::test] + async fn a_proxied_post_reaches_the_gateway_door() { + const REQUEST: &[u8] = b"POST http://openshell.local/mcp HTTP/1.1\r\nHost: openshell.local\r\nContent-Length: 2\r\n\r\n{}"; + let (_workspace_tx, workspace_rx) = tokio::sync::watch::channel("default".to_string()); + let context = Arc::new(PolicyLocalContext::new( + None, + None, + None, + AgentProposals::new(false), + workspace_rx, + )); + // The door answers 503 because the test context has no gateway. + let door = proxied_request(Some(context), REQUEST).await; + assert!(door.starts_with("HTTP/1.1 503 "), "{door}"); + assert!(door.contains("no gateway connection"), "{door}"); + assert_complete_body(&door); + + let unconfigured = proxied_request(None, REQUEST).await; + assert!(unconfigured.starts_with("HTTP/1.1 503 "), "{unconfigured}"); + assert!( + unconfigured.ends_with("openshell.local is not configured"), + "{unconfigured}" + ); + assert_complete_body(&unconfigured); + } + + #[tokio::test] + async fn staged_open_reaches_the_gateway_door_only_by_its_host() { + // The test context has no gateway, so reaching the door answers 503. + let door = staged_sandbox_local_request( + sandbox_local_destination(), + b"POST /mcp HTTP/1.1\r\nHost: openshell.local\r\nContent-Length: 2\r\nConnection: close\r\n\r\n{}", + ) + .await; + assert!(door.starts_with("HTTP/1.1 503 "), "{door}"); + assert!(door.contains("no gateway connection"), "{door}"); + + // A rebound name on the same address is neither door. + let rebound = staged_sandbox_local_request( + sandbox_local_destination(), + b"POST /mcp HTTP/1.1\r\nHost: attacker.example\r\nContent-Length: 2\r\nConnection: close\r\n\r\n{}", + ) + .await; + assert!(rebound.starts_with("HTTP/1.1 400 "), "{rebound}"); } #[tokio::test] diff --git a/crates/openshell-tui/src/lib.rs b/crates/openshell-tui/src/lib.rs index c6464157a9..80b87eadae 100644 --- a/crates/openshell-tui/src/lib.rs +++ b/crates/openshell-tui/src/lib.rs @@ -1401,6 +1401,7 @@ fn spawn_create_sandbox( }; let req = openshell_core::proto::CreateSandboxRequest { + parent: String::new(), request_id: String::new(), name, spec: Some(openshell_core::proto::SandboxSpec { @@ -2587,6 +2588,7 @@ async fn fetch_sandboxes( page_size: 100, page_token, label_selector: String::new(), + parent: String::new(), workspace_scope: Some(list_workspace_scope(¤t_workspace, all_workspaces)), }; let result = tokio::time::timeout(Duration::from_secs(5), client.list_sandboxes(req)).await; diff --git a/docs/how-it-works/gateways/configuration.mdx b/docs/how-it-works/gateways/configuration.mdx index ae7fd229ec..b1bddb6725 100644 --- a/docs/how-it-works/gateways/configuration.mdx +++ b/docs/how-it-works/gateways/configuration.mdx @@ -377,6 +377,12 @@ provisioning_repair_window_seconds = 300 mutation_admission_limit_per_caller = 1000 mutation_replay_window_seconds = 86400 +# Experimental. Allow child sandboxes under a root sandbox and serve /mcp. +experimental_enable_child_sandboxes = false +# Experimental. Most children one parent may have at once; 0 allows none. +# At most 1000. +experimental_max_concurrent_children = 10 + # Reject invalid policy generations securely by default. Set # "retain_last_valid" only when availability takes priority. policy_validation_failure_mode = "fail_closed" @@ -887,6 +893,32 @@ password, node identity, or Azure CLI credentials. Check the gateway identity, federated subject, projected volume, and Entra connectivity when refresh fails; never print token files or token responses while diagnosing authentication. +## Child Sandboxes + +`[openshell.gateway] experimental_enable_child_sandboxes` defaults to `false`. +When it is `true`, a sandbox can be created as a child of a root sandbox, and +the gateway serves the MCP tools at `/mcp`. Turning it off blocks new children +and the MCP tools: agents in sandboxes and `openshell mcp serve` can no longer +reach any tool. Existing children keep running and can still be listed, used +and deleted from the CLI. They stop receiving their parent's policy changes, +but still lose providers their parent loses. A root can be deleted while it +still has children. Delete children before you turn the setting off. + +`experimental_max_concurrent_children` limits how many children one parent may have at +once. Every existing child counts, whatever its state, until it is deleted. +The default is 10, `0` allows none, and the gateway refuses to start with a +value above 1000. + +```toml +[openshell.gateway] +experimental_enable_child_sandboxes = true +experimental_max_concurrent_children = 10 +``` + +The gateway reads both settings at startup. Refer to +[Child Sandboxes](/how-it-works/sandboxes/child-sandboxes) for how children and +the MCP tools work. + ## Database Pool `[openshell.gateway] database_max_connections` sets the connection ceiling for the gateway's database pool. One pool is shared by every database-backed RPC, so this value is also the gateway's ceiling on concurrent database work. When the pool is saturated, callers queue on connection acquisition and sqlx logs that the time to acquire a connection exceeded its slow threshold. The background readiness monitor draws from the same pool, so sustained saturation can push its database ping past the check timeout and flip `/readyz` to not-ready while the gateway is otherwise serving. On Postgres, a caller that gets no connection within 5 seconds fails instead of waiting for the database to answer, usually with a retryable `UNAVAILABLE` error whose reason is `DATABASE_UNAVAILABLE`. diff --git a/docs/how-it-works/sandboxes/child-sandboxes.mdx b/docs/how-it-works/sandboxes/child-sandboxes.mdx new file mode 100644 index 0000000000..d839317b2f --- /dev/null +++ b/docs/how-it-works/sandboxes/child-sandboxes.mdx @@ -0,0 +1,142 @@ +--- +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +title: "Child Sandboxes" +sidebar-title: "Child Sandboxes" +slug: "how-it-works/sandboxes/child-sandboxes" +description: "Create sandboxes under a root sandbox, and let agents create and run sub-agents in them through MCP tools." +keywords: "OpenShell, Sandboxes, Child Sandboxes, Sub-agents, MCP" +--- + +A child sandbox is an ordinary sandbox created under a root sandbox. It always runs under its parent's policy and can use only its parent's providers. Agents use child sandboxes to run sub-agents, each in its own sandbox, through a small set of MCP tools. + + +Child sandboxes are experimental. A gateway operator enables them, and the MCP tools, with `experimental_enable_child_sandboxes`. Refer to [Gateway Configuration](/how-it-works/gateways/configuration#child-sandboxes). + + + +Delete child sandboxes before you roll back to a gateway version without them or run gateway replicas of different versions. An older gateway drops a child's link to its parent, and the child becomes a root for good. + + +## Roots and Children + +A sandbox created without a parent is a root. A sandbox created with a parent is a child. Only a root can be a parent, so trees are one level deep: a child cannot have children of its own. Apart from the rules on this page, a child behaves like any other sandbox, with the same lifecycle and commands. + +## Create and List Children + +Create a child with `--parent` and the name of a root in the same workspace. Every other `sandbox create` option works as usual, except `--policy`. + +```shell +openshell sandbox create --name lead --from codex-agent:local --provider openai --provider anthropic +openshell sandbox create --name reviewer --parent lead --from claude-agent:local --provider anthropic +``` + +The gateway refuses a child of a child with `only one level of child sandboxes is supported`. When a root already has as many children as the gateway's `experimental_max_concurrent_children` allows, it refuses with `sandbox 'lead' has reached its limit of 10 children`. Every child counts whatever its state, and keeps its slot until its delete finishes. While one is still being deleted, the refusal says so and you can retry shortly. + +`sandbox list` adds a `PARENT` column when the page holds a child. A root shows `-`, and a child whose parent no longer exists shows `deleted ()`. List one root's children with `--parent`: + +```shell +openshell sandbox list --parent lead +``` + +## Policy + +A child always uses its parent's policy. When it is created, the gateway copies the parent's latest policy into the child. When the parent's policy changes, the gateway copies the new version into each child at the same time and delivers it to the parent and the children as it delivers any policy update. It does not wait for the parent to load the policy first. A copy that fails is made again within about 30 seconds. + +While a global policy is set, every sandbox runs it, children included. A root created without `--policy` under a global policy has no policy of its own, so its children start without one too. After the global policy is deleted, the root and its children block all network traffic until the root gets its own policy, when it restarts or through `openshell policy set`. The gateway then copies that policy into the children. + +You cannot give a child a policy of its own or change its policy. `sandbox create --parent` refuses `--policy` with `child sandboxes use their parent's policy; omit --policy`, and ignores `OPENSHELL_SANDBOX_POLICY` with a note. Policy updates, approvals and proposals for a child are refused. To change what a child can do, change its parent's policy. + +The parent's policy names the parent's filesystem paths, program paths and process user. A child that runs a different image, from `--from` or a template, needs the same user and folder layout as its parent's image. Paths the child's image lacks are skipped, which only removes access, so a child with a different layout can fail to start or find its programs denied. Read the child's startup errors and denials with `openshell logs` or the MCP `logs` tool. + +Each sandbox loads its policy on its own and handles a failure through the gateway's policy failure mode. A parent that rejects a policy does not affect its children. + +The parent and its children can run different policy versions for a while: until a copy is delivered, or, when the parent rejects a version its children loaded, until the parent loads a later one. If the parent rejects a version that grants more access, its children keep that access, even while the parent is blocked under `fail_closed`. This is tracked in [#6091](https://github.com/ai-openshell/openshell/issues/6091). + +## Providers + +A child can use only providers attached to its parent. Without `--provider`, a child gets all of its parent's providers. With `--provider`, it gets the ones you name, and naming one the parent does not have is refused with `provider 'github' is not attached to parent 'lead'`. + +When a provider is detached from the parent, every child stops receiving it at its next configuration update, and the gateway detaches it from the child too. A provider later attached to the parent reaches only children created after that. + +## Delete a Parent + +The gateway refuses to delete a root that still has children: + +```shell +openshell sandbox delete lead +``` + +```text +sandbox 'lead' has 3 child sandboxes; delete them first +``` + +Delete the children, then the parent: + +```shell +openshell sandbox delete reviewer coder helper +openshell sandbox delete lead +``` + +A child still counts until its delete finishes. Until then the gateway refuses the root with `sandbox 'lead' has 1 child sandbox still being deleted; try again once they are gone`, so run the delete again. `sandbox delete --all` deletes children first and waits up to two minutes for them before it deletes their root. If a child's delete is stuck, the root stays until the child is gone. + +A child's results live only inside the child, so this keeps one command from deleting work nobody has collected. If a child's parent record is gone, for example after a failure, the child keeps its last policy and loses all its providers. Delete it. + +## MCP Tools + +The gateway serves MCP tools at `/mcp` that create and manage sandboxes. Each tool call runs as the matching sandbox RPC, with the same authorization and gateway interceptors as a CLI call. The tools are experimental: their names, arguments and results may change between releases. `tools/list` describes each tool's arguments and results for the caller, a user or a sandbox. + +| Tool | What it does | +|---|---| +| `create_sandbox` | Create a sandbox and wait until it is ready, up to 45 seconds. If it is not ready by then, the tool returns its current state with `timed_out: true`, not an error; call it again with the same name to keep waiting. Calling it again returns the existing sandbox with `already_existed: true`. | +| `list` | List sandboxes and their state. | +| `exec` | Run a command and return its exit code and output. | +| `delete` | Delete a sandbox. | +| `logs` | Read a sandbox's own log lines, such as startup errors and policy denials. | + +### From Inside a Root Sandbox + +An agent in a root sandbox calls `http://openshell.local/mcp`. The sandbox's supervisor attaches the sandbox's credential, so the agent holds no token. A sandbox acts only on its own children: + +- `create_sandbox` takes a `name`, and optionally a `template` and `providers`. Without a template, the child copies the root's image, CPU and memory, but not a GPU or other device. With a template, the child gets the template's resources, including a GPU the template requests. A template must carry the label `openshell.ai/agent-usable: "true"` and have no driver configuration. The root's MCP tool list names the templates it may use, with their images, so the agent does not need to be told them. Either way, the child gets the root's runtime class and user namespace setting. Without `providers`, the child gets all of the root's. +- A root created with driver configuration cannot create children through MCP. +- `list`, `exec`, `delete` and `logs` act only on the root's children. Any other name reads as not found. +- The root's network policy does not apply to `openshell.local/mcp`. Any process in the root can call it, even when the policy denies all other traffic or the root is blocked under `fail_closed`. +- A sandbox can have 8 requests to `openshell.local/mcp` open at once. Another one gets `503` with `too many gateway requests at once; try again`. +- The root can create children only while the user who created it is a member of the workspace with at least the user role. A platform admin who is not a member must be added with `openshell workspace member add`. A gateway with no admin role configured treats every authenticated user as an admin and skips this check. A child the root creates records the root as its creator, as `sandbox:`; a child you create with `--parent` records you. + +### From the Host + +`openshell mcp serve` runs a local MCP server over stdio that forwards each call to the active gateway with your CLI login. It uses the same connection and login as the CLI, including mTLS client certificates, and it refreshes an OIDC login for as long as it runs. Add it to your MCP client's configuration: + +```json +{"mcpServers": {"openshell": {"command": "openshell", "args": ["mcp", "serve"]}}} +``` + +The tools act in the CLI's workspace. To use another workspace, add `"--workspace", "team"` to `args`. Through `openshell mcp serve` you can act on any sandbox the CLI lets you act on. `create_sandbox` takes `name`, `parent`, `image` and `providers`; use the CLI for other create options. The gateway refuses any `/mcp` request that a browser sends, so a web page cannot use your login. + +### Run Long Work + +The gateway has no background jobs. An agent starts long work detached inside the sandbox and collects it with later `exec` calls. The `exec` tool's description gives the agent a short example. Weaker models may need the full steps below in their instructions. + +- `exec` waits up to 30 seconds by default and 45 at most. A command that reaches its timeout is reported as timed out but can keep running in the sandbox. Deleting the sandbox stops it. +- For longer work, such as running a harness, start the command in its own session with its output in files, and write its exit code to a file when it ends. +- To wait, run a short loop with `exec` that checks for the exit code file, at most 25 seconds per call, and repeat it until the file exists. +- Read the output with `tail` or `grep`. Each `exec` reply keeps the first and last 16 KiB of each output stream. +- The files need a writable `/tmp`. A child uses its parent's filesystem policy, so the parent's policy must let `/tmp` be written. The default policy does. +- Nothing stops a second long command in the same sandbox. Use one child for each piece of parallel work. + +```text +exec {name: "reviewer", command: ["sh", "-c", "mkdir -p /tmp/jobs/review || exit 1; setsid sh -c 'claude -p \"Review the diff\" > /tmp/jobs/review/out 2> /tmp/jobs/review/err; echo $? > /tmp/jobs/review/exit.tmp; mv /tmp/jobs/review/exit.tmp /tmp/jobs/review/exit' < /dev/null > /dev/null 2>&1 &"]} +→ exit 0 +exec {name: "reviewer", command: ["sh", "-c", "for i in $(seq 25); do [ -f /tmp/jobs/review/exit ] && break; sleep 1; done; cat /tmp/jobs/review/exit 2>/dev/null || echo running"]} +→ running, then 0 +exec {name: "reviewer", command: ["tail", "/tmp/jobs/review/out"]} +→ the review +delete {name: "reviewer"} +``` + +## Next Steps + +- [Gateway Configuration](/how-it-works/gateways/configuration#child-sandboxes) covers the settings that enable child sandboxes and limit them. +- [Sandbox Templates](/how-it-works/sandboxes/templates) covers creating the templates agents can use. diff --git a/docs/how-it-works/sandboxes/templates.mdx b/docs/how-it-works/sandboxes/templates.mdx index e8f895e504..194f1c4d46 100644 --- a/docs/how-it-works/sandboxes/templates.mdx +++ b/docs/how-it-works/sandboxes/templates.mdx @@ -45,6 +45,18 @@ openshell sandbox create --template gpu-kata --provider github -- claude The `--template` flag cannot be combined with inline workload flags such as `--from`, `--cpu`, `--memory`, `--gpu`, `--env`, or `--driver-config-json`. Put those values on the template instead. Create-time policy and provider attachments remain part of the sandbox request, so each sandbox can keep its own access boundary. +## Make a Template Available to Agents + +An agent in a root sandbox can create [child sandboxes](/how-it-works/sandboxes/child-sandboxes) from a template only when the template carries the `openshell.ai/agent-usable` label and has no driver configuration: + +```shell +openshell sandbox template create codex-agent \ + --image registry.example.com/codex:latest \ + --label openshell.ai/agent-usable=true +``` + +The agent's MCP tool list names these templates, with their images, so you do not need to tell the agent which ones exist. It never shows their environment values. A child created from a template still uses its parent's policy, so the parent's policy must allow the programs and hosts the template's image needs. + ## Manage Templates ```shell diff --git a/docs/index.yml b/docs/index.yml index d40522246e..67e980b934 100644 --- a/docs/index.yml +++ b/docs/index.yml @@ -42,6 +42,8 @@ navigation: path: how-it-works/sandboxes/overview.mdx - page: "Templates" path: how-it-works/sandboxes/templates.mdx + - page: "Child Sandboxes" + path: how-it-works/sandboxes/child-sandboxes.mdx - page: "Runtimes" path: how-it-works/sandboxes/runtimes.mdx - section: "Providers" diff --git a/e2e/rust/Cargo.toml b/e2e/rust/Cargo.toml index 3eb0112a95..c897c04c33 100644 --- a/e2e/rust/Cargo.toml +++ b/e2e/rust/Cargo.toml @@ -27,6 +27,8 @@ e2e = [] e2e-host-gateway = ["e2e"] e2e-local-container-driver = ["e2e"] e2e-additional-ca = ["e2e", "e2e-host-gateway"] +# Selects tests that need child sandboxes and /mcp enabled on the gateway. +e2e-child-sandboxes = ["e2e", "e2e-host-gateway"] e2e-docker = ["e2e", "e2e-host-gateway", "e2e-local-container-driver"] e2e-gpu = ["e2e"] e2e-docker-gpu = ["e2e-docker", "e2e-gpu"] @@ -76,6 +78,11 @@ name = "vm_bind_mount" path = "tests/vm_bind_mount.rs" required-features = ["e2e-vm"] +[[test]] +name = "child_sandboxes" +path = "tests/child_sandboxes.rs" +required-features = ["e2e-child-sandboxes"] + [[test]] name = "additional_ca" path = "tests/additional_ca.rs" diff --git a/e2e/rust/tests/child_sandboxes.rs b/e2e/rust/tests/child_sandboxes.rs new file mode 100644 index 0000000000..927e3d7904 --- /dev/null +++ b/e2e/rust/tests/child_sandboxes.rs @@ -0,0 +1,688 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +#![cfg(feature = "e2e-child-sandboxes")] + +//! E2E tests for child sandboxes and the MCP tools (RFC 0021). +//! +//! Needs a gateway with `experimental_enable_child_sandboxes` on. Run with +//! `mise run e2e:rust:child-sandboxes`, which sets +//! `OPENSHELL_E2E_CHILD_SANDBOXES=1` for the Docker gateway wrapper. Each test +//! shares one root, since every sandbox start is slow. Sandboxes are deleted +//! by guards, children before their roots, even when a test fails. + +use std::io::Write as _; +use std::process::Stdio; +use std::time::Duration; + +use openshell_e2e::harness::binary::openshell_cmd; +use openshell_e2e::harness::output::strip_ansi; +use openshell_e2e::harness::sandbox::SandboxGuard; +use serde_json::{Value, json}; +use tempfile::NamedTempFile; +use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader}; +use tokio::net::TcpListener; + +const TEST_SERVER_HOST: &str = "host.openshell.internal"; +const PRIVATE_ALLOWED_IPS: &str = r#" allowed_ips: + - "10.0.0.0/8" + - "172.0.0.0/8" + - "192.168.0.0/16" + - "fc00::/7""#; + +async fn cli(args: &[&str]) -> (String, bool) { + let output = openshell_cmd() + .args(args) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .output() + .await + .expect("spawn openshell"); + let text = format!( + "{}{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + (strip_ansi(&text), output.status.success()) +} + +/// A policy that lets any binary reach the host test server on `allow_port`, +/// or nothing when `None`. `/tmp` is writable. +fn policy(allow_port: Option) -> NamedTempFile { + let network = allow_port.map_or_else(String::new, |port| { + format!( + r#"network_policies: + host_server: + name: host_server + endpoints: + - host: {TEST_SERVER_HOST} + port: {port} +{PRIVATE_ALLOWED_IPS} + binaries: + - path: "/**" +"# + ) + }); + let text = format!( + r"version: 1 + +filesystem_policy: + include_workdir: true + read_only: + - /usr + - /lib + - /proc + - /dev/urandom + - /app + - /etc + - /var/log + read_write: + - /sandbox + - /tmp + - /dev/null + +landlock: + compatibility: best_effort + +process: + run_as_user: sandbox + run_as_group: sandbox + +{network}" + ); + let mut file = NamedTempFile::new().expect("create policy file"); + file.write_all(text.as_bytes()).expect("write policy file"); + file.flush().expect("flush policy file"); + file +} + +fn path(file: &NamedTempFile) -> String { + file.path().to_string_lossy().into_owned() +} + +/// An HTTP server on the host that answers every request with 200. +async fn start_host_server() -> u16 { + let listener = TcpListener::bind(("0.0.0.0", 0)) + .await + .expect("bind host server"); + let port = listener.local_addr().expect("host server address").port(); + tokio::spawn(async move { + while let Ok((mut stream, _)) = listener.accept().await { + tokio::spawn(async move { + let mut request = Vec::new(); + let mut buf = [0_u8; 1024]; + while !request.windows(4).any(|w| w == b"\r\n\r\n") { + match stream.read(&mut buf).await { + Ok(0) | Err(_) => return, + Ok(n) => request.extend_from_slice(&buf[..n]), + } + } + let _ = stream + .write_all( + b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok", + ) + .await; + }); + } + }); + port +} + +/// The HTTP status a request from inside `sandbox` to the host server gets: +/// 200 when its policy allows it; anything else, such as `000` for a refused +/// connection, when not. +async fn probe(sandbox: &SandboxGuard, port: u16) -> String { + let script = format!( + "curl -s -o /dev/null -w '%{{http_code}}' --max-time 10 http://{TEST_SERVER_HOST}:{port}/; true" + ); + let output = sandbox + .exec(&["sh", "-c", &script]) + .await + .unwrap_or_else(|error| panic!("probe exec in {} failed: {error}", sandbox.name)); + output.trim().to_string() +} + +/// Probe until the host server is reachable or not, as `reachable` says, for +/// at most a minute: a parent's policy reaches its children a few seconds +/// after the parent loads it. +async fn probe_until(sandbox: &SandboxGuard, port: u16, reachable: bool) { + let mut last = String::new(); + for _ in 0..30 { + last = probe(sandbox, port).await; + if (last == "200") == reachable { + return; + } + tokio::time::sleep(Duration::from_secs(2)).await; + } + panic!( + "{} never became {} the host server; last answer {last}", + sandbox.name, + if reachable { + "able to reach" + } else { + "unable to reach" + } + ); +} + +/// Make the CLI's user a member of the default workspace, so roots it +/// creates can create children through MCP. A local development gateway's +/// built-in user needs no membership. +async fn ensure_workspace_member() { + let (whoami, ok) = cli(&["whoami", "-o", "json"]).await; + assert!(ok, "whoami failed: {whoami}"); + let identity: Value = serde_json::from_str(whoami.trim()).expect("whoami JSON"); + if identity["identity_provider"] == "local_dev" { + return; + } + let subject = identity["subject"].as_str().expect("whoami subject"); + // An existing membership is fine. + let _ = cli(&[ + "workspace", + "member", + "add", + "--workspace", + "default", + "--subject", + subject, + "--role", + "user", + ]) + .await; +} + +/// Call one MCP tool from inside `root`, through `http://openshell.local/mcp`, +/// and return the tool result (`structuredContent` and `isError`). +async fn mcp(root: &SandboxGuard, tool: &str, arguments: Value) -> Value { + mcp_request( + root, + "tools/call", + json!({"name": tool, "arguments": arguments}), + ) + .await["result"] + .clone() +} + +/// Send one JSON-RPC request from inside `root` to `http://openshell.local/mcp` +/// and return the whole reply. +async fn mcp_request(root: &SandboxGuard, method: &str, params: Value) -> Value { + let body = json!({"jsonrpc": "2.0", "id": 1, "method": method, "params": params}).to_string(); + let output = root + .exec(&[ + "curl", + "-s", + "--max-time", + "90", + "-X", + "POST", + "http://openshell.local/mcp", + "-H", + "content-type: application/json", + "-d", + &body, + ]) + .await + .unwrap_or_else(|error| panic!("MCP {method} failed: {error}")); + let reply = output + .lines() + .rev() + .find(|line| line.trim_start().starts_with('{')) + .unwrap_or_else(|| panic!("no JSON reply to {method}: {output}")); + serde_json::from_str(reply).expect("MCP reply JSON") +} + +fn content(result: &Value) -> &Value { + &result["structuredContent"] +} + +/// Deletes a provider when dropped, also when a test fails halfway. +struct ProviderGuard(String); + +impl Drop for ProviderGuard { + fn drop(&mut self) { + let _ = std::process::Command::new(openshell_e2e::harness::binary::openshell_bin()) + .args(["provider", "delete", &self.0]) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status(); + } +} + +#[tokio::test] +async fn children_are_created_listed_and_deleted_from_the_cli() { + let mut root = SandboxGuard::create(&[]).await.expect("create root"); + let mut child = SandboxGuard::create(&["--parent", &root.name]) + .await + .expect("create child"); + + let grandchild = SandboxGuard::create(&["--parent", &child.name]).await; + let error = grandchild.err().expect("a child of a child is refused"); + assert!( + error.contains("only one level of child sandboxes is supported"), + "{error}" + ); + + let (listed, ok) = cli(&["sandbox", "list", "--parent", &root.name]).await; + assert!(ok, "{listed}"); + assert!(listed.contains(&child.name), "{listed}"); + assert!( + !listed + .lines() + .any(|line| line.starts_with(&format!("{} ", root.name))), + "only children are listed: {listed}" + ); + let (all, ok) = cli(&["sandbox", "list"]).await; + assert!(ok && all.contains("PARENT"), "{all}"); + + let (refused, ok) = cli(&["sandbox", "delete", &root.name]).await; + assert!(!ok, "deleting a parent with a child must fail: {refused}"); + assert!( + refused.contains(&format!( + "sandbox '{}' has 1 child sandbox; delete them first", + root.name + )), + "{refused}" + ); + + child.delete().await.expect("delete child"); + // The root is refused until the child's delete finishes. + let mut deleted = root.delete().await; + for _ in 0..60 { + match &deleted { + Err(refused) if refused.contains("still being deleted") => { + tokio::time::sleep(std::time::Duration::from_secs(1)).await; + deleted = root.delete().await; + } + _ => break, + } + } + deleted.expect("delete parent"); +} + +#[tokio::test] +async fn a_child_follows_its_parents_policy_on_the_network() { + let port = start_host_server().await; + let closed = policy(None); + let open = policy(Some(port)); + let root = SandboxGuard::create(&["--policy", &path(&closed)]) + .await + .expect("create root"); + let child = SandboxGuard::create(&["--parent", &root.name]) + .await + .expect("create child"); + + assert_ne!(probe(&child, port).await, "200", "the child starts closed"); + + let (set, ok) = cli(&[ + "policy", + "set", + &root.name, + "--policy", + &path(&open), + "--wait", + ]) + .await; + assert!(ok, "policy set on the root failed: {set}"); + assert_eq!(probe(&root, port).await, "200", "the root is open"); + probe_until(&child, port, true).await; + + let (set, ok) = cli(&[ + "policy", + "set", + &root.name, + "--policy", + &path(&closed), + "--wait", + ]) + .await; + assert!(ok, "closing the root failed: {set}"); + probe_until(&child, port, false).await; + + drop(child); + drop(root); +} + +#[tokio::test] +async fn a_child_loses_a_provider_its_parent_loses() { + let provider = format!("e2e-child-provider-{}", std::process::id()); + // Any provider type the gateway has a profile for will do. + let (profiles, _) = cli(&["provider", "profile", "list"]).await; + let (provider_type, key) = [ + ("openai", "OPENAI_API_KEY"), + ("anthropic", "ANTHROPIC_API_KEY"), + ] + .into_iter() + .find(|(name, _)| { + profiles + .lines() + .any(|line| line.starts_with(&format!("{name} "))) + }) + .unwrap_or(("openai", "OPENAI_API_KEY")); + let credential = format!("{key}=sk-e2e-child-sandboxes"); + let (created, ok) = cli(&[ + "provider", + "create", + "--name", + &provider, + "--type", + provider_type, + "--credential", + &credential, + ]) + .await; + assert!(ok, "provider create failed: {created}"); + // Declared before the sandboxes, so it is dropped after them. + let _provider_guard = ProviderGuard(provider.clone()); + + let root = SandboxGuard::create(&["--provider", &provider]) + .await + .expect("create root"); + let child = SandboxGuard::create(&["--parent", &root.name]) + .await + .expect("create child"); + let (listed, ok) = cli(&["sandbox", "provider", "list", &child.name]).await; + assert!( + ok && listed.contains(&provider), + "child has the provider: {listed}" + ); + + let (detached, ok) = cli(&["sandbox", "provider", "detach", &root.name, &provider]).await; + assert!(ok, "detach from the root failed: {detached}"); + let (listed, ok) = cli(&["sandbox", "provider", "list", &child.name]).await; + assert!( + ok && !listed.contains(&provider), + "child lost the provider: {listed}" + ); + + drop(child); + drop(root); +} + +#[tokio::test] +async fn an_agent_in_a_root_manages_its_children_through_mcp() { + ensure_workspace_member().await; + let root = SandboxGuard::create(&[]).await.expect("create root"); + let other_root = SandboxGuard::create(&[]).await.expect("create other root"); + let worker = format!("{}-w", root.name); + + let created = mcp(&root, "create_sandbox", json!({"name": worker})).await; + // Dropped before the roots, so a failed test still deletes the child + // first and then its root. + let _worker_guard = SandboxGuard::manage_existing(worker.clone()); + assert_eq!(created["isError"], false, "{created}"); + assert_eq!(content(&created)["already_existed"], false, "{created}"); + let again = mcp(&root, "create_sandbox", json!({"name": worker})).await; + assert_eq!(content(&again)["already_existed"], true, "{again}"); + + let ran = mcp( + &root, + "exec", + json!({"name": worker, "command": ["sh", "-c", "echo hello; exit 3"]}), + ) + .await; + assert_eq!(content(&ran)["exit_code"], 3, "{ran}"); + assert_eq!(content(&ran)["stdout"], "hello\n", "{ran}"); + + // Long work is started detached, as the exec tool's text describes, and + // outlives the exec that started it. + let start = "mkdir -p /tmp/jobs/t1 || exit 1; setsid sh -c 'sleep 5; echo done > /tmp/jobs/t1/out \ + 2> /tmp/jobs/t1/err; echo $? > /tmp/jobs/t1/exit.tmp; mv /tmp/jobs/t1/exit.tmp \ + /tmp/jobs/t1/exit' < /dev/null > /dev/null 2>&1 &"; + let started = mcp( + &root, + "exec", + json!({"name": worker, "command": ["sh", "-c", start]}), + ) + .await; + assert_eq!(content(&started)["exit_code"], 0, "{started}"); + let check = "[ -d /tmp/jobs/t1 ] || { echo no such job; exit 0; }; for i in $(seq 25); do \ + [ -f /tmp/jobs/t1/exit ] && break; sleep 1; done; cat /tmp/jobs/t1/exit 2>/dev/null \ + || echo running"; + let waited = mcp( + &root, + "exec", + json!({"name": worker, "command": ["sh", "-c", check]}), + ) + .await; + assert_eq!(content(&waited)["stdout"], "0\n", "{waited}"); + let output = mcp( + &root, + "exec", + json!({"name": worker, "command": ["cat", "/tmp/jobs/t1/out"]}), + ) + .await; + assert_eq!(content(&output)["stdout"], "done\n", "{output}"); + + // Another root, and the caller itself, read as missing. + for name in [other_root.name.as_str(), root.name.as_str()] { + let refused = mcp(&root, "exec", json!({"name": name, "command": ["true"]})).await; + assert_eq!(content(&refused)["error"], "not_found", "{refused}"); + } + + assert_exec_audit_event(&worker); + + let deleted = mcp(&root, "delete", json!({"name": worker})).await; + assert_eq!(content(&deleted)["deleting"], true, "{deleted}"); +} + +/// The gateway writes an OCSF event for an exec in the child. The e2e wrapper +/// always writes the gateway's JSONL, so under it a missing directory fails +/// the test; against a gateway started by hand the check is skipped. +fn assert_exec_audit_event(worker: &str) { + let Ok(dir) = std::env::var("OPENSHELL_E2E_GATEWAY_OCSF_DIR") else { + assert_ne!( + std::env::var("OPENSHELL_E2E_CHILD_SANDBOXES").as_deref(), + Ok("1"), + "the e2e wrapper ran but OPENSHELL_E2E_GATEWAY_OCSF_DIR is not set" + ); + eprintln!("skipping the audit check: OPENSHELL_E2E_GATEWAY_OCSF_DIR is not set"); + return; + }; + let mut events = Vec::new(); + for entry in std::fs::read_dir(&dir).expect("read the gateway OCSF dir") { + let text = + std::fs::read_to_string(entry.expect("OCSF dir entry").path()).unwrap_or_default(); + events.extend( + text.lines() + .filter_map(|line| serde_json::from_str::(line).ok()), + ); + } + assert!( + events + .iter() + .any(|event| event["api"]["operation"] == "exec" + && event["unmapped"]["target"] == worker + && event["unmapped"]["exit_code"] == "3"), + "no exec event with exit code 3 for {worker}" + ); +} + +/// Deletes a sandbox template when dropped, also when a test fails halfway. +struct TemplateGuard(String); + +impl Drop for TemplateGuard { + fn drop(&mut self) { + let _ = std::process::Command::new(openshell_e2e::harness::binary::openshell_bin()) + .args(["sandbox", "template", "delete", &self.0]) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status(); + } +} + +/// Create a template whose sandboxes get `E2E_TEMPLATE_MARK=`, labelled +/// for agents when `agent_usable` is true. +async fn create_template(name: &str, mark: &str, agent_usable: bool) -> TemplateGuard { + let env = format!("E2E_TEMPLATE_MARK={mark}"); + let mut args = vec!["sandbox", "template", "create", name, "--env", &env]; + if agent_usable { + args.extend(["--label", "openshell.ai/agent-usable=true"]); + } + let (created, ok) = cli(&args).await; + assert!(ok, "template create {name} failed: {created}"); + TemplateGuard(name.to_string()) +} + +#[tokio::test] +async fn an_agent_creates_children_only_from_templates_marked_for_agents() { + ensure_workspace_member().await; + let id = std::process::id(); + let approved = format!("e2e-agent-tpl-{id}"); + let unlabelled = format!("e2e-plain-tpl-{id}"); + let mark = format!("from-template-{id}"); + // Declared before the sandboxes, so they are dropped after them. + let _approved_guard = create_template(&approved, &mark, true).await; + let _unlabelled_guard = create_template(&unlabelled, &mark, false).await; + + let root = SandboxGuard::create(&[]).await.expect("create root"); + + // The agent learns the templates it may use from the tool list. + let tools = mcp_request(&root, "tools/list", json!({})).await; + let create = tools["result"]["tools"] + .as_array() + .and_then(|tools| tools.iter().find(|tool| tool["name"] == "create_sandbox")) + .unwrap_or_else(|| panic!("no create_sandbox tool: {tools}")); + let offered = &create["inputSchema"]["properties"]["template"]["enum"]; + assert!( + offered.as_array().is_some_and( + |names| names.contains(&json!(approved)) && !names.contains(&json!(unlabelled)) + ), + "{create}" + ); + + let worker = format!("{}-t", root.name); + let created = mcp( + &root, + "create_sandbox", + json!({"name": worker, "template": approved}), + ) + .await; + let _worker_guard = SandboxGuard::manage_existing(worker.clone()); + assert_eq!(created["isError"], false, "{created}"); + + // The child runs with the template's settings, not a copy of its parent's. + let ran = mcp( + &root, + "exec", + json!({"name": worker, "command": ["sh", "-c", "printf %s \"$E2E_TEMPLATE_MARK\""]}), + ) + .await; + assert_eq!(content(&ran)["exit_code"], 0, "{ran}"); + assert_eq!(content(&ran)["stdout"], mark, "{ran}"); + + // An unlabelled template and a missing one get the same answer, so an + // agent cannot learn which templates exist. + let missing = format!("e2e-missing-tpl-{id}"); + for template in [&unlabelled, &missing] { + let refused = mcp( + &root, + "create_sandbox", + json!({"name": format!("{}-x", root.name), "template": template}), + ) + .await; + assert_eq!(refused["isError"], true, "{refused}"); + assert_eq!( + content(&refused)["message"], + format!("template '{template}' is not available to agents"), + "{refused}" + ); + } +} + +/// Talk to `openshell mcp serve` over stdio, as a host MCP client does. +struct Bridge { + child: tokio::process::Child, + stdin: tokio::process::ChildStdin, + stdout: tokio::io::Lines>, + next_id: u64, +} + +impl Bridge { + fn start(command: tokio::process::Command) -> Self { + let mut command = command; + command + .args(["mcp", "serve"]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::inherit()) + .kill_on_drop(true); + let mut child = command.spawn().expect("spawn openshell mcp serve"); + let stdin = child.stdin.take().expect("bridge stdin"); + let stdout = BufReader::new(child.stdout.take().expect("bridge stdout")).lines(); + Self { + child, + stdin, + stdout, + next_id: 0, + } + } + + async fn call(&mut self, method: &str, params: Value) -> Value { + self.next_id += 1; + let line = + json!({"jsonrpc": "2.0", "id": self.next_id, "method": method, "params": params}); + self.stdin + .write_all(format!("{line}\n").as_bytes()) + .await + .expect("write to the bridge"); + let reply = tokio::time::timeout(Duration::from_mins(2), self.stdout.next_line()) + .await + .expect("the bridge answers") + .expect("read from the bridge") + .expect("the bridge is still running"); + serde_json::from_str(&reply).unwrap_or_else(|_| panic!("not JSON-RPC: {reply}")) + } + + async fn tool(&mut self, name: &str, arguments: Value) -> Value { + self.call("tools/call", json!({"name": name, "arguments": arguments})) + .await["result"] + .clone() + } +} + +#[tokio::test] +async fn a_host_client_uses_the_tools_through_mcp_serve() { + let mut bridge = Bridge::start(openshell_cmd()); + let init = bridge + .call("initialize", json!({"protocolVersion": "2025-06-18"})) + .await; + assert_eq!(init["result"]["protocolVersion"], "2025-06-18", "{init}"); + + let name = format!("e2e-bridge-{}", std::process::id()); + let created = bridge.tool("create_sandbox", json!({"name": name})).await; + let guard = SandboxGuard::manage_existing(name.clone()); + assert_eq!(created["isError"], false, "{created}"); + + let mut ran = Value::Null; + // A sandbox still starting is reported as such; wait for it. + for _ in 0..12 { + ran = bridge + .tool( + "exec", + json!({"name": name, "command": ["echo", "from the host"]}), + ) + .await; + if content(&ran)["exit_code"] == 0 { + break; + } + tokio::time::sleep(Duration::from_secs(5)).await; + } + assert_eq!(content(&ran)["stdout"], "from the host\n", "{ran}"); + + let refused = bridge + .tool( + "exec", + json!({"name": name, "command": ["true"], "env": {"A": "1"}}), + ) + .await; + assert_eq!( + content(&refused)["message"], + "'env' is not available over MCP; users can set it with the CLI", + "{refused}" + ); + + drop(bridge.stdin); + let _ = bridge.child.wait().await; + drop(guard); +} diff --git a/e2e/rust/tests/edge_tunnel_e2e.rs b/e2e/rust/tests/edge_tunnel_e2e.rs index 80ee4a6ed8..8dd413a9bc 100644 --- a/e2e/rust/tests/edge_tunnel_e2e.rs +++ b/e2e/rust/tests/edge_tunnel_e2e.rs @@ -139,8 +139,9 @@ async fn gateway_status_reports_healthy() { /// /// Note: The dummy token won't be validated (no edge auth middleware on /// the plaintext gateway), but it triggers the CLI's tunnel proxy codepath. -#[tokio::test] -async fn ws_tunnel_status_through_edge_proxy() { +/// The live gateway's endpoint when it is healthy and plaintext, which the +/// edge tunnel tests need; otherwise say why the test is skipped. +async fn plaintext_gateway_endpoint(test: &str) -> Option { let (original_status, _) = run_cli(&["status"]).await; let clean_status = strip_ansi(&original_status); @@ -150,8 +151,8 @@ async fn ws_tunnel_status_through_edge_proxy() { && !clean_status.to_lowercase().contains("connected") && !clean_status.contains("✓") { - eprintln!("Skipping ws_tunnel test: no healthy gateway available"); - return; + eprintln!("Skipping {test}: no healthy gateway available"); + return None; } // Get the gateway endpoint from the gateway metadata. @@ -163,7 +164,8 @@ async fn ws_tunnel_status_through_edge_proxy() { // Extract the gateway endpoint from the info output. // The format varies, but it should contain a URL-like string. let endpoint = info_clean.lines().find_map(|line| { - if line.to_lowercase().contains("endpoint") || line.to_lowercase().contains("gateway") { + let lower = line.to_lowercase(); + if lower.contains("endpoint") || lower.contains("gateway") || lower.contains("server") { // Try to extract a URL from the line line.split_whitespace() .find(|word| word.starts_with("http://") || word.starts_with("https://")) @@ -174,10 +176,8 @@ async fn ws_tunnel_status_through_edge_proxy() { }); let Some(endpoint) = endpoint else { - eprintln!( - "Skipping ws_tunnel test: could not extract gateway endpoint from:\n{info_clean}" - ); - return; + eprintln!("Skipping {test}: could not extract gateway endpoint from:\n{info_clean}"); + return None; }; // For the WS tunnel test, we need the endpoint to be HTTP (plaintext). @@ -185,11 +185,19 @@ async fn ws_tunnel_status_through_edge_proxy() { // complicates things. Skip if the gateway isn't plaintext. if !endpoint.starts_with("http://") { eprintln!( - "Skipping ws_tunnel test: gateway endpoint is not plaintext HTTP: {endpoint}\n\ + "Skipping {test}: gateway endpoint is not plaintext HTTP: {endpoint}\n\ Use a plaintext local gateway such as `mise run gateway:docker` for this test." ); - return; + return None; } + Some(endpoint) +} + +#[tokio::test] +async fn ws_tunnel_status_through_edge_proxy() { + let Some(endpoint) = plaintext_gateway_endpoint("ws_tunnel test").await else { + return; + }; // Seed a temporary config directory with edge auth metadata pointing at // the live gateway. The dummy token triggers the WS tunnel codepath @@ -218,3 +226,81 @@ async fn ws_tunnel_status_through_edge_proxy() { "status through WS tunnel should report healthy:\n{clean}" ); } + +// ------------------------------------------------------------------- +// MCP through the WS tunnel proxy +// ------------------------------------------------------------------- + +/// `openshell mcp serve` sends MCP over the same connection as the CLI's +/// gRPC calls, so with edge auth it goes through the WebSocket tunnel. Needs +/// a plaintext gateway with child sandboxes, and so `/mcp`, enabled. No CI +/// gateway is plaintext, so it is ignored unless run by hand: +/// `OPENSHELL_E2E_CHILD_SANDBOXES=1 cargo test --manifest-path e2e/rust/Cargo.toml +/// --test edge_tunnel_e2e -- --ignored mcp_serve_through_edge_proxy`. +#[tokio::test] +#[ignore = "needs a plaintext gateway with child sandboxes enabled"] +async fn mcp_serve_through_edge_proxy() { + if std::env::var("OPENSHELL_E2E_CHILD_SANDBOXES").as_deref() != Ok("1") { + eprintln!( + "Skipping mcp_serve test: set OPENSHELL_E2E_CHILD_SANDBOXES=1 on a gateway with /mcp" + ); + return; + } + let Some(endpoint) = plaintext_gateway_endpoint("mcp_serve test").await else { + return; + }; + let tmpdir = tempfile::tempdir().expect("create temp config dir"); + seed_edge_gateway_config( + tmpdir.path(), + "edge-tunnel-mcp", + &endpoint, + "dummy-test-jwt", + ); + + let mut cmd = openshell_cmd(); + cmd.args(["--gateway", "edge-tunnel-mcp", "mcp", "serve"]) + .env("XDG_CONFIG_HOME", tmpdir.path()) + .env("HOME", tmpdir.path()) + .env_remove("OPENSHELL_GATEWAY") + .env_remove("OPENSHELL_GATEWAY_ENDPOINT") + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + let mut child = cmd.spawn().expect("spawn openshell mcp serve"); + { + use tokio::io::AsyncWriteExt; + let mut stdin = child.stdin.take().expect("bridge stdin"); + stdin + .write_all( + concat!( + r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18"}}"#, + "\n", + r#"{"jsonrpc":"2.0","id":2,"method":"tools/list"}"#, + "\n", + ) + .as_bytes(), + ) + .await + .expect("write to the bridge"); + } + let output = tokio::time::timeout(std::time::Duration::from_mins(1), child.wait_with_output()) + .await + .expect("the bridge exits once stdin closes") + .expect("bridge output"); + let stdout = String::from_utf8_lossy(&output.stdout); + let replies: Vec = stdout + .lines() + .map(|line| serde_json::from_str(line).unwrap_or_else(|_| panic!("not JSON-RPC: {line}"))) + .collect(); + let tools = replies + .iter() + .find(|reply| reply["id"] == 2) + .and_then(|reply| reply["result"]["tools"].as_array()) + .unwrap_or_else(|| { + panic!( + "no tools/list result through the tunnel: {stdout}\n{}", + String::from_utf8_lossy(&output.stderr) + ) + }); + assert_eq!(tools.len(), 6, "{stdout}"); +} diff --git a/e2e/support/gateway-common.sh b/e2e/support/gateway-common.sh index f69518f0bc..2125b38130 100644 --- a/e2e/support/gateway-common.sh +++ b/e2e/support/gateway-common.sh @@ -463,6 +463,29 @@ e2e_write_gateway_mtls_auth_config() { printf 'enabled = true\n\n' } +# Opt the gateway into child sandboxes for the child_sandboxes e2e test: turn +# on the experimental setting (which also serves /mcp), and write the +# gateway's OCSF events as JSONL where the test can read the MCP audit fields. +e2e_enable_child_sandboxes() { + local gateway_config=$1 + local state_dir=$2 + local with_child_settings="${gateway_config}.child-sandboxes" + + awk ' + { print } + !inserted && $0 == "[openshell.gateway]" { + print "experimental_enable_child_sandboxes = true" + inserted = 1 + } + END { if (!inserted) exit 42 } + ' "${gateway_config}" >"${with_child_settings}" + mv "${with_child_settings}" "${gateway_config}" + + export OPENSHELL_OCSF_JSON=1 + export OPENSHELL_OCSF_LOG_DIR="${state_dir}/gateway-ocsf" + export OPENSHELL_E2E_GATEWAY_OCSF_DIR="${OPENSHELL_OCSF_LOG_DIR}" +} + e2e_write_gateway_oidc_config() { local issuer=$1 local scopes_claim="${2:-scope}" diff --git a/e2e/with-docker-gateway.sh b/e2e/with-docker-gateway.sh index 57d49632f4..0b387e2ba8 100755 --- a/e2e/with-docker-gateway.sh +++ b/e2e/with-docker-gateway.sh @@ -671,6 +671,9 @@ GATEWAY_CONFIG="${STATE_DIR}/gateway.toml" printf '\n[openshell.drivers.docker.resource_admission]\n' printf 'enabled = false\n' } > "${GATEWAY_CONFIG}" +if [ "${OPENSHELL_E2E_CHILD_SANDBOXES:-0}" = "1" ]; then + e2e_enable_child_sandboxes "${GATEWAY_CONFIG}" "${STATE_DIR}" +fi GATEWAY_ARGS=( --config "${GATEWAY_CONFIG}" diff --git a/e2e/with-podman-gateway.sh b/e2e/with-podman-gateway.sh index c489fb678e..19901d5d8b 100755 --- a/e2e/with-podman-gateway.sh +++ b/e2e/with-podman-gateway.sh @@ -603,6 +603,9 @@ if [ "${OPENSHELL_E2E_EXTERNAL_COMPUTE_DRIVER:-0}" != "1" ]; then ' "${GATEWAY_CONFIG}" >"${CONFIG_WITH_DRIVER_DIR}" mv "${CONFIG_WITH_DRIVER_DIR}" "${GATEWAY_CONFIG}" fi +if [ "${OPENSHELL_E2E_CHILD_SANDBOXES:-0}" = "1" ]; then + e2e_enable_child_sandboxes "${GATEWAY_CONFIG}" "${STATE_DIR}" +fi EXTERNAL_DRIVER_GRPC_ENDPOINT="https://127.0.0.1:${HOST_PORT}" EXTERNAL_DRIVER_HEALTH_CHECK_INTERVAL_SECS=10 EXTERNAL_DRIVER_ENABLE_BIND_MOUNTS=true diff --git a/examples/governance-interceptor/src/main.rs b/examples/governance-interceptor/src/main.rs index 2d670f82cf..3975991651 100644 --- a/examples/governance-interceptor/src/main.rs +++ b/examples/governance-interceptor/src/main.rs @@ -1246,6 +1246,7 @@ async fn propagate_policy_to_running_sandboxes( page_token, label_selector: String::new(), workspace_scope: Some(openshell_core::proto::all_workspaces_selector()), + parent: String::new(), }) .await .map_err(|status| format!("list sandboxes failed: {status}"))? diff --git a/proto/openshell.proto b/proto/openshell.proto index 4212445623..a60e36377c 100644 --- a/proto/openshell.proto +++ b/proto/openshell.proto @@ -1210,6 +1210,16 @@ message Sandbox { string host_key_fingerprint = 6; // Read-only provenance for sandboxes created from a reusable workload template. SandboxWorkloadTemplateProvenance created_from_workload_template = 20; + // EXPERIMENTAL: Read-only parent of a child sandbox, set by the gateway at + // creation. Absent on root sandboxes. Never changes. This API and its + // behavior may change or be removed. + SandboxParent parent = 21; + // EXPERIMENTAL: Read-only user this sandbox was created on behalf of, + // directly or through a sandbox acting for them. Set once by the gateway at + // creation; a child created over MCP copies its root's value. Absent on + // sandboxes created before this field existed and on sandboxes no user + // created. This API and its behavior may change or be removed. + UserRef created_on_behalf_of = 22; reserved 4, 5; reserved "phase", "current_policy_version"; @@ -1356,6 +1366,26 @@ message SandboxWorkloadTemplateProvenance { string resource_version = 2; } +// EXPERIMENTAL: The parent of a child sandbox. This API and its behavior may +// change or be removed. +message SandboxParent { + // The parent's name, for display. + string name = 1; + // The parent's immutable id; names can be reused after a delete. + string id = 2; +} + +// EXPERIMENTAL: A user, as the gateway authenticated them. This API and its +// behavior may change or be removed. +message UserRef { + // Stable identity subject, as in `WorkspaceMember.principal_subject`. + string subject = 1; + // How the user authenticated, as in + // `GetCurrentUserResponse.identity_provider`. It names the login method, not + // the issuer, so it does not tell apart two users with the same subject. + string identity_provider = 2; +} + // User-facing sandbox status derived by the gateway from compute-driver observations. // // Public status does not embed driver-only flags such as `deleting`. @@ -1484,6 +1514,10 @@ message CreateSandboxRequest { // registered after the sandbox has been persisted and route only while the // sandbox is ready. repeated SandboxServiceExposure service_exposures = 9; + // EXPERIMENTAL: Optional name of a root sandbox in the same workspace to + // create this sandbox under. Empty creates a root sandbox. This API and its + // behavior may change or be removed. + string parent = 10; } // Update selected configuration of a stopped sandbox. Omitted fields are unchanged. @@ -1622,6 +1656,10 @@ message ListSandboxesRequest { string page_token = 2; // Optional label selector for filtering (format: "key1=value1,key2=value2"). string label_selector = 3; + // EXPERIMENTAL: Optional name of a root sandbox; lists only its children. + // Needs a named workspace scope. A child of a deleted root of the same name + // is not listed. This API and its behavior may change or be removed. + string parent = 5; } // List providers attached to a sandbox request. diff --git a/skills/openshell-cli/SKILL.md b/skills/openshell-cli/SKILL.md index c89ba151ea..3ffd5146ee 100644 --- a/skills/openshell-cli/SKILL.md +++ b/skills/openshell-cli/SKILL.md @@ -36,6 +36,7 @@ Use `openshell --help` and nested `--help` output as the authority for the insta - [Manage gateways](https://docs.nvidia.com/openshell/latest/how-it-works/gateways/overview) - [Manage sandboxes](https://docs.nvidia.com/openshell/latest/how-it-works/sandboxes/overview) +- [Child sandboxes](https://docs.nvidia.com/openshell/latest/how-it-works/sandboxes/child-sandboxes) - [Manage providers](https://docs.nvidia.com/openshell/latest/how-it-works/providers/overview) - [Profiles](https://docs.nvidia.com/openshell/latest/how-it-works/providers/profiles) - [Sandbox policies](https://docs.nvidia.com/openshell/latest/how-it-works/policies/overview) @@ -433,6 +434,30 @@ applies its default sandbox image when creating a sandbox from the template. Create-time policy, providers, labels, uploads, forwarding, editor launch, and the initial command stay on `sandbox create`. +### Create child sandboxes (experimental) + +Needs `experimental_enable_child_sandboxes` on the gateway. A child is created +under a root, uses the root's policy, and can use only the root's providers; +a child cannot have children. + +```bash +openshell sandbox create --name reviewer --parent lead --provider anthropic +openshell sandbox list --parent lead +openshell sandbox delete reviewer # delete children before their parent +openshell sandbox delete lead +``` + +Do not pass `--policy` with `--parent`; change the parent's policy instead. A +provider the parent lacks is refused. `sandbox list` shows a `PARENT` column +when the page holds a child. + +### Serve the sandbox tools to an MCP client (experimental) + +`openshell mcp serve` runs a local MCP server over stdio that forwards tool +calls to the active gateway with the CLI login, acting in `--workspace`. Add it +to the MCP client's configuration as the command `openshell mcp serve`. Its +stdout carries only MCP messages; diagnostics go to stderr. + ### List and inspect sandboxes ```bash diff --git a/tasks/scripts/gateway-docker.sh b/tasks/scripts/gateway-docker.sh index e507cc0ba5..0b6ca91ae5 100644 --- a/tasks/scripts/gateway-docker.sh +++ b/tasks/scripts/gateway-docker.sh @@ -19,6 +19,7 @@ # OPENSHELL_SUPERVISOR_IMAGE=ghcr.io/... mise run gateway:docker # OPENSHELL_SANDBOX_RUNTIME_IMAGE=ghcr.io/... mise run gateway:docker # OPENSHELL_DEV_OTLP_ENDPOINT=http://127.0.0.1:4317 mise run gateway:docker +# OPENSHELL_EXPERIMENTAL_CHILD_SANDBOXES=1 mise run gateway:docker # # After the gateway is running, point the CLI at it with either: # openshell --gateway docker-dev @@ -164,6 +165,7 @@ name = "${GATEWAY_NAME}" compute_driver = "docker" driver_dir = "${ROOT}/target/debug" disable_tls = true +$([[ "${OPENSHELL_EXPERIMENTAL_CHILD_SANDBOXES:-0}" == "1" ]] && echo "experimental_enable_child_sandboxes = true") [openshell.gateway.auth] allow_unauthenticated_users = true diff --git a/tasks/test.toml b/tasks/test.toml index eadccc4789..ffbc4a98bb 100644 --- a/tasks/test.toml +++ b/tasks/test.toml @@ -214,6 +214,14 @@ description = "Run the testkit suites in tests/suites/conformance against a Dock depends = ["e2e:python-image:build"] run = "e2e/with-docker-gateway.sh cargo nextest run --locked --manifest-path tests/suites/conformance/Cargo.toml --workspace --test-threads 1 --no-fail-fast" +["e2e:rust:child-sandboxes"] +description = "Run the child sandbox and MCP e2e tests against a Docker gateway with child sandboxes enabled" +run = "OPENSHELL_E2E_CHILD_SANDBOXES=1 OPENSHELL_TEST_CONTAINER_ENGINE=docker e2e/with-docker-gateway.sh cargo test --manifest-path e2e/rust/Cargo.toml --features e2e-docker,e2e-child-sandboxes --test child_sandboxes" + +["e2e:rust:child-sandboxes:podman"] +description = "Run the child sandbox and MCP e2e tests against a Podman gateway with child sandboxes enabled" +run = "OPENSHELL_E2E_CHILD_SANDBOXES=1 OPENSHELL_TEST_CONTAINER_ENGINE=podman e2e/with-podman-gateway.sh cargo test --manifest-path e2e/rust/Cargo.toml --features e2e-docker,e2e-child-sandboxes --test child_sandboxes" + ["e2e:python-image:build"] description = "Build the E2E Python image (openshell/e2e-python:dev) for Docker" run = "CONTAINER_ENGINE=docker bash tasks/scripts/e2e-build-workload.sh" diff --git a/tests/suites/conformance/Cargo.lock b/tests/suites/conformance/Cargo.lock index 3fbaf3269e..e434d13318 100644 --- a/tests/suites/conformance/Cargo.lock +++ b/tests/suites/conformance/Cargo.lock @@ -2437,6 +2437,8 @@ dependencies = [ "async-stream", "async-trait", "futures", + "http", + "http-body-util", "hyper", "hyper-util", "miette", diff --git a/tests/suites/continuity/Cargo.lock b/tests/suites/continuity/Cargo.lock index f031bc1b57..83ddd69651 100644 --- a/tests/suites/continuity/Cargo.lock +++ b/tests/suites/continuity/Cargo.lock @@ -2416,6 +2416,8 @@ dependencies = [ "async-stream", "async-trait", "futures", + "http", + "http-body-util", "hyper", "hyper-util", "miette", diff --git a/tests/suites/drivers/docker/Cargo.lock b/tests/suites/drivers/docker/Cargo.lock index c9e06d3753..c1f80a6b4b 100644 --- a/tests/suites/drivers/docker/Cargo.lock +++ b/tests/suites/drivers/docker/Cargo.lock @@ -2425,6 +2425,8 @@ dependencies = [ "async-stream", "async-trait", "futures", + "http", + "http-body-util", "hyper", "hyper-util", "miette", diff --git a/tests/suites/drivers/podman/Cargo.lock b/tests/suites/drivers/podman/Cargo.lock index 1187155f9c..29dd4bd251 100644 --- a/tests/suites/drivers/podman/Cargo.lock +++ b/tests/suites/drivers/podman/Cargo.lock @@ -2417,6 +2417,8 @@ dependencies = [ "async-stream", "async-trait", "futures", + "http", + "http-body-util", "hyper", "hyper-util", "miette", diff --git a/tests/suites/features/Cargo.lock b/tests/suites/features/Cargo.lock index 9c6425175c..33016964d4 100644 --- a/tests/suites/features/Cargo.lock +++ b/tests/suites/features/Cargo.lock @@ -2869,6 +2869,8 @@ dependencies = [ "async-stream", "async-trait", "futures", + "http", + "http-body-util", "hyper", "hyper-util", "miette", diff --git a/tests/support/Cargo.lock b/tests/support/Cargo.lock index 83e25ef4da..58f16dd6e3 100644 --- a/tests/support/Cargo.lock +++ b/tests/support/Cargo.lock @@ -2570,6 +2570,8 @@ dependencies = [ "async-stream", "async-trait", "futures", + "http", + "http-body-util", "hyper", "hyper-util", "miette", diff --git a/tests/testkit/Cargo.lock b/tests/testkit/Cargo.lock index 154e28d156..ae7c661516 100644 --- a/tests/testkit/Cargo.lock +++ b/tests/testkit/Cargo.lock @@ -2408,6 +2408,8 @@ dependencies = [ "async-stream", "async-trait", "futures", + "http", + "http-body-util", "hyper", "hyper-util", "miette",