diff --git a/Cargo.lock b/Cargo.lock index 1f0f2b414e..c31970abfa 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4527,6 +4527,7 @@ dependencies = [ "tokio", "tokio-rustls", "tokio-stream", + "tokio-util", "tonic", "tonic-prost", "tonic-prost-build", @@ -4535,6 +4536,7 @@ dependencies = [ "tracing-subscriber", "url", "uuid", + "windows-sys 0.61.2", "zeroize", ] diff --git a/crates/openshell-cli/src/main.rs b/crates/openshell-cli/src/main.rs index 8fc1a33116..197ecb64d1 100644 --- a/crates/openshell-cli/src/main.rs +++ b/crates/openshell-cli/src/main.rs @@ -5,7 +5,7 @@ #![forbid(unsafe_code)] -use clap::{CommandFactory, Parser, Subcommand, ValueEnum, ValueHint}; +use clap::{CommandFactory, FromArgMatches, Parser, Subcommand, ValueEnum, ValueHint}; use clap_complete::engine::ArgValueCompleter; use clap_complete::env::CompleteEnv; use miette::Result; @@ -45,19 +45,25 @@ impl From for GpuResourceRequirements { } } -/// Resolve the gateway name to a [`GatewayContext`] with the gateway endpoint. -/// -/// Resolution priority: -/// 1. `--gateway-endpoint` flag (direct URL, preserving metadata when available) -/// 2. `--gateway` flag (explicit name) -/// 3. `OPENSHELL_GATEWAY` environment variable -/// 4. Active gateway from `~/.config/openshell/active_gateway` -/// -/// When `--gateway-endpoint` is provided, it is used directly as the endpoint. -/// If stored metadata can still identify the gateway, the stored gateway name -/// is preserved so auth and TLS materials continue to resolve correctly. -fn normalize_gateway_endpoint(endpoint: &str) -> &str { - endpoint.trim_end_matches('/') +fn normalize_gateway_endpoint(endpoint: &str) -> String { + let endpoint = if endpoint.contains(['?', '#']) { + endpoint + } else { + endpoint.trim_end_matches('/') + }; + let Some((scheme, rest)) = endpoint.split_once("://") else { + return endpoint.to_owned(); + }; + let (authority, route) = rest.split_at(rest.find(['/', '?', '#', '\\']).unwrap_or(rest.len())); + let (userinfo, host_port) = authority.split_at(authority.rfind('@').map_or(0, |i| i + 1)); + if host_port.starts_with('[') { + return endpoint.to_owned(); + } + let (host, port) = host_port.split_at(host_port.find(':').unwrap_or(host_port.len())); + format!( + "{scheme}://{userinfo}{}{port}{route}", + host.to_ascii_lowercase() + ) } fn find_gateway_by_endpoint(endpoint: &str) -> Option { @@ -76,18 +82,33 @@ fn find_gateway_by_endpoint(endpoint: &str) -> Option { }) } +/// Resolve the gateway name to a [`GatewayContext`] with the gateway endpoint. +/// +/// Resolution priority: +/// 1. `--gateway-endpoint` flag (direct URL, preserving metadata when available) +/// 2. `--gateway` flag (explicit name) +/// 3. `OPENSHELL_GATEWAY` environment variable +/// 4. Active gateway from `~/.config/openshell/active_gateway` +/// +/// When `--gateway-endpoint` is provided, it is used directly as the endpoint. +/// If stored metadata can still identify the gateway, the stored gateway name +/// is preserved so auth and TLS materials continue to resolve correctly. fn resolve_gateway( gateway_flag: &Option, gateway_endpoint: &Option, + allow_endpoint_override: bool, ) -> Result { if let Some(endpoint) = gateway_endpoint { - // When a gateway name is explicitly provided (via flag or env var), - // trust it directly — don't require metadata to exist yet. This - // avoids a race condition where mTLS certs are stored under the - // real gateway name but the CLI falls back to using the raw - // endpoint URL (producing a mangled path like `https___...`). let name = gateway_flag - .clone() + .as_ref() + .filter(|name| { + allow_endpoint_override + || get_gateway_metadata(name).is_some_and(|metadata| { + normalize_gateway_endpoint(&metadata.gateway_endpoint) + == normalize_gateway_endpoint(endpoint) + }) + }) + .cloned() .or_else(|| find_gateway_by_endpoint(endpoint)) .unwrap_or_else(|| endpoint.clone()); return Ok(GatewayContext { @@ -675,41 +696,24 @@ enum Commands { shell: CompletionShell, }, - /// SSH proxy (used by `ProxyCommand`). - /// - /// Two mutually exclusive modes: - /// - /// **Token mode** (used internally by `sandbox connect`): - /// `openshell ssh-proxy --gateway --sandbox --token ` - /// - /// **Name mode** (for use in `~/.ssh/config`): - /// `openshell ssh-proxy --gateway --name ` + /// Mint an SSH session and relay SSH over the selected gateway. #[command(hide = true, help_template = LEAF_HELP_TEMPLATE, next_help_heading = "FLAGS")] SshProxy { - /// Gateway URL (e.g., ). - /// Required in token mode. In name mode, can be a gateway name. - #[arg(long, short = 'g')] - gateway: Option, - - /// Sandbox name. Required in token mode. - #[arg(long)] - sandbox: Option, - - /// SSH session token. Required in token mode. - #[arg(long)] - token: Option, - - /// Gateway endpoint URL. Used in name mode. Deprecated: prefer --gateway. + /// Gateway endpoint override. #[arg(long)] server: Option, - /// Gateway name. Used with --name to resolve gateway from metadata. + /// One-use local relay grant prepared by the parent. + #[arg(long, conflicts_with_all = ["server", "gateway_name"])] + handoff: Option, + + /// Registered gateway to use for credentials and endpoint discovery. #[arg(long)] gateway_name: Option, - /// Sandbox name. Used in name mode. - #[arg(long)] - name: Option, + /// Sandbox to connect to. + #[arg(long, alias = "sandbox")] + name: String, }, } @@ -2797,7 +2801,25 @@ fn run_main() -> Result<()> { async fn run_async() -> Result<()> { CompleteEnv::with_factory(Cli::command).complete(); - let cli = Cli::parse(); + let (cli, explicit_gateway, explicit_endpoint) = { + let mut args = Cli::command().get_matches(); + let explicit_gateway = + args.value_source("gateway") == Some(clap::parser::ValueSource::CommandLine); + let explicit_endpoint = + args.value_source("gateway_endpoint") == Some(clap::parser::ValueSource::CommandLine); + ( + Cli::from_arg_matches_mut(&mut args).unwrap_or_else(|err| err.exit()), + explicit_gateway, + explicit_endpoint, + ) + }; + let current_gateway = || { + resolve_gateway( + &cli.gateway, + &cli.gateway_endpoint, + explicit_gateway == explicit_endpoint, + ) + }; // Resolve colorization before anything is printed, so no command can emit // escape sequences into a pipe. @@ -2902,7 +2924,7 @@ async fn run_async() -> Result<()> { run::gateway_select(name.as_deref(), &cli.gateway)?; } GatewayCommands::Info { output } => { - if let Ok(ctx) = resolve_gateway(&cli.gateway, &cli.gateway_endpoint) { + if let Ok(ctx) = current_gateway() { let mut tls = tls.with_gateway_name(&ctx.name); apply_auth(&mut tls, &ctx.name)?; run::gateway_info(&ctx.name, &ctx.endpoint, &tls, output.as_str()).await?; @@ -2938,7 +2960,7 @@ async fn run_async() -> Result<()> { // ----------------------------------------------------------- Some(Commands::Status { output }) => { // A gateway named on the command line must be registered. - let resolved = match resolve_gateway(&cli.gateway, &cli.gateway_endpoint) { + let resolved = match current_gateway() { Err(err) if cli.gateway.is_some() => return Err(err), resolved => resolved, }; @@ -2975,7 +2997,7 @@ async fn run_async() -> Result<()> { // Top-level current identity // ----------------------------------------------------------- Some(Commands::Whoami { output }) => { - let ctx = resolve_gateway(&cli.gateway, &cli.gateway_endpoint)?; + let ctx = current_gateway()?; let mut tls = tls.with_gateway_name(&ctx.name); apply_auth(&mut tls, &ctx.name)?; run::whoami(&ctx.endpoint, &tls, output.as_str()).await?; @@ -3091,7 +3113,7 @@ async fn run_async() -> Result<()> { target_host, local, } => { - let ctx = resolve_gateway(&cli.gateway, &cli.gateway_endpoint)?; + let ctx = current_gateway()?; let mut tls = tls.with_gateway_name(&ctx.name); apply_auth(&mut tls, &ctx.name)?; let name = resolve_sandbox_name(name, &ctx.name, &cli.workspace)?; @@ -3113,7 +3135,7 @@ async fn run_async() -> Result<()> { background, } => { let spec = openshell_core::forward::ForwardSpec::parse(&port)?; - let ctx = resolve_gateway(&cli.gateway, &cli.gateway_endpoint)?; + let ctx = current_gateway()?; let mut tls = tls.with_gateway_name(&ctx.name); apply_auth(&mut tls, &ctx.name)?; let name = resolve_sandbox_name(name, &ctx.name, &cli.workspace)?; @@ -3144,7 +3166,7 @@ async fn run_async() -> Result<()> { Some(Commands::Service { command: Some(command), }) => { - let ctx = resolve_gateway(&cli.gateway, &cli.gateway_endpoint)?; + let ctx = current_gateway()?; let mut tls = tls.with_gateway_name(&ctx.name); apply_auth(&mut tls, &ctx.name)?; match command { @@ -3208,7 +3230,7 @@ async fn run_async() -> Result<()> { source, level, }) => { - let ctx = resolve_gateway(&cli.gateway, &cli.gateway_endpoint)?; + let ctx = current_gateway()?; let mut tls = tls.with_gateway_name(&ctx.name); apply_auth(&mut tls, &ctx.name)?; let name = resolve_sandbox_name(name, &ctx.name, &cli.workspace)?; @@ -3235,7 +3257,7 @@ async fn run_async() -> Result<()> { Some(Commands::Policy { command: Some(policy_cmd), }) => { - let ctx = resolve_gateway(&cli.gateway, &cli.gateway_endpoint)?; + let ctx = current_gateway()?; let mut tls = tls.with_gateway_name(&ctx.name); apply_auth(&mut tls, &ctx.name)?; match policy_cmd { @@ -3397,7 +3419,7 @@ async fn run_async() -> Result<()> { Some(Commands::Settings { command: Some(settings_cmd), }) => { - let ctx = resolve_gateway(&cli.gateway, &cli.gateway_endpoint)?; + let ctx = current_gateway()?; let mut tls = tls.with_gateway_name(&ctx.name); apply_auth(&mut tls, &ctx.name)?; @@ -3476,7 +3498,7 @@ async fn run_async() -> Result<()> { Some(Commands::Rule { command: Some(draft_cmd), }) => { - let ctx = resolve_gateway(&cli.gateway, &cli.gateway_endpoint)?; + let ctx = current_gateway()?; let mut tls = tls.with_gateway_name(&ctx.name); apply_auth(&mut tls, &ctx.name)?; match draft_cmd { @@ -3635,7 +3657,7 @@ async fn run_async() -> Result<()> { || expose.is_some(); let gpu_requirements: Option = gpu.map(Into::into); - let ctx = resolve_gateway(&cli.gateway, &cli.gateway_endpoint)?; + let ctx = current_gateway()?; let endpoint = &ctx.endpoint; let mut tls = tls.with_gateway_name(&ctx.name); apply_auth(&mut tls, &ctx.name)?; @@ -3685,7 +3707,7 @@ async fn run_async() -> Result<()> { dest, no_git_ignore, } => { - let ctx = resolve_gateway(&cli.gateway, &cli.gateway_endpoint)?; + let ctx = current_gateway()?; let mut tls = tls.with_gateway_name(&ctx.name); apply_auth(&mut tls, &ctx.name)?; let local = std::path::Path::new(&local_path); @@ -3705,7 +3727,7 @@ async fn run_async() -> Result<()> { sandbox_path, dest, } => { - let ctx = resolve_gateway(&cli.gateway, &cli.gateway_endpoint)?; + let ctx = current_gateway()?; let mut tls = tls.with_gateway_name(&ctx.name); apply_auth(&mut tls, &ctx.name)?; let local_dest = dest.as_deref().unwrap_or("."); @@ -3722,7 +3744,7 @@ async fn run_async() -> Result<()> { eprintln!("{} Download complete", "✓".green().bold()); } other => { - let ctx = resolve_gateway(&cli.gateway, &cli.gateway_endpoint)?; + let ctx = current_gateway()?; let endpoint = &ctx.endpoint; let mut tls = tls.with_gateway_name(&ctx.name); apply_auth(&mut tls, &ctx.name)?; @@ -3862,7 +3884,7 @@ async fn run_async() -> Result<()> { } SandboxCommands::SshConfig { name } => { let name = resolve_sandbox_name(name, &ctx.name, &cli.workspace)?; - run::print_ssh_config(&ctx.name, &name, &cli.workspace); + run::print_ssh_config(&ctx.name, &name, &cli.workspace)?; } SandboxCommands::Provider(command) => match command { SandboxProviderCommands::List { @@ -4025,7 +4047,7 @@ async fn run_async() -> Result<()> { Some(Commands::Workspace { command: Some(command), }) => { - let ctx = resolve_gateway(&cli.gateway, &cli.gateway_endpoint)?; + let ctx = current_gateway()?; let endpoint = &ctx.endpoint; let mut tls = tls.with_gateway_name(&ctx.name); apply_auth(&mut tls, &ctx.name)?; @@ -4095,7 +4117,7 @@ async fn run_async() -> Result<()> { Some(Commands::Provider { command: Some(command), }) => { - let ctx = resolve_gateway(&cli.gateway, &cli.gateway_endpoint)?; + let ctx = current_gateway()?; let endpoint = &ctx.endpoint; let mut tls = tls.with_gateway_name(&ctx.name); apply_auth(&mut tls, &ctx.name)?; @@ -4289,14 +4311,14 @@ async fn run_async() -> Result<()> { Some(Commands::Profile { command: Some(command), }) => { - let ctx = resolve_gateway(&cli.gateway, &cli.gateway_endpoint)?; + let ctx = current_gateway()?; let endpoint = &ctx.endpoint; let mut tls = tls.with_gateway_name(&ctx.name); apply_auth(&mut tls, &ctx.name)?; command.run(endpoint, &cli.workspace, &tls).await?; } Some(Commands::Term { theme }) => { - let ctx = resolve_gateway(&cli.gateway, &cli.gateway_endpoint)?; + let ctx = current_gateway()?; let mut tls = tls.with_gateway_name(&ctx.name); apply_auth(&mut tls, &ctx.name)?; let channel = openshell_cli::tls::build_channel(&ctx.endpoint, &tls).await?; @@ -4304,13 +4326,14 @@ async fn run_async() -> Result<()> { tls.oidc_token.as_deref(), tls.edge_token.as_deref(), )?; - openshell_tui::run( + openshell_tui::run_with_gateway_insecure( channel, interceptor, &ctx.name, &ctx.endpoint, &cli.workspace, theme, + tls.gateway_insecure, ) .await?; } @@ -4327,53 +4350,30 @@ async fn run_async() -> Result<()> { .map_err(|e| miette::miette!("failed to write completions: {e}"))?; } Some(Commands::SshProxy { - gateway, - sandbox, - token, server, gateway_name, name, + handoff, }) => { - match (gateway, sandbox, token, server, gateway_name, name) { - // Token mode (existing behavior): pre-created session credentials. - (Some(gw), Some(sandbox), Some(tok), _, gateway_name_opt, _) => { - let mut effective_tls = match gateway_name_opt { - Some(ref g) => tls.with_gateway_name(g), - None => tls, - }; - if let Some(ref g) = gateway_name_opt { - apply_auth(&mut effective_tls, g)?; - } - run::sandbox_ssh_proxy(&gw, &sandbox, &cli.workspace, &tok, &effective_tls) - .await?; - } - // Name mode with --gateway-name: resolve endpoint from metadata. - (_, _, _, server_override, Some(g), Some(n)) => { - let endpoint = if let Some(srv) = server_override { - srv - } else { - let meta = load_gateway_metadata(&g).map_err(|_| { - miette::miette!( - "Unknown gateway '{g}'.\n\ - Register it first: openshell gateway add --name {g}\n\ - Or list available gateways: openshell gateway select" - ) - })?; - meta.gateway_endpoint - }; - let mut tls = tls.with_gateway_name(&g); - apply_auth(&mut tls, &g)?; - run::sandbox_ssh_proxy_by_name(&endpoint, &n, &tls, &cli.workspace).await?; - } - // Legacy name mode with --server only (no --gateway-name). - (_, _, _, Some(srv), None, Some(n)) => { - run::sandbox_ssh_proxy_by_name(&srv, &n, &tls, &cli.workspace).await?; - } - _ => { - return Err(miette::miette!( - "provide either --gateway/--sandbox/--token or --gateway-name/--name (or --server/--name)" - )); - } + if let Some(handle) = handoff { + let (grant, peer) = openshell_core::ssh_handoff::receive(&handle).await?; + let mut tls = tls.with_gateway_name(&grant.gateway_name); + apply_auth(&mut tls, &grant.gateway_name)?; + openshell_cli::ssh::relay_prepared_ssh(grant, peer, &name, &cli.workspace, &tls) + .await?; + } else { + // A saved profile resolves its own endpoint. A local --server + // can explicitly pair an endpoint with the chosen profile. + let use_global_endpoint = + gateway_name.is_none() && (!explicit_gateway || explicit_endpoint); + let endpoint = + server.or_else(|| cli.gateway_endpoint.filter(|_| use_global_endpoint)); + let allow_endpoint_override = gateway_name.is_some() || explicit_gateway; + let profile = gateway_name.or(cli.gateway); + let ctx = resolve_gateway(&profile, &endpoint, allow_endpoint_override)?; + let mut tls = tls.with_gateway_name(&ctx.name); + apply_auth(&mut tls, &ctx.name)?; + run::sandbox_ssh_proxy_by_name(&ctx.endpoint, &name, &tls, &cli.workspace).await?; } } @@ -4416,7 +4416,7 @@ async fn run_async() -> Result<()> { Some(Commands::Secret { command: Some(command), }) => { - let ctx = resolve_gateway(&cli.gateway, &cli.gateway_endpoint)?; + let ctx = current_gateway()?; let endpoint = &ctx.endpoint; let mut tls = tls.with_gateway_name(&ctx.name); apply_auth(&mut tls, &ctx.name)?; @@ -5272,12 +5272,37 @@ mod tests { ) .unwrap(); - let ctx = resolve_gateway(&None, &Some("https://gw.example.com/".to_string())).unwrap(); + let ctx = resolve_gateway(&None, &Some("https://GW.example.com/".to_string()), false) + .unwrap(); assert_eq!(ctx.name, "edge-gateway"); - assert_eq!(ctx.endpoint, "https://gw.example.com/"); + assert_eq!(ctx.endpoint, "https://GW.example.com/"); }); } + #[test] + fn endpoint_matching_preserves_userinfo_port_and_route() { + let endpoint = "https://User:Password@GW.example:8443/Tenant?k=Token/#Section"; + let normalized = normalize_gateway_endpoint(endpoint); + assert_eq!(normalized, endpoint.replace("GW", "gw")); + for (from, to) in [ + ("User", "user"), + ("Password", "password"), + ("8443", "443"), + ("Tenant", "tenant"), + ("Token", "token"), + ("Section", "section"), + ] { + assert_ne!( + normalized, + normalize_gateway_endpoint(&endpoint.replace(from, to)) + ); + } + assert_ne!( + normalize_gateway_endpoint("https://gw/?key=token/"), + normalize_gateway_endpoint("https://gw/?key=token") + ); + } + #[test] fn resolve_gateway_prefers_explicit_gateway_for_direct_endpoint() { let tmp = tempfile::tempdir().unwrap(); @@ -5291,6 +5316,7 @@ mod tests { let ctx = resolve_gateway( &Some("named-gateway".to_string()), &Some("https://override.example.com".to_string()), + true, ) .unwrap(); @@ -5357,48 +5383,46 @@ mod tests { }); } - /// Verify the flag names the TUI uses to build its `ProxyCommand` are - /// accepted by the `SshProxy` subcommand and land in the right fields. - /// This catches drift when CLI flags are renamed or restructured. #[test] - fn ssh_proxy_token_mode_flags_match_tui_proxy_command() { - // This is the exact flag pattern constructed by the TUI in lib.rs - // (handle_shell_connect, handle_exec, handle_port_forward). - let cli = Cli::try_parse_from([ - "openshell", - "ssh-proxy", - "--gateway", - "https://gw.example.com:8080/proxy/connect", - "--sandbox", - "my-box", - "--workspace", - "team-a", - "--token", - "tok-abc", - "--gateway-name", - "my-gateway", - ]) - .expect("TUI proxy command flags must be accepted by the CLI"); - assert_eq!(cli.workspace, "team-a"); + fn ssh_proxy_rejects_tokens_in_arguments() { + assert!( + Cli::try_parse_from([ + "openshell", + "ssh-proxy", + "--gateway", + "gw", + "--sandbox", + "demo", + "--token", + "test-token", + ]) + .is_err() + ); + } - match cli.command { - Some(Commands::SshProxy { - gateway, - sandbox, - token, - gateway_name, - .. - }) => { - assert_eq!( - gateway.as_deref(), - Some("https://gw.example.com:8080/proxy/connect"), - "gateway URL must land in SshProxy.gateway, not the global flag" - ); - assert_eq!(sandbox.as_deref(), Some("my-box")); - assert_eq!(token.as_deref(), Some("tok-abc")); - assert_eq!(gateway_name.as_deref(), Some("my-gateway")); - } - other => panic!("expected SshProxy, got: {other:?}"), + #[test] + fn ssh_proxy_accepts_generated_and_saved_commands() { + for name_flag in ["--sandbox", "--name"] { + let cli = Cli::try_parse_from([ + "openshell", + "ssh-proxy", + "--gateway-name", + "my-gateway", + name_flag, + "my-box", + "--workspace", + "team-a", + ]) + .unwrap(); + assert_eq!(cli.workspace, "team-a"); + let Some(Commands::SshProxy { + gateway_name, name, .. + }) = cli.command + else { + panic!("expected ssh-proxy") + }; + assert_eq!(gateway_name.as_deref(), Some("my-gateway")); + assert_eq!(name, "my-box"); } } diff --git a/crates/openshell-cli/src/run.rs b/crates/openshell-cli/src/run.rs index dafc10efba..b7b172dc39 100644 --- a/crates/openshell-cli/src/run.rs +++ b/crates/openshell-cli/src/run.rs @@ -101,7 +101,7 @@ fn proto_execution_timeout(timeout_seconds: u32) -> Result, @@ -1082,10 +1082,11 @@ pub async fn sandbox_create( } // Boxed so the upload state machine lives on the heap instead of // inflating the `sandbox_create` future (clippy::large_futures). - Box::pin(sandbox_upload_planned( + Box::pin(crate::ssh::sandbox_upload_planned( upload_plan, &effective_server, &sandbox_name, + Some(sandbox.object_id()), Path::new(local_path), dest, &effective_tls, @@ -5367,38 +5368,6 @@ fn git_filtered_upload_plan(local_path: &Path) -> Result { Ok(SandboxUploadPlan::GitAware { base_dir, files }) } -async fn sandbox_upload_planned( - plan: SandboxUploadPlan, - server: &str, - name: &str, - local_path: &Path, - sandbox_path: Option<&str>, - tls: &TlsOptions, - workspace: &str, -) -> Result> { - match plan { - SandboxUploadPlan::GitAware { base_dir, files } => { - sandbox_sync_up_files( - server, - name, - &base_dir, - &files, - local_path, - sandbox_path, - tls, - workspace, - ) - .await?; - Ok(None) - } - SandboxUploadPlan::Regular => { - sandbox_sync_up(server, name, local_path, sandbox_path, tls, workspace) - .await - .map(Some) - } - } -} - /// Upload a local path to a sandbox. /// /// Symlink sources, including dangling links, bypass Git-aware filtering so @@ -5420,10 +5389,11 @@ pub async fn sandbox_upload( dest_display ); - let uploaded_path = sandbox_upload_planned( + let uploaded_path = crate::ssh::sandbox_upload_planned( upload_plan, server, name, + None, local_path, sandbox_path, tls, diff --git a/crates/openshell-cli/src/ssh.rs b/crates/openshell-cli/src/ssh.rs index 5eb6738ddd..a61f781691 100644 --- a/crates/openshell-cli/src/ssh.rs +++ b/crates/openshell-cli/src/ssh.rs @@ -12,23 +12,24 @@ use crate::tls::{ use miette::{IntoDiagnostic, Report, Result, WrapErr}; #[cfg(unix)] use nix::sys::signal::Signal; -use openshell_core::driver_mounts; use openshell_core::forward::{ - ForwardSpec, build_proxy_command, format_gateway_url, resolve_ssh_gateway, sandbox_ssh_args, - shell_escape, validate_ssh_session_response, write_forward_pid, + ForwardSpec, format_gateway_url, resolve_ssh_gateway, sandbox_ssh_args, shell_escape, + supports_direct_ssh, validate_ssh_session_response, write_forward_pid, }; use openshell_core::proto::{ - CreateSshSessionRequest, GetSandboxRequest, SandboxPhase, SshRelayTarget, TcpForwardFrame, - TcpForwardInit, tcp_forward_init, + CreateSshSessionRequest, CreateSshSessionResponse, GetSandboxRequest, SandboxPhase, + SshRelayTarget, TcpForwardFrame, TcpForwardInit, tcp_forward_init, +}; +use openshell_core::ssh_handoff::{ + PreparedProxy, RelayAuthorization, SshAdmissionError, SshCleanup, SshTarget, }; use openshell_core::upload::{ DestinationKind as UploadDestinationKind, ExpectedDestination, UploadPlan, }; +use openshell_core::{ObjectId, driver_mounts}; use std::fs; use std::future::Future; use std::io::{IsTerminal, Write}; -#[cfg(unix)] -use std::os::unix::process::CommandExt; use std::path::{Path, PathBuf}; use std::process::{Command, ExitStatus, Stdio}; use std::sync::OnceLock; @@ -36,7 +37,6 @@ use std::time::{Duration, Instant}; use tokio::io::AsyncWriteExt; use tokio::process::{Child, Command as TokioCommand}; use tokio_stream::wrappers::ReceiverStream; -use tonic::Code; use tonic::metadata::AsciiMetadataValue; /// Time budget for the local listener to become reachable after `ssh` starts. @@ -51,7 +51,6 @@ const FORWARD_LISTENER_CONNECT_TIMEOUT: Duration = Duration::from_millis(200); /// Time budget for the supervisor relay to register after a fast canonical /// command has already reported its terminal result. const TERMINAL_RELAY_REGISTRATION_TIMEOUT: Duration = Duration::from_secs(5); -const TERMINAL_RELAY_REGISTRATION_INTERVAL: Duration = Duration::from_millis(50); /// An SSH client that remained alive for this long was attached successfully, /// rather than failing during initial authentication or setup. const CONNECT_ESTABLISHED_DURATION: Duration = Duration::from_secs(2); @@ -104,13 +103,15 @@ impl Editor { } struct SshSessionConfig { - proxy_command: String, - sandbox_id: String, - sandbox_name: String, - gateway_url: String, - token: String, + target: SshTarget, + client: GrpcClient, main_terminal: bool, - replica: Option, +} + +impl SshSessionConfig { + async fn prepare(&self) -> Result { + self.target.prepare(self.client.clone(), None).await + } } async fn ssh_session_config( @@ -118,97 +119,24 @@ async fn ssh_session_config( name: &str, tls: &TlsOptions, workspace: &str, - terminal_relay_registration_timeout: Option, ) -> Result { let mut client = grpc_client(server, tls).await?; - // Resolve the sandbox and retain its ID for local lifecycle tracking. - let response = client - .get_sandbox(with_owner_hint(GetSandboxRequest { - name: name.to_string(), - workspace_scope: Some(openshell_core::proto::workspace_selector( - (workspace).to_string(), - )), - })) - .await - .into_diagnostic()?; - let replica = owner_replica(&response); - let sandbox = response - .into_inner() - .sandbox - .ok_or_else(|| miette::miette!("sandbox not found"))?; - - let relay_registration_deadline = - terminal_relay_registration_timeout.map(|timeout| tokio::time::Instant::now() + timeout); - let response = loop { - match client - .create_ssh_session(CreateSshSessionRequest { - sandbox: name.to_string(), - workspace_scope: Some(openshell_core::proto::workspace_selector( - (workspace).to_string(), - )), - }) - .await - { - Ok(response) => break response, - Err(status) - if status.code() == Code::FailedPrecondition - && relay_registration_deadline - .is_some_and(|deadline| tokio::time::Instant::now() < deadline) => - { - tokio::time::sleep(TERMINAL_RELAY_REGISTRATION_INTERVAL).await; - } - Err(status) => return Err(status).into_diagnostic(), - } - }; - let session = response.into_inner(); - validate_ssh_session_response(&session) - .map_err(|err| miette::miette!("gateway returned invalid SSH session response: {err}"))?; - - let exe = std::env::current_exe() - .into_diagnostic() - .wrap_err("failed to resolve OpenShell executable")?; - let exe_command = exe.to_string_lossy().into_owned(); - - // When using Cloudflare bearer auth, the SSH CONNECT must go through the - // external tunnel endpoint (the cluster URL), not the server's internal - // scheme/host/port which may be plaintext HTTP on 127.0.0.1. - let gateway_url = if tls.is_bearer_auth() { - server.trim_end_matches('/').to_string() - } else { - // If the server returned a loopback gateway address, override it with the - // cluster endpoint's host. This handles the case where the server defaults - // to 127.0.0.1 but the cluster is actually running on a remote host. - #[allow(clippy::cast_possible_truncation)] - let gateway_port_u16 = session.gateway_port as u16; - let (gateway_scheme, gateway_host, gateway_port) = resolve_ssh_gateway( - &session.gateway_scheme, - &session.gateway_host, - gateway_port_u16, - server, - ); - format_gateway_url(&gateway_scheme, &gateway_host, gateway_port) - }; + let (sandbox, replica, direct_ssh) = lookup_ssh_sandbox(&mut client, name, workspace).await?; let gateway_name = tls .gateway_name() .ok_or_else(|| miette::miette!("gateway name is required to build SSH proxy command"))?; - let proxy_command = build_proxy_command( - &exe_command, - &gateway_url, - name, - workspace, - &session.token, - gateway_name, - ); - + let mut target = SshTarget::new(server, gateway_name, name, workspace, sandbox.object_id()); + target.direct_ssh = Some(direct_ssh); + target.gateway_insecure = tls.gateway_insecure; + target.replica = replica + .as_ref() + .and_then(|v| v.to_str().ok()) + .map(str::to_owned); Ok(SshSessionConfig { - proxy_command, - sandbox_id: session.sandbox_id.clone(), - sandbox_name: name.to_string(), - gateway_url, - token: session.token, + target, + client, main_terminal: sandbox.spec.as_ref().is_none_or(|spec| spec.tty), - replica, }) } @@ -238,21 +166,12 @@ fn ssh_base_command(proxy_command: &str) -> Command { command } -async fn exec_or_wait(command: Command, replace_process: bool) -> Result { - if replace_process && std::io::stdin().is_terminal() { - #[cfg(unix)] - { - let mut command = command; - let err = command.exec(); - return Err(miette::miette!("failed to exec ssh: {err}")); - } - } - +async fn wait_for_ssh(command: Command) -> Result { // Catch terminal signals in the parent while SSH receives the same signals // from the foreground process group. Unlike SIG_IGN, caught dispositions // reset to their defaults when the child execs, so SSH stays interruptible. #[cfg(unix)] - let mut signals = if !replace_process && std::io::stdin().is_terminal() { + let mut signals = if std::io::stdin().is_terminal() { Some(TerminationSignals::new()?) } else { None @@ -273,9 +192,9 @@ async fn exec_or_wait(command: Command, replace_process: bool) -> Result { Ok(process_exit_code(child.wait().await.into_diagnostic()?)) } -fn main_attach_command(session: &SshSessionConfig) -> Command { - let mut command = ssh_base_command(&session.proxy_command); - if session.main_terminal { +fn main_attach_command(proxy: &PreparedProxy, main_terminal: bool) -> Command { + let mut command = ssh_base_command(proxy.command()); + if main_terminal { command.arg("-tt").arg("-o").arg("RequestTTY=force"); } else { command.arg("-T"); @@ -292,11 +211,6 @@ fn main_attach_command(session: &SshSessionConfig) -> Command { command } -async fn run_main_attach(session: &SshSessionConfig, replace_process: bool) -> Result { - let command = main_attach_command(session); - exec_or_wait(command, replace_process).await -} - fn process_exit_code(status: ExitStatus) -> i32 { status.code().unwrap_or(1) } @@ -394,13 +308,13 @@ async fn terminate_and_reap_child(child: &mut Child, signal: Signal) -> Result Result { #[cfg(not(unix))] let _ = cancellation; - let mut command = TokioCommand::from(main_attach_command(session)); + let mut command = TokioCommand::from(command); command.kill_on_drop(true); let mut child = command.spawn().into_diagnostic()?; @@ -514,6 +428,9 @@ fn next_connect_retry_delay(delay: Duration) -> Duration { } fn connect_error_is_retryable(error: &Report) -> bool { + if let Some(error) = error.downcast_ref::() { + return error.is_retryable(); + } let message = format!("{error:?}").to_ascii_lowercase(); [ "broken pipe", @@ -542,7 +459,10 @@ async fn sandbox_connect_supervised( name: &str, tls: &TlsOptions, workspace: &str, + cleanup: &SshCleanup, ) -> Result { + let mut selected_id = None; + let mut require_direct = false; let mut recovery_deadline = None; let mut retry_delay = CONNECT_RETRY_INITIAL_DELAY; let mut cancellation = ConnectCancellation::new()?; @@ -555,14 +475,27 @@ async fn sandbox_connect_supervised( let session_attempt = match Box::pin(cancellation.wait(await_before_recovery_deadline( recovery_deadline, - ssh_session_config(server, name, tls, workspace, None), + async { + let mut session = ssh_session_config(server, name, tls, workspace).await?; + session.target.cleanup.clone_from(cleanup); + if selected_id.get_or_insert_with(|| session.target.id.clone()) + != &session.target.id + { + return Err(miette::miette!("sandbox was replaced before reconnecting")); + } + if require_direct && session.target.direct_ssh != Some(true) { + return Err(SshAdmissionError::CapabilityLost.into()); + } + require_direct = session.target.direct_ssh == Some(true); + Ok((session.prepare().await?, session.main_terminal)) + }, ))) .await { Ok(attempt) => attempt, Err(exit_code) => return Ok(exit_code), }; - let session = match session_attempt { + let (proxy, main_terminal) = match session_attempt { Err(()) => { print_connect_recovery_timeout(); return Ok(SSH_TRANSPORT_FAILURE_EXIT_CODE); @@ -589,10 +522,20 @@ async fn sandbox_connect_supervised( Ok(Err(error)) => return Err(error), }; - let attach_started = Instant::now(); - let exit_code = run_main_attach_supervised(&session, &mut cancellation).await?; - let attached_for = attach_started.elapsed(); + let command = main_attach_command(&proxy, main_terminal); + let ((exit_code, elapsed), revocation_wait) = proxy + .run_with_admission(async { + let started = Instant::now(); + let code = run_main_attach_supervised(command, &mut cancellation).await?; + Ok((code, started.elapsed())) + }) + .await?; let recovery_active = recovery_deadline.is_some(); + if revocation_wait.is_none() && !recovery_active { + return Ok(exit_code); + } + let attached_for = + revocation_wait.map_or(Duration::ZERO, |wait| elapsed.saturating_sub(wait)); let main_has_terminal_result = if exit_code == SSH_TRANSPORT_FAILURE_EXIT_CODE { match cancellation .wait(canonical_main_has_terminal_result( @@ -650,26 +593,6 @@ async fn sandbox_connect_supervised( } } -async fn sandbox_connect_with_mode( - server: &str, - name: &str, - tls: &TlsOptions, - replace_process: bool, - workspace: &str, - terminal_relay_registration_timeout: Option, -) -> Result { - let session = ssh_session_config( - server, - name, - tls, - workspace, - terminal_relay_registration_timeout, - ) - .await?; - - run_main_attach(&session, replace_process).await -} - /// Connect to a sandbox via SSH. pub async fn sandbox_connect( server: &str, @@ -677,7 +600,10 @@ pub async fn sandbox_connect( tls: &TlsOptions, workspace: &str, ) -> Result { - sandbox_connect_supervised(server, name, tls, workspace).await + let cleanup = SshCleanup::default(); + let result = sandbox_connect_supervised(server, name, tls, workspace, &cleanup).await; + cleanup.drain().await; + result } pub(crate) async fn sandbox_connect_without_exec( @@ -686,7 +612,10 @@ pub(crate) async fn sandbox_connect_without_exec( tls: &TlsOptions, workspace: &str, ) -> Result { - sandbox_connect_with_mode(server, name, tls, false, workspace, None).await + let session = ssh_session_config(server, name, tls, workspace).await?; + let proxy = session.prepare().await?; + let command = main_attach_command(&proxy, session.main_terminal); + proxy.run(wait_for_ssh(command)).await } pub(crate) async fn sandbox_connect_terminal_main( @@ -695,15 +624,13 @@ pub(crate) async fn sandbox_connect_terminal_main( tls: &TlsOptions, workspace: &str, ) -> Result { - sandbox_connect_with_mode( - server, - name, - tls, - false, - workspace, - Some(TERMINAL_RELAY_REGISTRATION_TIMEOUT), - ) - .await + let session = ssh_session_config(server, name, tls, workspace).await?; + let proxy = session + .target + .prepare(session.client, Some(TERMINAL_RELAY_REGISTRATION_TIMEOUT)) + .await?; + let command = main_attach_command(&proxy, session.main_terminal); + proxy.run(wait_for_ssh(command)).await } pub async fn sandbox_connect_editor( @@ -714,7 +641,7 @@ pub async fn sandbox_connect_editor( tls: &TlsOptions, workspace: &str, ) -> Result<()> { - let session = ssh_session_config(server, name, tls, workspace, None).await?; + let session = ssh_session_config(server, name, tls, workspace).await?; let workspace_root = discover_workspace_root(&session).await?; let host_alias = host_alias(name, workspace); @@ -743,14 +670,34 @@ pub async fn sandbox_forward( ) -> Result<()> { openshell_core::forward::check_port_available(spec)?; - let session = ssh_session_config(server, name, tls, workspace, None).await?; + let session = ssh_session_config(server, name, tls, workspace).await?; - let mut command = TokioCommand::from(ssh_forward_command( - &session.proxy_command, - &session.sandbox_id, + let proxy = session.prepare().await?; + let command = TokioCommand::from(ssh_forward_command( + proxy.command(), + &session.target.id, spec, )); + proxy + .run(run_forward( + command, + name, + workspace, + &session.target.id, + spec, + background, + )) + .await +} +async fn run_forward( + mut command: TokioCommand, + name: &str, + workspace: &str, + sandbox_id: &str, + spec: &ForwardSpec, + background: bool, +) -> Result<()> { if background { command .kill_on_drop(false) @@ -765,30 +712,34 @@ pub async fn sandbox_forward( } let port = spec.port; + let mut cancellation = ConnectCancellation::new()?; + let mut child = command.spawn().into_diagnostic()?; + let readiness = cancellation + .wait(wait_for_forward_start(&mut child, spec)) + .await + .unwrap_or_else(|_| Err(miette::miette!("forward interrupted"))); + if let Err(error) = readiness { + terminate_owned_forward_child(&mut child).await; + return if background { + Err(error).wrap_err("ssh process started but local forward listener was not reachable") + } else { + Err(error) + }; + } if background { - let mut child = command.spawn().into_diagnostic()?; let Some(pid) = child.id() else { terminate_owned_forward_child(&mut child).await; return Err(miette::miette!( "ssh process did not expose a PID for background tracking" )); }; - - if let Err(err) = wait_for_forward_start(&mut child, spec) - .await - .wrap_err("ssh process started but local forward listener was not reachable") - { - terminate_owned_forward_child(&mut child).await; - return Err(err); - } - let tracked = track_background_forward_or_cleanup( workspace, name, port, pid, - &session.sandbox_id, + sandbox_id, &spec.bind_addr, || { let _ = child.start_kill(); @@ -801,16 +752,12 @@ pub async fn sandbox_forward( return Ok(()); } - let status = { - let mut child = command.spawn().into_diagnostic()?; - if let Err(err) = wait_for_forward_start(&mut child, spec).await { - terminate_owned_forward_child(&mut child).await; - return Err(err); - } - eprintln!("{}", foreground_forward_started_message(name, spec)); - child.wait().await.into_diagnostic()? + eprintln!("{}", foreground_forward_started_message(name, spec)); + let Ok(status) = cancellation.wait(child.wait()).await else { + terminate_owned_forward_child(&mut child).await; + return Err(miette::miette!("forward interrupted")); }; - + let status = status.into_diagnostic()?; if !status.success() { return Err(miette::miette!("ssh exited with status {status}")); } @@ -980,21 +927,29 @@ fn foreground_forward_started_message(name: &str, spec: &ForwardSpec) -> String ) } -async fn sandbox_exec_with_mode( +/// Exit status returned by a sandbox command run through OpenSSH. +#[derive(Debug, thiserror::Error, miette::Diagnostic)] +#[error("ssh exited with status {code}")] +pub struct SshCommandExit { + pub code: i32, +} + +/// Execute a sandbox command and return a `SshCommandExit` on a nonzero exit. +pub async fn sandbox_exec( server: &str, name: &str, command: &[String], tty: bool, tls: &TlsOptions, - replace_process: bool, workspace: &str, ) -> Result<()> { if command.is_empty() { return Err(miette::miette!("no command provided")); } - let session = ssh_session_config(server, name, tls, workspace, None).await?; - let mut ssh = ssh_base_command(&session.proxy_command); + let session = ssh_session_config(server, name, tls, workspace).await?; + let proxy = session.prepare().await?; + let mut ssh = ssh_base_command(proxy.command()); if tty { ssh.arg("-tt") @@ -1018,23 +973,13 @@ async fn sandbox_exec_with_mode( .stdout(Stdio::inherit()) .stderr(Stdio::inherit()); - exec_or_wait(ssh, tty && replace_process).await?; - + let code = proxy.run(wait_for_ssh(ssh)).await?; + if code != 0 { + return Err(Report::new(SshCommandExit { code })); + } Ok(()) } -/// Execute a command in a sandbox via SSH. -pub async fn sandbox_exec( - server: &str, - name: &str, - command: &[String], - tty: bool, - tls: &TlsOptions, - workspace: &str, -) -> Result<()> { - sandbox_exec_with_mode(server, name, command, tty, tls, true, workspace).await -} - /// What to pack into the tar archive streamed to the sandbox. #[derive(Clone)] enum UploadSource { @@ -1247,14 +1192,10 @@ fn build_upload_extract_cmd( /// placing the source inside a directory and renaming it. File-list uploads /// retain their directory-only placement and return that directory. async fn ssh_tar_upload( - server: &str, - name: &str, + session: &SshSessionConfig, dest: Option<&str>, mut source: UploadSource, - tls: &TlsOptions, - workspace: &str, ) -> Result { - let session = ssh_session_config(server, name, tls, workspace, None).await?; let mut dest_dir = dest.unwrap_or("."); let expected_destination = if let Some(path) = dest && let UploadSource::SinglePath { @@ -1264,7 +1205,7 @@ async fn ssh_tar_upload( && local_upload_path_is_file_like(local_path) && file_upload_destination_needs_probe(path) { - let output = ssh_run_capture_stdout(&session, &build_upload_destination_probe_cmd(path)) + let output = ssh_run_capture_stdout(session, &build_upload_destination_probe_cmd(path)) .await .map_err(|error| { if sync_error_is_retryable(&error) { @@ -1294,7 +1235,8 @@ async fn ssh_tar_upload( UploadSource::FileList { .. } => dest_dir.to_string(), }; - let ssh = ssh_upload_command(&session.proxy_command); + let proxy = session.prepare().await?; + let ssh = ssh_upload_command(proxy.command()); let plan = UploadPlan { destination_directory: dest_dir.to_string(), expected_destination: expected_destination.map(|(path, kind)| ExpectedDestination { @@ -1302,11 +1244,15 @@ async fn ssh_tar_upload( kind, }), }; - upload::run(ssh, plan, move |writer| { - write_upload_archive(writer, source) - }) - .await - .map_err(Report::new)?; + proxy + .run(async move { + upload::run(ssh, plan, move |writer| { + write_upload_archive(writer, source) + }) + .await + .map_err(Report::new) + }) + .await?; Ok(final_path) } @@ -1502,18 +1448,19 @@ pub async fn sandbox_sync_up_files( tls: &TlsOptions, workspace: &str, ) -> Result<()> { - if files.is_empty() { - return Ok(()); - } - let source = UploadSource::FileList { - base_dir: base_dir.to_path_buf(), - files: files.to_vec(), - archive_prefix: file_list_archive_prefix(local_path), - }; - retry_sandbox_upload(|| { - let source = source.clone(); - async move { ssh_tar_upload(server, name, dest, source, tls, workspace).await } - }) + sandbox_upload_planned( + crate::run::SandboxUploadPlan::GitAware { + base_dir: base_dir.to_owned(), + files: files.to_vec(), + }, + server, + name, + None, + local_path, + dest, + tls, + workspace, + ) .await .map(|_| ()) } @@ -1532,6 +1479,19 @@ pub async fn sandbox_sync_up( tls: &TlsOptions, workspace: &str, ) -> Result { + upload_source( + server, + name, + sandbox_path, + path_upload_source(local_path)?, + tls, + workspace, + None, + ) + .await +} + +fn path_upload_source(local_path: &Path) -> Result { let local_path_is_file_like = local_upload_path_is_file_like(local_path); let tar_name = if local_path_is_file_like { local_path @@ -1546,15 +1506,67 @@ pub async fn sandbox_sync_up( directory_upload_prefix(local_path) }; - let source = UploadSource::SinglePath { - local_path: local_path.to_path_buf(), + Ok(UploadSource::SinglePath { + local_path: local_path.to_owned(), tar_name, + }) +} + +#[allow(clippy::too_many_arguments)] +pub(crate) async fn sandbox_upload_planned( + plan: crate::run::SandboxUploadPlan, + server: &str, + name: &str, + expected_id: Option<&str>, + local_path: &Path, + dest: Option<&str>, + tls: &TlsOptions, + workspace: &str, +) -> Result> { + use crate::run::SandboxUploadPlan; + let source = match plan { + SandboxUploadPlan::GitAware { files, .. } if files.is_empty() => return Ok(None), + SandboxUploadPlan::GitAware { base_dir, files } => UploadSource::FileList { + base_dir, + files, + archive_prefix: file_list_archive_prefix(local_path), + }, + SandboxUploadPlan::Regular => path_upload_source(local_path)?, }; - retry_sandbox_upload(|| { - let source = source.clone(); - async move { ssh_tar_upload(server, name, sandbox_path, source, tls, workspace).await } + let single_path = matches!(source, UploadSource::SinglePath { .. }); + let uploaded = upload_source(server, name, dest, source, tls, workspace, expected_id).await?; + Ok(single_path.then_some(uploaded)) +} + +async fn upload_source( + server: &str, + name: &str, + dest: Option<&str>, + source: UploadSource, + tls: &TlsOptions, + workspace: &str, + expected_id: Option<&str>, +) -> Result { + let selected = tokio::sync::OnceCell::new(); + let result = retry_sandbox_upload(|| async { + let session = selected + .get_or_try_init(|| async { + let selected = ssh_session_config(server, name, tls, workspace).await?; + if expected_id.is_some_and(|id| id != selected.target.id) { + return Err(miette::miette!( + "sandbox was replaced before uploading files" + )); + } + Ok::<_, Report>(selected) + }) + .await?; + ssh_tar_upload(session, dest, source.clone()).await }) - .await + .await; + if let Some(session) = selected.get() { + session.target.cleanup.drain().await; + } + result } /// Compute the tar entry prefix for a directory upload. @@ -1588,7 +1600,12 @@ fn file_list_archive_prefix(local_path: &Path) -> Option { /// file or a directory before streaming the tar archive. Stderr is inherited /// so the user still sees any diagnostic output from ssh itself. async fn ssh_run_capture_stdout(session: &SshSessionConfig, command: &str) -> Result { - let mut ssh = ssh_base_command(&session.proxy_command); + let proxy = session.prepare().await?; + let ssh = ssh_base_command(proxy.command()); + proxy.run(run_ssh_probe(ssh, command)).await +} + +async fn run_ssh_probe(mut ssh: Command, command: &str) -> Result { ssh.arg("-T") .arg("-o") .arg("RequestTTY=no") @@ -1694,28 +1711,35 @@ pub async fn sandbox_sync_down( tls: &TlsOptions, workspace: &str, ) -> Result<()> { - retry_sandbox_sync("download", || async { - sandbox_sync_down_once(server, name, sandbox_path, dest, tls, workspace).await - }) - .await + let selected = tokio::sync::OnceCell::new(); + let mut cancellation = ConnectCancellation::new()?; + let result = cancellation + .wait(retry_sandbox_sync("download", || async { + let session = selected + .get_or_try_init(|| ssh_session_config(server, name, tls, workspace)) + .await?; + Box::pin(sandbox_sync_down_once(session, sandbox_path, dest)).await + })) + .await + .unwrap_or_else(|_| Err(miette::miette!("download interrupted"))); + if let Some(session) = selected.get() { + session.target.cleanup.drain().await; + } + result } async fn sandbox_sync_down_once( - server: &str, - name: &str, + session: &SshSessionConfig, sandbox_path: &str, dest: &str, - tls: &TlsOptions, - workspace: &str, ) -> Result<()> { - let session = ssh_session_config(server, name, tls, workspace, None).await?; - let sandbox_path = resolve_sandbox_source_path(&session, sandbox_path).await?; - let kind = probe_sandbox_source_kind(&session, &sandbox_path).await?; + let sandbox_path = resolve_sandbox_source_path(session, sandbox_path).await?; + let kind = probe_sandbox_source_kind(session, &sandbox_path).await?; match kind { - SandboxSourceKind::File => sandbox_sync_down_file(&session, &sandbox_path, dest).await, + SandboxSourceKind::File => sandbox_sync_down_file(session, &sandbox_path, dest).await, SandboxSourceKind::Directory => { - sandbox_sync_down_directory(&session, &sandbox_path, dest).await + sandbox_sync_down_directory(session, &sandbox_path, dest).await } } } @@ -1765,6 +1789,9 @@ where } fn sync_error_is_retryable(error: &Report) -> bool { + if let Some(error) = error.downcast_ref::() { + return error.is_retryable(); + } if let Some(error) = error.downcast_ref::() { return error.is_retryable(); } @@ -1798,45 +1825,71 @@ async fn stream_sandbox_tar( tar_cmd: String, extract_into: &Path, ) -> Result<()> { - let mut ssh = ssh_base_command(&session.proxy_command); + let proxy = session.prepare().await?; + let ssh = ssh_base_command(proxy.command()); + proxy + .run(extract_ssh_tar( + ssh, + tar_cmd, + extract_into, + &session.target.cleanup, + )) + .await +} + +async fn extract_ssh_tar( + mut ssh: Command, + tar_cmd: String, + extract_into: &Path, + cleanup: &SshCleanup, +) -> Result<()> { + let (reader, writer) = std::io::pipe().into_diagnostic()?; ssh.arg("-T") .arg("-o") .arg("RequestTTY=no") .arg("sandbox") .arg(tar_cmd) .stdin(Stdio::null()) - .stdout(Stdio::piped()) .stderr(Stdio::inherit()); - - let mut child = ssh.spawn().into_diagnostic()?; - let stdout = child - .stdout - .take() - .ok_or_else(|| miette::miette!("failed to open stdout for ssh process"))?; - + let mut child = TokioCommand::from(ssh) + .stdout(writer) + .kill_on_drop(true) + .spawn() + .into_diagnostic()?; let extract_into = extract_into.to_path_buf(); - tokio::task::spawn_blocking(move || -> Result<()> { - let mut archive = tar::Archive::new(stdout); - archive - .unpack(&extract_into) + let mut unpack = tokio::task::spawn_blocking(move || { + tar::Archive::new(reader) + .unpack(extract_into) .into_diagnostic() - .wrap_err("failed to extract tar archive from sandbox")?; - Ok(()) - }) - .await - .into_diagnostic()??; - - let status = tokio::task::spawn_blocking(move || child.wait()) - .await - .into_diagnostic()? - .into_diagnostic()?; + .wrap_err("failed to extract tar archive from sandbox") + }); - if !status.success() { - return Err(miette::miette!( - "ssh tar create exited with status {status}" - )); - } - Ok(()) + // The blocking tar reader can only stop when the SSH writer closes. + // Keep both owned even if the caller drops this transfer on a signal. + let (cancel, cancelled) = tokio::sync::oneshot::channel::<()>(); + let worker = cleanup.spawn(async move { + let result = tokio::select! { + _ = cancelled => Err(miette::miette!("download interrupted")), + result = async { + (&mut unpack).await.into_diagnostic()??; + let status = child.wait().await.into_diagnostic()?; + if !status.success() { + return Err(miette::miette!("ssh tar create exited with status {status}")); + } + Ok(()) + } => result, + }; + if result.is_err() { + let _ = child.kill().await; + if !unpack.is_finished() { + let _ = unpack.await; + } + } + result + }); + let result = worker.await.into_diagnostic()?; + drop(cancel); + result } /// Build the `tar cf - -C -- ` command used to wrap a @@ -1955,51 +2008,183 @@ async fn sandbox_sync_down_directory( stream_sandbox_tar(session, tar_cmd, dest_path).await } -/// Run the SSH proxy, connecting stdin/stdout to the gateway. -pub async fn sandbox_ssh_proxy( - gateway_url: &str, - sandbox_name: &str, +async fn lookup_ssh_sandbox( + client: &mut GrpcClient, + name: &str, workspace: &str, - token: &str, +) -> Result<( + openshell_core::proto::Sandbox, + Option, + bool, +)> { + let response = client + .get_sandbox(with_owner_hint(GetSandboxRequest { + name: name.to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + (workspace).to_string(), + )), + })) + .await + .map_err(SshAdmissionError::Rpc)?; + let replica = owner_replica(&response); + let direct_ssh = supports_direct_ssh(&response)?; + let sandbox = response + .into_inner() + .sandbox + .ok_or_else(|| miette::miette!("sandbox not found"))?; + + Ok((sandbox, replica, direct_ssh)) +} + +/// Connect a saved SSH profile to the sandbox selected by this invocation. +pub async fn sandbox_ssh_proxy_by_name( + server: &str, + name: &str, tls: &TlsOptions, + workspace: &str, ) -> Result<()> { - let server = grpc_server_from_ssh_gateway_url(gateway_url)?; - let mut client = grpc_client(&server, tls).await?; - - let replica = client - .get_sandbox(with_owner_hint(GetSandboxRequest { - name: sandbox_name.to_string(), + let mut client = grpc_client(server, tls).await?; + let (sandbox, replica, direct_ssh) = lookup_ssh_sandbox(&mut client, name, workspace).await?; + let mut cancellation = ConnectCancellation::new()?; + if direct_ssh { + return cancellation + .wait(async { + let relay = open_direct_ssh( + &mut client, + name, + workspace, + sandbox.object_id(), + replica.as_ref(), + None, + ) + .await?; + relay_ssh_proxy(relay).await + }) + .await + .map_err(|_| miette::miette!("SSH proxy interrupted"))?; + } + let session = cancellation + .wait(client.create_ssh_session(CreateSshSessionRequest { + sandbox: name.to_string(), workspace_scope: Some(openshell_core::proto::workspace_selector( workspace.to_string(), )), })) .await - .ok() - .and_then(|response| owner_replica(&response)); - relay_ssh_proxy(client, sandbox_name, workspace, token, replica.as_ref()).await + .map_err(|_| miette::miette!("SSH proxy interrupted"))? + .into_diagnostic()? + .into_inner(); + let opened = cancellation + .wait(async { + if sandbox.object_id() != session.sandbox_id { + return Err(miette::miette!( + "sandbox was replaced before opening the SSH relay" + )); + } + open_ssh_relay(server, name, tls, workspace, &session, replica.as_ref()).await + }) + .await; + // ForwardTcp authenticates its first frame. Revoke even on a failed open, + // before a long-lived forward or a killed SSH process can strand the grant. + openshell_core::ssh_handoff::revoke_grant(client, session.token).await; + let relay = opened.map_err(|_| miette::miette!("SSH proxy interrupted"))??; + cancellation + .wait(relay_ssh_proxy(relay)) + .await + .map_err(|_| miette::miette!("SSH proxy interrupted"))? } -async fn relay_ssh_proxy( - mut client: GrpcClient, - sandbox_name: &str, +pub async fn relay_prepared_ssh( + grant: openshell_core::ssh_handoff::RelayGrant, + mut peer: impl tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin, + name: &str, workspace: &str, - token: &str, - replica: Option<&AsciiMetadataValue>, + tls: &TlsOptions, ) -> Result<()> { - let init = TcpForwardFrame { - payload: Some(openshell_core::proto::tcp_forward_frame::Payload::Init( - TcpForwardInit { - sandbox: sandbox_name.to_string(), - workspace: (workspace).to_string(), - service_id: format!("ssh-proxy:{sandbox_name}"), - target: Some(tcp_forward_init::Target::Ssh(SshRelayTarget {})), - authorization_token: token.to_string(), - }, - )), + use tokio::io::AsyncReadExt; + let replica = grant + .replica + .as_deref() + .map(str::parse) + .transpose() + .into_diagnostic()?; + let direct = matches!(&grant.authorization, Some(RelayAuthorization::Direct(_))); + let open = async { + match grant + .authorization + .ok_or_else(|| miette::miette!("missing SSH relay authorization"))? + { + RelayAuthorization::Session(session) => { + open_ssh_relay( + &grant.endpoint, + name, + tls, + workspace, + &session, + replica.as_ref(), + ) + .await + } + RelayAuthorization::Direct(direct) => { + let mut tls = tls.clone(); + tls.gateway_insecure = direct.gateway_insecure; + let mut client = grpc_client(&grant.endpoint, &tls).await?; + open_direct_ssh( + &mut client, + name, + workspace, + &direct.sandbox_id, + replica.as_ref(), + direct.registration_timeout()?, + ) + .await + } + } + }; + let opened = tokio::select! { + result = open => result, + _ = peer.read_u8() => return Err(miette::miette!("SSH handoff closed before relay admission")), + }; + let result = match opened { + Ok(relay) => { + notify_ssh_issuer(&mut peer, 1).await?; + if !direct { + drop(peer); + return relay_ssh_proxy(relay).await; + } + relay_ssh_proxy(relay).await + } + Err(error) => Err(error), }; - let (tx, response) = open_forward_tcp(&mut client, init, replica).await; - let mut response = response.into_diagnostic()?.into_inner(); + if direct + && let Err(error) = &result + && error + .downcast_ref::() + .is_some_and(|rpc| !rpc.is_retryable()) + { + let _ = notify_ssh_issuer(&mut peer, openshell_core::ssh_handoff::DIRECT_SSH_REFUSED).await; + } + result +} + +async fn notify_ssh_issuer( + peer: &mut (impl tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin), + reply: u8, +) -> Result<()> { + use tokio::io::AsyncReadExt; + peer.write_u8(reply).await.into_diagnostic()?; + if peer.read_u8().await.into_diagnostic()? != 1 { + return Err(miette::miette!("invalid SSH handoff acknowledgement")); + } + Ok(()) +} +type SshRelay = ( + tokio::sync::mpsc::Sender, + tonic::Streaming, +); + +async fn relay_ssh_proxy((tx, mut response): SshRelay) -> Result<()> { let stdout = tokio::io::stdout(); // Tokio stdin uses an uncancellable read on the runtime's blocking pool. @@ -2046,7 +2231,7 @@ async fn relay_ssh_proxy( let frame = match response.message().await { Ok(Some(frame)) => frame, Ok(None) => return Ok::<_, Report>(()), - Err(error) => return Err(error).into_diagnostic(), + Err(status) => return Err(SshAdmissionError::Rpc(status).into()), }; let Some(openshell_core::proto::tcp_forward_frame::Payload::Data(data)) = frame.payload else { @@ -2091,64 +2276,142 @@ pub(crate) async fn open_forward_tcp( } } -fn grpc_server_from_ssh_gateway_url(gateway_url: &str) -> Result { - let url: url::Url = gateway_url - .parse() - .into_diagnostic() - .wrap_err("invalid gateway URL")?; - let scheme = url.scheme(); - let gateway_host = url - .host_str() - .ok_or_else(|| miette::miette!("gateway URL missing host"))?; - let gateway_port = url - .port_or_known_default() - .ok_or_else(|| miette::miette!("gateway URL missing port"))?; - Ok(format_gateway_url(scheme, gateway_host, gateway_port)) -} - -/// Run the SSH proxy in "name mode": create a session on the fly, then proxy. -/// -/// This is equivalent to [`sandbox_ssh_proxy`] but accepts a cluster endpoint -/// and sandbox name instead of pre-created gateway/token credentials. It is -/// suitable for use as an SSH `ProxyCommand` in `~/.ssh/config` because it -/// creates a fresh session on every invocation. -pub async fn sandbox_ssh_proxy_by_name( +async fn open_ssh_relay( server: &str, name: &str, tls: &TlsOptions, workspace: &str, -) -> Result<()> { - let session = ssh_session_config(server, name, tls, workspace, None).await?; - let server = grpc_server_from_ssh_gateway_url(&session.gateway_url)?; - let client = grpc_client(&server, tls).await?; - relay_ssh_proxy( - client, - &session.sandbox_name, + session: &CreateSshSessionResponse, + replica: Option<&AsciiMetadataValue>, +) -> Result { + validate_ssh_session_response(session) + .map_err(|err| miette::miette!("gateway returned invalid SSH session response: {err}"))?; + // When using Cloudflare bearer auth, the SSH CONNECT must go through the + // external tunnel endpoint (the cluster URL), not the server's internal + // scheme/host/port which may be plaintext HTTP on 127.0.0.1. + let gateway_url = if tls.is_bearer_auth() { + server.to_string() + } else { + // If the server returned a loopback gateway address, override it with the + // cluster endpoint's host. This handles the case where the server defaults + // to 127.0.0.1 but the cluster is actually running on a remote host. + #[allow(clippy::cast_possible_truncation)] + let gateway_port_u16 = session.gateway_port as u16; + let (gateway_scheme, gateway_host, gateway_port) = resolve_ssh_gateway( + &session.gateway_scheme, + &session.gateway_host, + gateway_port_u16, + server, + ); + format_gateway_url(&gateway_scheme, &gateway_host, gateway_port) + }; + let mut client = grpc_client(&gateway_url, tls).await?; + let owner = match replica { + Some(owner) => Some(owner.clone()), + None => lookup_ssh_sandbox(&mut client, name, workspace) + .await + .ok() + .and_then(|(_, owner, _)| owner), + }; + open_ssh_stream( + &mut client, + name, workspace, + tcp_forward_init::Target::Ssh(SshRelayTarget {}), &session.token, - session.replica.as_ref(), + owner.as_ref(), ) .await + .into_diagnostic() +} + +async fn open_direct_ssh( + client: &mut GrpcClient, + name: &str, + workspace: &str, + sandbox_id: &str, + replica: Option<&AsciiMetadataValue>, + registration_timeout: Option, +) -> Result { + openshell_core::forward::validate_ssh_sandbox_id(sandbox_id).into_diagnostic()?; + let started = Instant::now(); + loop { + let target = tcp_forward_init::Target::DirectSshSandboxId(sandbox_id.to_owned()); + match open_ssh_stream(client, name, workspace, target, "", replica).await { + Err(status) + if status.code() == tonic::Code::FailedPrecondition + && status.message() == "sandbox is not ready" + && registration_timeout.is_some_and(|timeout| started.elapsed() < timeout) => + { + tokio::time::sleep(Duration::from_millis(50)).await; + } + result => return result.map_err(|status| Report::new(SshAdmissionError::Rpc(status))), + } + } +} + +async fn open_ssh_stream( + client: &mut GrpcClient, + name: &str, + workspace: &str, + target: tcp_forward_init::Target, + token: &str, + replica: Option<&AsciiMetadataValue>, +) -> std::result::Result { + let init = TcpForwardFrame { + payload: Some(openshell_core::proto::tcp_forward_frame::Payload::Init( + TcpForwardInit { + sandbox: name.to_string(), + workspace: workspace.to_string(), + service_id: format!("ssh-proxy:{name}"), + target: Some(target), + authorization_token: token.to_owned(), + }, + )), + }; + let (tx, response) = open_forward_tcp(client, init, replica).await; + Ok((tx, response?.into_inner())) } fn host_alias(name: &str, workspace: &str) -> String { format!("openshell-{name}.{workspace}") } -fn render_ssh_config(gateway: &str, name: &str, workspace: &str) -> String { - let exe = std::env::current_exe().expect("failed to resolve OpenShell executable"); - let exe = shell_escape(&exe.to_string_lossy()); - +fn render_ssh_config(gateway: &str, name: &str, workspace: &str) -> Result { + let exe = std::env::current_exe().into_diagnostic()?; + let (selector, target) = match gateway.split_once("://") { + Some((scheme, rest)) + if (scheme.eq_ignore_ascii_case("http") || scheme.eq_ignore_ascii_case("https")) + && !rest.contains('@') + && rest + .strip_suffix('/') + .unwrap_or(rest) + .parse::() + .is_ok() => + { + ( + "--server", + format!("{}://{rest}", scheme.to_ascii_lowercase()), + ) + } + None if !gateway.contains(['/', '\r', '\n']) => ("--gateway-name", gateway.to_owned()), + _ => { + return Err(miette::miette!( + "A saved SSH configuration needs a named gateway profile for this private endpoint. Register the endpoint with `openshell gateway add --name `." + )); + } + }; let proxy_cmd = format!( - "{exe} ssh-proxy --gateway-name {} --name {} --workspace {}", - shell_escape(gateway), - shell_escape(name), - shell_escape(workspace), + "{} ssh-proxy {selector} {} --name {} --workspace {}", + shell_escape(&exe.to_string_lossy()).replace('%', "%%"), + shell_escape(&target).replace('%', "%%"), + shell_escape(name).replace('%', "%%"), + shell_escape(workspace).replace('%', "%%"), ); let host_alias = host_alias(name, workspace); - format!( + Ok(format!( "Host {host_alias}\n User sandbox\n StrictHostKeyChecking no\n UserKnownHostsFile /dev/null\n GlobalKnownHostsFile /dev/null\n LogLevel ERROR\n ServerAliveInterval 15\n ServerAliveCountMax 3\n ProxyCommand {proxy_cmd}\n" - ) + )) } fn openshell_ssh_config_path() -> Result { @@ -2272,6 +2535,7 @@ fn upsert_host_block(contents: &str, alias: &str, block: &str) -> String { } pub fn install_ssh_config(gateway: &str, name: &str, workspace: &str) -> Result { + let block = render_ssh_config(gateway, name, workspace)?; let managed_config = openshell_ssh_config_path()?; let main_config = user_ssh_config_path()?; ensure_openshell_include(&main_config, &managed_config)?; @@ -2281,7 +2545,6 @@ pub fn install_ssh_config(gateway: &str, name: &str, workspace: &str) -> Result< } let alias = host_alias(name, workspace); - let block = render_ssh_config(gateway, name, workspace); let contents = fs::read_to_string(&managed_config).unwrap_or_default(); let updated = upsert_host_block(&contents, &alias, &block); fs::write(&managed_config, updated) @@ -2334,13 +2597,13 @@ fn launch_editor_command( /// The `ProxyCommand` uses `--gateway-name` so that `ssh-proxy` resolves the /// gateway endpoint and TLS certificates from the gateway metadata directory /// (`~/.config/openshell/gateways//mtls/`). -pub fn print_ssh_config(gateway: &str, name: &str, workspace: &str) { - print!("{}", render_ssh_config(gateway, name, workspace)); +pub fn print_ssh_config(gateway: &str, name: &str, workspace: &str) -> Result<()> { + print!("{}", render_ssh_config(gateway, name, workspace)?); + Ok(()) } #[cfg(test)] mod tests { - #[test] fn ssh_verbosity_reaches_nested_proxy_commands_and_respects_override() { for override_level in [None, Some("INFO")] { @@ -2398,7 +2661,7 @@ mod tests { .enable_all() .build() .unwrap(); - assert_eq!(runtime.block_on(exec_or_wait(command, false)).unwrap(), 1); + assert_eq!(runtime.block_on(wait_for_ssh(command)).unwrap(), 1); } #[cfg(target_os = "linux")] @@ -2406,6 +2669,7 @@ mod tests { fn interactive_wait_survives_terminal_signals_and_reaps_child() { use nix::sys::signal::killpg; use nix::unistd::Pid; + use std::os::unix::process::CommandExt; struct Probe(std::process::Child); impl Drop for Probe { @@ -2526,6 +2790,43 @@ mod tests { ))); } + #[cfg(unix)] + #[tokio::test] + async fn cancelled_download_reaps_ssh_while_the_tar_reader_is_blocked() { + let dir = tempfile::tempdir().unwrap(); + let marker = dir.path().join("ssh.pid"); + let mut ssh = Command::new("sh"); + ssh.args(["-c", "printf '%s' $$ > \"$1\"; exec sleep 5", "ssh"]) + .arg(&marker); + let cleanup = SshCleanup::default(); + let owner = cleanup.clone(); + let dest = dir.path().to_owned(); + let transfer = + tokio::spawn(async move { extract_ssh_tar(ssh, String::new(), &dest, &owner).await }); + let pid = tokio::time::timeout(Duration::from_secs(2), async { + loop { + if let Some(pid) = fs::read_to_string(&marker) + .ok() + .and_then(|pid| pid.parse::().ok()) + { + break nix::unistd::Pid::from_raw(pid); + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .unwrap(); + transfer.abort(); + assert!(transfer.await.unwrap_err().is_cancelled()); + tokio::time::timeout(Duration::from_secs(2), cleanup.drain()) + .await + .unwrap(); + assert_eq!( + nix::sys::signal::kill(pid, None), + Err(nix::errno::Errno::ESRCH) + ); + } + #[cfg(unix)] #[test] fn upload_cancellation_covers_retry_delay_and_setup() { @@ -2556,16 +2857,9 @@ mod tests { let setup = phase == "setup"; async move { if setup { - let session = SshSessionConfig { - proxy_command: String::new(), - sandbox_id: String::new(), - sandbox_name: String::new(), - gateway_url: String::new(), - token: String::new(), - main_terminal: false, - replica: None, - }; - return ssh_run_capture_stdout(&session, "unused").await.map(|_| ()); + return run_ssh_probe(ssh_base_command(""), "unused") + .await + .map(|_| ()); } let mut command = Command::new("sh"); command.args(["-c", "exit 255"]); @@ -2733,6 +3027,11 @@ mod tests { #[test] fn connect_retry_filter_rejects_authentication_failures() { + let denied = Report::new(SshAdmissionError::Rpc(tonic::Status::permission_denied( + "connection unavailable", + ))); + assert!(!connect_error_is_retryable(&denied)); + assert!(!sync_error_is_retryable(&denied)); let transient = miette::miette!("transport error: connection reset by peer"); assert!(connect_error_is_retryable(&transient)); @@ -2796,7 +3095,8 @@ mod tests { #[test] fn render_ssh_config_includes_workspace_in_proxy_command() { - let config = render_ssh_config("my-gw", "demo", "beta"); + let config = render_ssh_config("my-gw", "demo", "beta").unwrap(); + assert!(config.contains("--gateway-name my-gw")); assert!( config.contains("Host openshell-demo.beta"), "host alias should be workspace-qualified: {config}" @@ -2807,6 +3107,36 @@ mod tests { ); } + #[test] + fn ssh_config_only_saves_direct_http_origins() { + for scheme in ["http", "https", "HTTP", "HtTpS"] { + for suffix in [ + "user:pw@gw", + "gw/private/..", + "gw/?key=value", + "gw/#private", + "gw\\private", + ] { + let endpoint = format!("{scheme}://{suffix}"); + let err = render_ssh_config(&endpoint, "demo", "beta").unwrap_err(); + assert!(!err.to_string().contains(&endpoint)); + } + let endpoint = format!("{scheme}://[::1]:8443/"); + let config = render_ssh_config(&endpoint, "demo", "beta").unwrap(); + assert!(config.contains(&format!( + "--server {}", + shell_escape(&endpoint.to_ascii_lowercase()) + ))); + } + for endpoint in [ + " https://user:pw@gw", + "unknown://user:pw@gw", + "https:/private", + ] { + assert!(render_ssh_config(endpoint, "demo", "beta").is_err()); + } + } + #[test] fn host_alias_includes_workspace() { assert_eq!(host_alias("demo", "default"), "openshell-demo.default"); diff --git a/crates/openshell-cli/tests/sandbox_create_lifecycle_integration.rs b/crates/openshell-cli/tests/sandbox_create_lifecycle_integration.rs index 6608e54b96..3308c49b17 100644 --- a/crates/openshell-cli/tests/sandbox_create_lifecycle_integration.rs +++ b/crates/openshell-cli/tests/sandbox_create_lifecycle_integration.rs @@ -77,7 +77,10 @@ struct SandboxState { provisional_container_exit_sent: Arc, ssh_session_failures_remaining: Arc, ssh_session_requests: Arc, + ssh_requests_with_cached_bearer: Arc, + replace_after_first_ssh_revoke: Arc, ssh_session_revocations: Arc, + revoked_ssh_tokens: Arc>>, /// Reject token-less `ForwardTcp` inits the way a gateway that predates /// principal-authorized TCP forwards does. forward_requires_session_token: Arc, @@ -93,6 +96,17 @@ struct SandboxState { template_delete_requests: Arc>>, } +impl SandboxState { + fn ssh_sandbox_id(&self, name: &str) -> String { + if self.replace_after_first_ssh_revoke.load(Ordering::SeqCst) + && self.ssh_session_revocations.load(Ordering::SeqCst) > 0 + { + return format!("replacement-{name}"); + } + format!("id-{name}") + } +} + #[derive(Clone, Default)] struct TestOpenShell { state: SandboxState, @@ -198,7 +212,7 @@ impl OpenShell for TestOpenShell { let name = request.name; let mut sandbox = Sandbox { metadata: Some(openshell_core::proto::datamodel::v1::ObjectMeta { - id: format!("id-{name}"), + id: self.state.ssh_sandbox_id(&name), name, created_time: None, labels: HashMap::new(), @@ -395,6 +409,16 @@ impl OpenShell for TestOpenShell { &self, request: tonic::Request, ) -> Result, Status> { + if request + .metadata() + .get("authorization") + .and_then(|v| v.to_str().ok()) + == Some("Bearer cached-access-token") + { + self.state + .ssh_requests_with_cached_bearer + .fetch_add(1, Ordering::SeqCst); + } self.state .ssh_session_requests .fetch_add(1, Ordering::SeqCst); @@ -409,10 +433,10 @@ impl OpenShell for TestOpenShell { return Err(Status::failed_precondition("sandbox is not ready")); } let request = request.into_inner(); - let sandbox_id = format!("id-{}", request.sandbox); + let sandbox_id = self.state.ssh_sandbox_id(&request.sandbox); Ok(Response::new(CreateSshSessionResponse { + token: format!("token-{sandbox_id}"), sandbox_id, - token: "test-token".to_string(), gateway_scheme: "https".to_string(), gateway_host: "localhost".to_string(), gateway_port: 443, @@ -455,8 +479,13 @@ impl OpenShell for TestOpenShell { async fn revoke_ssh_session( &self, - _request: tonic::Request, + request: tonic::Request, ) -> Result, Status> { + self.state + .revoked_ssh_tokens + .lock() + .await + .push(request.into_inner().token); self.state .ssh_session_revocations .fetch_add(1, Ordering::SeqCst); @@ -824,7 +853,9 @@ impl OpenShell for TestOpenShell { "authorization_token is required for ForwardTcp", )); } - } else if init.authorization_token != "test-token" { + } else if init.authorization_token + != format!("token-{}", self.state.ssh_sandbox_id(&init.sandbox)) + { return Err(Status::unauthenticated("SSH session token not found")); } @@ -1109,8 +1140,8 @@ fi helper='@HELPER_PATH@' echo "$$" > '@PID_PATH@' -printf '%s\n' "ssh -N -o ProxyCommand=/tmp/openshell ssh-proxy --gateway https://127.0.0.1:9443 --sandbox $sandbox_name --workspace $workspace --token test-token --gateway-name test-gateway -o ExitOnForwardFailure=yes -o SetEnv=OPENSHELL_FORWARD_SANDBOX_ID=$immutable_id -L $forward sandbox" > '@COMMAND_PATH@' -exec env OPENSHELL_FAKE_FORWARD_MODE=listen "$helper" -N -o "ProxyCommand=/tmp/openshell ssh-proxy --gateway https://127.0.0.1:9443 --sandbox $sandbox_name --workspace $workspace --token test-token --gateway-name test-gateway" -o ExitOnForwardFailure=yes -o "SetEnv=OPENSHELL_FORWARD_SANDBOX_ID=$immutable_id" -L "$forward" sandbox +printf '%s\n' "ssh -N -o ProxyCommand=/tmp/openshell ssh-proxy --sandbox $sandbox_name --workspace $workspace --handoff test-handle -o ExitOnForwardFailure=yes -o SetEnv=OPENSHELL_FORWARD_SANDBOX_ID=$immutable_id -L $forward sandbox" > '@COMMAND_PATH@' +exec env OPENSHELL_FAKE_FORWARD_MODE=listen "$helper" -N -o "ProxyCommand=/tmp/openshell ssh-proxy --sandbox $sandbox_name --workspace $workspace --handoff test-handle" -o ExitOnForwardFailure=yes -o "SetEnv=OPENSHELL_FORWARD_SANDBOX_ID=$immutable_id" -L "$forward" sandbox "# .replace("@PID_PATH@", &pid_path.display().to_string()) .replace("@COMMAND_PATH@", &command_path.display().to_string()) @@ -1183,7 +1214,7 @@ fi helper='@HELPER_PATH@' echo "$$" > '@PID_PATH@' -exec env OPENSHELL_FAKE_FORWARD_MODE=sleep "$helper" -N -o "ProxyCommand=/tmp/openshell ssh-proxy --gateway https://127.0.0.1:9443 --sandbox $sandbox_id --token test-token --gateway-name test-gateway" -o ExitOnForwardFailure=yes -L "$forward" sandbox >'@LOG_PATH@' 2>&1 +exec env OPENSHELL_FAKE_FORWARD_MODE=sleep "$helper" -N -o "ProxyCommand=/tmp/openshell ssh-proxy --sandbox $sandbox_id --handoff test-handle" -o ExitOnForwardFailure=yes -L "$forward" sandbox >'@LOG_PATH@' 2>&1 "# .replace("@LOG_PATH@", &log_path.display().to_string()) .replace("@PID_PATH@", &pid_path.display().to_string()) @@ -2868,6 +2899,249 @@ async fn service_expose_forwards_bearer_passthrough_mode() { ); } +#[tokio::test] +async fn create_upload_keeps_the_id_from_the_create_response() { + let server = run_server().await; + let state = &server.openshell.state; + // The name already points at a replacement when the first upload starts. + state.ssh_session_revocations.store(1, Ordering::SeqCst); + state + .replace_after_first_ssh_revoke + .store(true, Ordering::SeqCst); + let source = helpers::tempdir().unwrap(); + let file = source.path().join("payload"); + fs::write(&file, b"for the original sandbox").unwrap(); + let output = run_cli_sandbox_create( + &server, + "upload-target", + &[ + "--detach", + "--no-git-ignore", + "--upload", + file.to_str().unwrap(), + ], + ) + .await; + assert!(!output.status.success()); + assert!(String::from_utf8_lossy(&output.stderr).contains("sandbox was replaced")); + assert_eq!(state.ssh_session_requests.load(Ordering::SeqCst), 0); +} + +#[tokio::test] +async fn copy_retry_refuses_and_revokes_a_same_name_replacement() { + let bin = helpers::tempdir().unwrap(); + let xdg = helpers::tempdir().unwrap(); + test_env(&bin, &xdg) + .run_async(async { + install_executable_script(&bin, "ssh", "#!/bin/sh\nexit 255\n"); + let file = xdg.path().join("payload"); + fs::write(&file, b"original data").unwrap(); + for upload in [true, false] { + let server = run_server().await; + let state = &server.openshell.state; + state + .replace_after_first_ssh_revoke + .store(true, Ordering::SeqCst); + let tls = test_tls(&server); + let result = if upload { + run::sandbox_sync_up( + &server.endpoint, + "copy", + &file, + Some("/target/"), + &tls, + "default", + ) + .await + .map(|_| ()) + } else { + run::sandbox_sync_down( + &server.endpoint, + "copy", + "payload", + file.to_str().unwrap(), + &tls, + "default", + ) + .await + }; + let err = result.unwrap_err(); + assert!( + err.chain() + .any(|cause| cause.to_string().contains("sandbox was replaced")), + "{err:?}" + ); + assert_eq!(state.ssh_session_requests.load(Ordering::SeqCst), 2); + assert_eq!( + *state.revoked_ssh_tokens.lock().await, + ["token-id-copy", "token-replacement-copy"] + ); + assert_eq!(fs::read(&file).unwrap(), b"original data"); + } + }) + .await; +} + +#[tokio::test] +async fn ssh_profile_credentials_follow_the_selected_endpoint() { + let server = run_server().await; + let xdg = helpers::tempdir().unwrap(); + prepare_cli_xdg(&server, &xdg, "openshell"); + write_oidc_test_credentials(&server, &xdg, "https://unused.invalid", 4_102_444_800); + let cli = || { + let mut command = tokio::process::Command::new(env!("CARGO_BIN_EXE_openshell")); + command + .env_remove("OPENSHELL_GATEWAY") + .env_remove("OPENSHELL_GATEWAY_ENDPOINT") + .env("XDG_CONFIG_HOME", xdg.path()) + .env("OPENSHELL_TELEMETRY_ENABLED", "false"); + command + }; + let state = &server.openshell.state; + state + .ssh_session_failures_remaining + .store(3, Ordering::SeqCst); + for args in [ + vec!["ssh-proxy", "--gateway-name", "openshell", "--name", "demo"], + vec!["ssh-proxy", "--gateway", "openshell", "--name", "demo"], + vec![ + "--gateway", + "openshell", + "ssh-proxy", + "--server", + &server.endpoint, + "--name", + "demo", + ], + ] { + let output = cli() + .args(args) + .env("OPENSHELL_GATEWAY_ENDPOINT", "http://127.0.0.1:1") + .output() + .await + .unwrap(); + assert!(!output.status.success()); + assert!(String::from_utf8_lossy(&output.stderr).contains("sandbox is not ready")); + } + assert_eq!( + state.ssh_requests_with_cached_bearer.load(Ordering::SeqCst), + 3 + ); + + // --server selects B's mTLS identity even if the shell exports profile A. + let other = run_server().await; + prepare_cli_xdg(&other, &xdg, "other"); + fs::write( + xdg.path().join("openshell/gateways/other/metadata.json"), + serde_json::to_vec(&openshell_bootstrap::GatewayMetadata { + name: "other".into(), + gateway_endpoint: other.endpoint.clone(), + ..openshell_bootstrap::GatewayMetadata::default() + }) + .unwrap(), + ) + .unwrap(); + let other_state = &other.openshell.state; + other_state + .ssh_session_failures_remaining + .store(3, Ordering::SeqCst); + let status = cli() + .args(["-g", "openshell", "status", "--output", "json"]) + .env("OPENSHELL_GATEWAY_ENDPOINT", &other.endpoint) + .output() + .await + .unwrap(); + assert!( + status.status.success(), + "{}", + String::from_utf8_lossy(&status.stderr) + ); + let status: serde_json::Value = serde_json::from_slice(&status.stdout).unwrap(); + assert_eq!(status["server"], other.endpoint); + assert_eq!(status["gateway"], "other"); + assert_eq!(status["status"], "connected"); + + let connect = cli() + .args(["-g", "openshell", "sandbox", "connect", "demo"]) + .env("OPENSHELL_GATEWAY_ENDPOINT", &other.endpoint) + .output() + .await + .unwrap(); + assert!(String::from_utf8_lossy(&connect.stderr).contains("sandbox is not ready")); + for flag in ["--server", "--gateway-endpoint"] { + let output = cli() + .args(["ssh-proxy", flag, &other.endpoint, "--name", "demo"]) + .env("OPENSHELL_GATEWAY", "openshell") + .output() + .await + .unwrap(); + assert!(String::from_utf8_lossy(&output.stderr).contains("sandbox is not ready")); + } + assert_eq!(other_state.ssh_session_requests.load(Ordering::SeqCst), 3); + assert_eq!( + other_state + .ssh_requests_with_cached_bearer + .load(Ordering::SeqCst), + 0 + ); +} + +#[tokio::test] +async fn selected_ssh_profile_wins_over_an_active_profile_on_the_same_host() { + let server = run_server().await; + let xdg = helpers::tempdir().unwrap(); + prepare_cli_xdg(&server, &xdg, "openshell"); + write_oidc_test_credentials(&server, &xdg, "https://unused.invalid", 4_102_444_800); + let endpoint = server.endpoint.replace("localhost", "LOCALHOST"); + let profiles = xdg.path().join("openshell"); + prepare_cli_xdg(&server, &xdg, "other"); + fs::write(profiles.join("active_gateway"), "other").unwrap(); + fs::write( + profiles.join("gateways/other/metadata.json"), + serde_json::to_vec(&openshell_bootstrap::GatewayMetadata { + name: "other".into(), + gateway_endpoint: endpoint.clone(), + ..Default::default() + }) + .unwrap(), + ) + .unwrap(); + let state = &server.openshell.state; + state + .ssh_session_failures_remaining + .store(3, Ordering::SeqCst); + for (request, args) in [ + &["-g", "openshell", "sandbox", "connect", "demo"][..], + &["ssh-proxy", "--server", &endpoint, "--name", "demo"], + &[ + "ssh-proxy", + "--gateway-endpoint", + &endpoint, + "--name", + "demo", + ], + ] + .into_iter() + .enumerate() + { + let output = tokio::process::Command::new(env!("CARGO_BIN_EXE_openshell")) + .args(args) + .env("OPENSHELL_GATEWAY", "openshell") + .env("OPENSHELL_GATEWAY_ENDPOINT", &endpoint) + .env("XDG_CONFIG_HOME", xdg.path()) + .env("OPENSHELL_TELEMETRY_ENABLED", "false") + .output() + .await + .unwrap(); + assert!(String::from_utf8_lossy(&output.stderr).contains("sandbox is not ready")); + assert_eq!( + state.ssh_requests_with_cached_bearer.load(Ordering::SeqCst), + request + 1, + "{args:?}" + ); + } +} + #[tokio::test] async fn sandbox_forward_background_tracks_owned_child_when_pid_discovery_fails() { let server = run_server().await; @@ -2887,6 +3161,24 @@ async fn sandbox_forward_background_tracks_owned_child_when_pid_discovery_fails( result.expect( "background forward should track the owned SSH child without PID discovery", ); + // The fake openssh opened the listener without collecting its grant. + // A successful background handoff must still revoke before the CLI exits. + assert_eq!( + server + .openshell + .state + .ssh_session_requests + .load(Ordering::SeqCst), + 1 + ); + assert_eq!( + server + .openshell + .state + .ssh_session_revocations + .load(Ordering::SeqCst), + 1 + ); let record = openshell_core::forward::read_forward_pid("default", "owned-forward", forward_port) .expect("owned background forward should write a PID file"); @@ -3073,8 +3365,12 @@ async fn sandbox_create_env_rejects_invalid_key_name() { ); } -fn prepare_cli_xdg(server: &TestServer, xdg_dir: &TempDir) { - let tls_dir = xdg_dir.path().join("openshell/gateways/openshell/mtls"); +fn prepare_cli_xdg(server: &TestServer, xdg_dir: &TempDir, profile: &str) { + let tls_dir = xdg_dir + .path() + .join("openshell/gateways") + .join(profile) + .join("mtls"); fs::create_dir_all(&tls_dir).unwrap(); for filename in ["ca.crt", "tls.crt", "tls.key"] { fs::copy(server.dir.path().join(filename), tls_dir.join(filename)).unwrap(); @@ -3129,7 +3425,7 @@ async fn run_cli_sandbox_create( extra_args: &[&str], ) -> std::process::Output { let xdg_dir = helpers::tempdir().unwrap(); - prepare_cli_xdg(server, &xdg_dir); + prepare_cli_xdg(server, &xdg_dir, "openshell"); run_cli_sandbox_create_with_xdg(server, &xdg_dir, name, extra_args).await } @@ -3217,7 +3513,11 @@ async fn sandbox_create_upload_warns_and_reaches_ssh_outside_git_repository() { let xdg_dir = helpers::tempdir().unwrap(); test_env(&fake_ssh_dir, &xdg_dir) .run_async(async { - install_executable_script(&fake_ssh_dir, "ssh", "#!/bin/sh\nexit 7\n"); + install_executable_script( + &fake_ssh_dir, + "ssh", + "#!/bin/sh\n: > \"$0.called\"\nexit 7\n", + ); let source = tempfile::tempdir().unwrap(); fs::write(source.path().join("marker.txt"), "dummy content").unwrap(); let args = ["--detach", "--upload", source.path().to_str().unwrap()]; @@ -3240,12 +3540,7 @@ async fn sandbox_create_upload_warns_and_reaches_ssh_outside_git_repository() { assert!(stderr.contains("openshell sandbox delete"), "{stderr}"); assert_eq!(create_requests(&server).await.len(), 1); assert!( - server - .openshell - .state - .ssh_session_requests - .load(Ordering::SeqCst) - > 0, + fake_ssh_dir.path().join("ssh.called").is_file(), "an upload outside a repository must reach the SSH transport", ); }) @@ -3259,7 +3554,7 @@ async fn run_cli_sandbox_create_with_env( environment: &[(&str, &str)], ) -> std::process::Output { let xdg_dir = helpers::tempdir().unwrap(); - prepare_cli_xdg(server, &xdg_dir); + prepare_cli_xdg(server, &xdg_dir, "openshell"); run_cli_sandbox_create_with_xdg_and_env(server, &xdg_dir, name, extra_args, environment).await } @@ -3426,7 +3721,7 @@ async fn sandbox_create_fails_before_mutation_when_expired_oidc_refresh_is_rejec let server = run_server().await; let issuer = run_rejected_oidc_refresh_server().await; let xdg_dir = helpers::tempdir().unwrap(); - prepare_cli_xdg(&server, &xdg_dir); + prepare_cli_xdg(&server, &xdg_dir, "openshell"); write_oidc_test_credentials(&server, &xdg_dir, &issuer, 0); @@ -3462,7 +3757,7 @@ async fn sandbox_create_continues_with_unexpired_cached_token_when_refresh_fails let server = run_server().await; let issuer = run_rejected_oidc_refresh_server().await; let xdg_dir = helpers::tempdir().unwrap(); - prepare_cli_xdg(&server, &xdg_dir); + prepare_cli_xdg(&server, &xdg_dir, "openshell"); let expires_at = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .unwrap() @@ -3818,7 +4113,7 @@ async fn service_forward_falls_back_to_session_tokens_once_for_a_legacy_gateway( echo_through_local_forward(&forward, port, b"first connection").await; wait_for_count(&state.ssh_session_revocations, 1, "revocation").await; let inits = state.forward_inits.lock().await.clone(); - assert_eq!(forward_tokens(&inits), vec!["", "test-token"]); + assert_eq!(forward_tokens(&inits), vec!["", "token-id-svc-sandbox"]); assert_eq!(state.forward_token_rejections.load(Ordering::SeqCst), 1); assert_eq!(state.ssh_session_requests.load(Ordering::SeqCst), 1); @@ -3827,7 +4122,10 @@ async fn service_forward_falls_back_to_session_tokens_once_for_a_legacy_gateway( echo_through_local_forward(&forward, port, b"second connection").await; wait_for_count(&state.ssh_session_revocations, 2, "revocations").await; let inits = state.forward_inits.lock().await.clone(); - assert_eq!(forward_tokens(&inits), vec!["", "test-token", "test-token"]); + assert_eq!( + forward_tokens(&inits), + vec!["", "token-id-svc-sandbox", "token-id-svc-sandbox"] + ); assert_eq!(state.forward_token_rejections.load(Ordering::SeqCst), 1); assert_eq!(state.ssh_session_requests.load(Ordering::SeqCst), 2); assert!( diff --git a/crates/openshell-cli/tests/ssh_proxy_shutdown_integration.rs b/crates/openshell-cli/tests/ssh_proxy_shutdown_integration.rs index 76f9b32f5e..7213317a1b 100644 --- a/crates/openshell-cli/tests/ssh_proxy_shutdown_integration.rs +++ b/crates/openshell-cli/tests/ssh_proxy_shutdown_integration.rs @@ -1,77 +1,205 @@ // SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -use bytes::Bytes; -use http_body_util::{BodyExt, StreamBody}; -use hyper::body::Frame; -use hyper::service::service_fn; -use hyper_util::rt::{TokioExecutor, TokioIo}; -use openshell_core::proto::{TcpForwardFrame, tcp_forward_frame}; -use prost::Message; -use std::convert::Infallible; +use futures::StreamExt; +use openshell_core::proto::{self, TcpForwardFrame, tcp_forward_frame}; +use openshell_server::test_support::grpc::open_shell_server::{OpenShell, OpenShellServer}; +use std::net::SocketAddr; use std::process::Stdio; +use std::sync::{ + Arc, + atomic::{AtomicBool, AtomicUsize, Ordering}, +}; use std::time::Duration; use tokio::io::AsyncWriteExt; +use tokio_stream::wrappers::TcpListenerStream; +use tonic::{Request, Response, Status}; -async fn proxy_exits_with_stdin_open(relay_status: tonic::Status) { - let expected_code = relay_status.code(); - let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); - let address = listener.local_addr().unwrap(); - let server = tokio::spawn(async move { - let (socket, _) = listener.accept().await.unwrap(); - let service = service_fn(move |request: hyper::Request| { - let status = relay_status.clone(); - async move { - assert_eq!(request.uri().path(), "/openshell.v1.OpenShell/ForwardTcp"); - let body = StreamBody::new(futures::stream::once(async move { - // Wait until stdin actually traverses the proxy. After this - // chunk its reader blocks again, with the parent pipe open. - let mut inbound = request.into_body(); - let mut pending = Vec::new(); - 'input: while let Some(frame) = inbound.frame().await { - if let Ok(data) = frame.unwrap().into_data() { - pending.extend_from_slice(&data); - while pending.len() >= 5 { - let length = - u32::from_be_bytes(pending[1..5].try_into().unwrap()) as usize; - if pending.len() < 5 + length { - break; - } - let frame = - TcpForwardFrame::decode(&pending[5..5 + length]).unwrap(); - pending.drain(..5 + length); - if matches!(frame.payload, Some(tcp_forward_frame::Payload::Data(data)) if data == b"probe") - { - break 'input; - } - } - } - } - tokio::time::sleep(Duration::from_millis(100)).await; - let trailers = status.into_http::<()>().into_parts().0.headers; - Ok::, Infallible>(Frame::trailers(trailers)) - })); - let mut response = hyper::Response::new(body); - response - .headers_mut() - .insert("content-type", "application/grpc".parse().unwrap()); - Ok::<_, Infallible>(response) - } +const TOKEN: &str = "test-ssh-session"; + +#[derive(Clone, Copy)] +enum Admission { + Legacy, + Direct, + RejectDirect(tonic::Code), +} + +struct Gateway { + admissions: Vec, + lookups: AtomicUsize, + direct_opens: AtomicUsize, + minted: AtomicBool, + relay_status: Status, + port: u16, + revoked: AtomicBool, + stall_open: Option>, + reset_transport: Arc, +} + +impl Gateway { + async fn start( + admissions: Vec, + relay_status: Status, + stall_open: Option>, + ) -> (SocketAddr, Arc, tokio::task::AbortHandle) { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let gateway = Arc::new(Self { + admissions, + lookups: AtomicUsize::default(), + direct_opens: AtomicUsize::default(), + minted: AtomicBool::default(), + relay_status, + port: address.port(), + revoked: AtomicBool::default(), + stall_open, + reset_transport: Arc::default(), }); - let _ = hyper::server::conn::http2::Builder::new(TokioExecutor::new()) - .serve_connection(TokioIo::new(socket), service) - .await; - }); + let server = tokio::spawn( + tonic::transport::Server::builder() + .add_service(OpenShellServer::from_arc(gateway.clone())) + .serve_with_incoming(TcpListenerStream::new(listener)), + ); + (address, gateway, server.abort_handle()) + } + + fn admission(&self) -> Result { + let index = self.lookups.load(Ordering::SeqCst).saturating_sub(1); + self.admissions + .get(index) + .copied() + .ok_or_else(|| Status::permission_denied("unexpected SSH reconnect")) + } +} + +#[tonic::async_trait] +impl OpenShell for Gateway { + async fn get_sandbox( + &self, + req: Request, + ) -> Result, Status> { + let metadata = proto::datamodel::v1::ObjectMeta { + id: "id-repro".into(), + ..proto::datamodel::v1::ObjectMeta::default() + }; + let mut response = Response::new(proto::SandboxResponse { + sandbox: Some(proto::Sandbox { + metadata: Some(metadata), + ..proto::Sandbox::default() + }), + ..proto::SandboxResponse::default() + }); + // Only a connection lookup advances the script. Lifecycle polls also call GetSandbox. + if self.admissions.len() > 1 + && req + .metadata() + .contains_key(openshell_core::replica_routing::OWNER_REQUEST_HEADER) + { + self.lookups.fetch_add(1, Ordering::SeqCst); + } + if !matches!(self.admission()?, Admission::Legacy) { + response.metadata_mut().insert( + openshell_core::forward::DIRECT_SSH_HEADER, + "1".parse().unwrap(), + ); + } + Ok(response) + } + + async fn create_ssh_session( + &self, + _: Request, + ) -> Result, Status> { + self.minted.store(true, Ordering::SeqCst); + Ok(Response::new(proto::CreateSshSessionResponse { + sandbox_id: "id-repro".into(), + token: TOKEN.into(), + gateway_host: "127.0.0.1".into(), + gateway_port: self.port.into(), + gateway_scheme: "http".into(), + ..proto::CreateSshSessionResponse::default() + })) + } + + async fn forward_tcp( + &self, + req: Request>, + ) -> Result>, Status> { + let mut inbound = req.into_inner(); + let Some(tcp_forward_frame::Payload::Init(init)) = + inbound.message().await?.and_then(|f| f.payload) + else { + return Err(Status::invalid_argument("expected init")); + }; + let admission = self.admission()?; + match admission { + Admission::Legacy => { + assert!(matches!( + init.target, + Some(proto::tcp_forward_init::Target::Ssh(_)) + )); + assert_eq!(init.authorization_token, TOKEN); + } + Admission::Direct | Admission::RejectDirect(_) => { + assert!(init.authorization_token.is_empty()); + assert_eq!( + init.target, + Some(proto::tcp_forward_init::Target::DirectSshSandboxId( + "id-repro".into() + )) + ); + self.direct_opens.fetch_add(1, Ordering::SeqCst); + if let Admission::RejectDirect(code) = admission { + return Err(Status::new(code, "SSHREFUSED")); + } + } + } + if let Some(started) = &self.stall_open { + started.notify_one(); + return std::future::pending().await; + } + let status = self.relay_status.clone(); + let reset_transport = (self.admissions.len() > 1 + && self.lookups.load(Ordering::SeqCst) == 1) + .then(|| self.reset_transport.clone()); + let stream = futures::stream::once(async move { + // Leave stdin open after one chunk traverses the proxy. + let frame = inbound.message().await.unwrap().unwrap(); + assert!(matches!(frame.payload, Some(tcp_forward_frame::Payload::Data(data)) if data == b"probe")); + if let Some(reset_transport) = reset_transport { + // Keep the admitted relay alive past the connect establishment threshold. + tokio::time::sleep(Duration::from_millis(2_200)).await; + reset_transport.notify_waiters(); + return std::future::pending().await; + } + (status.code() != tonic::Code::Ok).then_some(Err(status)) + }).filter_map(futures::future::ready); + Ok(Response::new(Box::pin(stream))) + } + + async fn revoke_ssh_session( + &self, + req: Request, + ) -> Result, Status> { + let req = req.into_inner(); + assert!(req.token == TOKEN, "unexpected token in revocation"); + assert!(req.allow_missing); + self.revoked.store(true, Ordering::SeqCst); + Ok(Response::new(proto::RevokeSshSessionResponse::default())) + } +} + +async fn proxy_exits_with_stdin_open(relay_status: Status, admission: Admission) { + let expected_code = relay_status.code(); + let (address, gateway, server) = Gateway::start(vec![admission], relay_status, None).await; let config = tempfile::tempdir().unwrap(); let mut child = tokio::process::Command::new(env!("CARGO_BIN_EXE_openshell")) .args([ "ssh-proxy", - "--gateway", - &format!("http://{address}/proxy/connect"), + "--server", + &format!("http://{address}"), "--sandbox", "repro", - "--token", - "test-token", ]) .env("XDG_CONFIG_HOME", config.path()) .env("OPENSHELL_TELEMETRY_ENABLED", "false") @@ -81,37 +209,245 @@ async fn proxy_exits_with_stdin_open(relay_status: tonic::Status) { .kill_on_drop(true) .spawn() .unwrap(); - child - .stdin - .as_mut() - .unwrap() - .write_all(b"probe") - .await - .unwrap(); - // Keep child.stdin alive throughout wait: closing it would conceal the bug. + let mut stdin = child.stdin.take().unwrap(); + stdin.write_all(b"probe").await.unwrap(); let status = tokio::time::timeout(Duration::from_secs(5), child.wait()) .await .expect("SSH proxy must exit even while the parent holds stdin open") .unwrap(); + drop(stdin); let mut stderr = String::new(); tokio::io::AsyncReadExt::read_to_string(child.stderr.as_mut().unwrap(), &mut stderr) .await .unwrap(); - if expected_code == tonic::Code::Ok { + if matches!(admission, Admission::RejectDirect(_)) { + assert!( + !status.success() && stderr.contains("SSHREFUSED"), + "{stderr}" + ); + } else if expected_code == tonic::Code::Ok { assert!(status.success(), "{stderr}"); } else { assert!(!status.success(), "relay failure must propagate to SSH"); assert!(stderr.contains("Deadline expired"), "{stderr}"); } + assert_eq!( + gateway.minted.load(Ordering::SeqCst), + matches!(admission, Admission::Legacy) + ); + assert_eq!( + gateway.revoked.load(Ordering::SeqCst), + matches!(admission, Admission::Legacy) + ); + server.abort(); +} + +#[tokio::test] +async fn dropping_handoff_cancels_a_stalled_relay_open() { + let started = Arc::new(tokio::sync::Notify::new()); + let (address, _, server) = Gateway::start( + vec![Admission::Legacy], + Status::ok(""), + Some(started.clone()), + ) + .await; + let (owner, peer) = tokio::io::duplex(8); + let proxy = tokio::spawn(async move { + let grant = openshell_core::ssh_handoff::RelayGrant { + authorization: Some(openshell_core::ssh_handoff::RelayAuthorization::Session( + proto::CreateSshSessionResponse { + sandbox_id: "id-repro".into(), + token: TOKEN.into(), + gateway_scheme: "http".into(), + gateway_host: "127.0.0.1".into(), + gateway_port: address.port().into(), + ..proto::CreateSshSessionResponse::default() + }, + )), + endpoint: format!("http://{address}"), + gateway_name: "test".into(), + replica: None, + }; + openshell_cli::ssh::relay_prepared_ssh( + grant, + peer, + "repro", + "default", + &openshell_cli::tls::TlsOptions::default(), + ) + .await + }); + tokio::time::timeout(Duration::from_secs(5), started.notified()) + .await + .unwrap(); + drop(owner); + let result = tokio::time::timeout(Duration::from_secs(2), proxy) + .await + .expect("proxy must leave the blocked RPC when the issuer exits") + .unwrap(); + assert!(result.is_err()); server.abort(); } #[tokio::test] async fn proxy_exits_after_relay_error_with_stdin_open() { - proxy_exits_with_stdin_open(tonic::Status::deadline_exceeded("relay open timed out")).await; + proxy_exits_with_stdin_open( + Status::deadline_exceeded("relay open timed out"), + Admission::Legacy, + ) + .await; } #[tokio::test] async fn proxy_exits_after_clean_relay_close_with_stdin_open() { - proxy_exits_with_stdin_open(tonic::Status::ok("")).await; + proxy_exits_with_stdin_open(Status::ok(""), Admission::Legacy).await; +} + +#[tokio::test] +async fn advertised_direct_ssh_never_mints_even_when_rejected() { + proxy_exits_with_stdin_open(Status::ok(""), Admission::Direct).await; + for code in [ + tonic::Code::PermissionDenied, + tonic::Code::FailedPrecondition, + tonic::Code::Unimplemented, + ] { + proxy_exits_with_stdin_open(Status::ok(""), Admission::RejectDirect(code)).await; + } +} + +#[cfg(unix)] +fn proxying_ssh_config() -> tempfile::TempDir { + use std::os::unix::fs::PermissionsExt; + + let config = tempfile::tempdir().unwrap(); + let ssh = config.path().join("ssh"); + std::fs::write( + &ssh, + r#"#!/bin/sh +for arg do + case "$arg" in + ProxyCommand=*) printf probe | /bin/sh -c "${arg#ProxyCommand=}"; exit 255 ;; + esac +done +exit 1 +"#, + ) + .unwrap(); + std::fs::set_permissions(&ssh, std::fs::Permissions::from_mode(0o700)).unwrap(); + config +} + +#[cfg(unix)] +fn sandbox_cli(config: &tempfile::TempDir, address: SocketAddr) -> tokio::process::Command { + let mut cli = tokio::process::Command::new(env!("CARGO_BIN_EXE_openshell")); + cli.args([ + "--gateway", + "test", + "--gateway-endpoint", + &format!("http://{address}"), + "sandbox", + ]) + .env("PATH", config.path()) + .env("XDG_CONFIG_HOME", config.path()) + .env("OPENSHELL_TELEMETRY_ENABLED", "false") + .kill_on_drop(true); + cli +} + +#[cfg(unix)] +#[tokio::test] +async fn connect_recovers_after_tcp_reset_but_stops_on_direct_refusal_or_capability_loss() { + let config = proxying_ssh_config(); + for (replacement, expected_direct_opens) in [ + (Admission::RejectDirect(tonic::Code::PermissionDenied), 2), + (Admission::Legacy, 1), + ] { + let (address, gateway, server) = Gateway::start( + // An extra lookup after a refusal reaches a legacy-only gateway. + vec![Admission::Direct, replacement, Admission::Legacy], + Status::unavailable("connection lost"), + None, + ) + .await; + // Reset established TCP connections while the gateway keeps accepting reconnects. + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let relay_address = listener.local_addr().unwrap(); + let reset = gateway.reset_transport.clone(); + let bridge = tokio::spawn(async move { + while let Ok((mut downstream, _)) = listener.accept().await { + let reset = reset.clone(); + tokio::spawn(async move { + let mut upstream = + openshell_core::net::connect_tcp_nodelay_best_effort(address) + .await + .unwrap(); + tokio::select! { + () = reset.notified() => downstream.set_zero_linger().unwrap(), + _ = tokio::io::copy_bidirectional(&mut downstream, &mut upstream) => {} + } + }); + } + }); + let output = tokio::time::timeout( + Duration::from_secs(10), + sandbox_cli(&config, relay_address) + .args(["connect", "repro"]) + .output(), + ) + .await + .expect("connect must stop during recovery") + .unwrap(); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!(!output.status.success(), "{stderr}"); + assert!( + !gateway.minted.load(Ordering::SeqCst), + "minted a legacy SSH session during recovery: {stderr}" + ); + assert_eq!(gateway.lookups.load(Ordering::SeqCst), 2, "{stderr}"); + assert_eq!( + gateway.direct_opens.load(Ordering::SeqCst), + expected_direct_opens, + "{stderr}" + ); + bridge.abort(); + server.abort(); + } +} + +#[cfg(unix)] +#[tokio::test] +async fn download_stops_on_direct_refusal_even_with_transport_words_in_the_path() { + let config = proxying_ssh_config(); + for admission in [ + Admission::RejectDirect(tonic::Code::PermissionDenied), + Admission::Direct, + ] { + let (address, gateway, server) = Gateway::start( + vec![admission], + Status::permission_denied("SSHREFUSED"), + None, + ) + .await; + let dest = config.path().join("download"); + for (index, path) in ["plain.bin", "connection-roundtrip.bin"] + .into_iter() + .enumerate() + { + let output = sandbox_cli(&config, address) + .args(["download", "repro", path]) + .arg(&dest) + .output() + .await + .unwrap(); + assert!(!output.status.success()); + assert_eq!( + gateway.direct_opens.load(Ordering::SeqCst), + index + 1, + "{path}" + ); + assert!(!dest.exists()); + } + assert!(!gateway.minted.load(Ordering::SeqCst)); + server.abort(); + } } diff --git a/crates/openshell-core/Cargo.toml b/crates/openshell-core/Cargo.toml index 55339e09b5..80de75fcc3 100644 --- a/crates/openshell-core/Cargo.toml +++ b/crates/openshell-core/Cargo.toml @@ -24,6 +24,7 @@ tonic-prost = { workspace = true } tonic-types = { workspace = true } tokio = { workspace = true } tokio-stream = { workspace = true } +tokio-util = { version = "0.7", features = ["rt"] } thiserror = { workspace = true } miette = { workspace = true } serde = { workspace = true } @@ -80,3 +81,6 @@ tokio-rustls = { workspace = true } [lints] workspace = true + +[target.'cfg(windows)'.dependencies] +windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_Security_Authorization", "Win32_System_Pipes", "Win32_System_Threading"] } diff --git a/crates/openshell-core/src/forward.rs b/crates/openshell-core/src/forward.rs index c8e6c10131..4f1a4a1eeb 100644 --- a/crates/openshell-core/src/forward.rs +++ b/crates/openshell-core/src/forward.rs @@ -364,14 +364,13 @@ fn proxy_command_option_present(args: &[&str], proxy_index: usize) -> bool { fn proxy_option_takes_value(arg: &str) -> bool { matches!( arg, - "--gateway" | "--workspace" | "--token" | "--gateway-name" + "--gateway" | "--workspace" | "--token" | "--gateway-name" | "--server" | "--handoff" ) } fn proxy_option_has_inline_value(arg: &str) -> bool { - ["--gateway=", "--workspace=", "--token=", "--gateway-name="] - .iter() - .any(|prefix| arg.starts_with(prefix)) + arg.split_once('=') + .is_some_and(|(option, _)| proxy_option_takes_value(option)) } fn is_outer_ssh_option_start(arg: &str) -> bool { @@ -826,6 +825,21 @@ fn lsof_listeners(port: u16) -> Option { // SSH utility functions (shared between CLI and TUI) // --------------------------------------------------------------------------- +/// An authenticated `GetSandbox` reply advertises tokenless SSH on this gateway. +pub const DIRECT_SSH_HEADER: &str = "x-openshell-direct-ssh"; + +pub fn supports_direct_ssh(response: &tonic::Response) -> Result { + let values = response.metadata().get_all(DIRECT_SSH_HEADER); + let mut values = values.iter(); + match (values.next(), values.next()) { + (None, None) => Ok(false), + (Some(value), None) if value == "1" => Ok(true), + _ => Err(miette::miette!( + "invalid direct SSH capability in gateway response" + )), + } +} + /// Resolve the SSH gateway scheme, host, and port for a sandbox connection. /// /// If the server-provided gateway host is a loopback address, use the host @@ -923,28 +937,17 @@ pub fn shell_escape(value: &str) -> String { format!("'{escaped}'") } -/// Build the SSH `ProxyCommand` string used to tunnel to a sandbox. -/// -/// Every interpolated argument is shell-escaped so that server-supplied values -/// (gateway URL, sandbox name, workspace, token, gateway name) cannot inject shell -/// metacharacters into the command that OpenSSH executes via `/bin/sh -c`. -pub fn build_proxy_command( - exe: &str, - gateway_url: &str, - sandbox_name: &str, - workspace: &str, - token: &str, - gateway_name: &str, -) -> String { +/// Build a one-use proxy command. The handle identifies an owner-only IPC +/// endpoint. Only the parent and proxy exchange the relay credentials. +pub fn build_proxy_command(exe: &str, handle: &str, sandbox: &str, workspace: &str) -> String { format!( - "{} ssh-proxy --gateway {} --sandbox {} --workspace {} --token {} --gateway-name {}", + "{} ssh-proxy --sandbox {} --workspace {} --handoff {}", shell_escape(exe), - shell_escape(gateway_url), - shell_escape(sandbox_name), + shell_escape(sandbox), shell_escape(workspace), - shell_escape(token), - shell_escape(gateway_name), + shell_escape(handle), ) + .replace('%', "%%") } /// Build the `ssh` options shared by every sandbox session. @@ -968,11 +971,7 @@ pub fn sandbox_ssh_args(proxy_command: &str, log_level: &str) -> Vec { .collect() } -/// Error returned when a `CreateSshSessionResponse` fails validation. -/// -/// The response fields flow into a `ProxyCommand` string executed by -/// `/bin/sh -c`; any deviation from the documented charset is rejected at the -/// gRPC trust boundary before escaping is attempted. +/// Error returned when an SSH session field fails validation. #[derive(Debug, thiserror::Error)] pub enum SshSessionResponseError { #[error("{field} is empty")] @@ -1012,22 +1011,11 @@ fn is_fingerprint_byte(b: u8) -> bool { b.is_ascii_alphanumeric() || matches!(b, b':' | b'+' | b'/' | b'=' | b'-') } -/// Validate a `CreateSshSessionResponse` before any of its fields are used to -/// build a shell command or config file. -/// -/// This is a belt-and-suspenders pair to [`build_proxy_command`]: escaping -/// alone is sufficient to prevent injection, but rejecting malformed fields -/// at the trust boundary fails loudly before the string is assembled and -/// catches gateway bugs or tampering early. +/// Check the SSH session response against the gateway protocol's charset and length limits. pub fn validate_ssh_session_response( resp: &crate::proto::CreateSshSessionResponse, ) -> std::result::Result<(), SshSessionResponseError> { - validate_field( - "sandbox_id", - &resp.sandbox_id, - MAX_SANDBOX_ID_LEN, - is_sandbox_id_byte, - )?; + validate_ssh_sandbox_id(&resp.sandbox_id)?; validate_field("token", &resp.token, MAX_TOKEN_LEN, is_token_byte)?; validate_field( "gateway_host", @@ -1058,6 +1046,10 @@ pub fn validate_ssh_session_response( Ok(()) } +pub fn validate_ssh_sandbox_id(id: &str) -> std::result::Result<(), SshSessionResponseError> { + validate_field("sandbox_id", id, MAX_SANDBOX_ID_LEN, is_sandbox_id_byte) +} + fn validate_field( name: &'static str, value: &str, @@ -1109,6 +1101,26 @@ mod tests { use super::*; use crate::test_environment::Environment; + #[test] + fn direct_ssh_requires_one_explicit_capability_value() { + let mut response = tonic::Response::new(()); + assert!(!supports_direct_ssh(&response).unwrap()); + for value in ["0", "true", "1,1"] { + response + .metadata_mut() + .insert(DIRECT_SSH_HEADER, value.parse().unwrap()); + assert!(supports_direct_ssh(&response).is_err()); + } + response + .metadata_mut() + .insert(DIRECT_SSH_HEADER, "1".parse().unwrap()); + assert!(supports_direct_ssh(&response).unwrap()); + response + .metadata_mut() + .append(DIRECT_SSH_HEADER, "1".parse().unwrap()); + assert!(supports_direct_ssh(&response).is_err()); + } + #[test] fn resolve_ssh_gateway_keeps_non_loopback() { let resolved = resolve_ssh_gateway("http", "10.0.0.5", 8080, "https://spark.local"); @@ -1351,11 +1363,9 @@ mod tests { // Attacker-controlled values in every escapable position. let cmd = build_proxy_command( "/usr/local/bin/openshell", - "https://gw:443/connect", + "handle", "x$(touch /tmp/pwn)x", "ws; touch /tmp/pwn", - "tok`id`", - "gw-name", ); // The `$` / backtick must only appear inside single-quoted regions. @@ -1373,24 +1383,17 @@ mod tests { fn build_proxy_command_empty_values_quote_rather_than_vanish() { // An empty value must become `''` rather than disappearing — otherwise // downstream argv splitting would misalign. - let cmd = build_proxy_command("exe", "gw", "", "", "tok", "name"); + let cmd = build_proxy_command("exe", "handle", "", ""); assert!(cmd.contains("--sandbox ''")); assert!(cmd.contains("--workspace ''")); } #[test] - fn build_proxy_command_safe_values_pass_through_unquoted() { - let cmd = build_proxy_command( - "/usr/local/bin/openshell", - "gw", - "sb-123", - "workspace-1", - "tok.456", - "name_1", - ); + fn build_proxy_command_contains_only_handle_and_sandbox_identity() { + let cmd = build_proxy_command("/opt/My %h/bin", "opaque", "sb-123", "workspace-1"); assert_eq!( cmd, - "/usr/local/bin/openshell ssh-proxy --gateway gw --sandbox sb-123 --workspace workspace-1 --token tok.456 --gateway-name name_1" + "'/opt/My %%h/bin' ssh-proxy --sandbox sb-123 --workspace workspace-1 --handoff opaque" ); } diff --git a/crates/openshell-core/src/lib.rs b/crates/openshell-core/src/lib.rs index 530fb3e09d..c9187a9bc7 100644 --- a/crates/openshell-core/src/lib.rs +++ b/crates/openshell-core/src/lib.rs @@ -65,6 +65,7 @@ pub mod sandbox_update; pub mod secrets; pub mod settings; pub mod shell; +pub mod ssh_handoff; pub mod telemetry; pub mod time; pub mod token_grant_failure; diff --git a/crates/openshell-core/src/ssh_handoff.rs b/crates/openshell-core/src/ssh_handoff.rs new file mode 100644 index 0000000000..dea861ed01 --- /dev/null +++ b/crates/openshell-core/src/ssh_handoff.rs @@ -0,0 +1,509 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Hand the proxy the selected gateway and SSH route over private IPC. The +//! issuer retains any legacy session grant until admission or cancellation. + +#[cfg(unix)] +mod unix; +#[cfg(windows)] +mod windows; +#[cfg(unix)] +use unix as ipc; +#[cfg(windows)] +use windows as ipc; + +use crate::forward::{ + build_proxy_command, supports_direct_ssh, validate_ssh_sandbox_id, + validate_ssh_session_response, +}; +use crate::metadata::ObjectId; +use crate::proto::{ + CreateSshSessionRequest, CreateSshSessionResponse, GetSandboxRequest, RevokeSshSessionRequest, + Sandbox, SandboxResponse, open_shell_client::OpenShellClient, workspace_selector, +}; +use crate::replica_routing::{owner_replica, with_owner_hint}; +use crate::time::{duration_from_std, duration_to_std}; +use miette::{IntoDiagnostic, Result}; +use prost::Message; +use std::{borrow::Cow, future::Future, time::Duration}; +use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}; +use tokio::sync::oneshot; +use tonic::{ + service::{Interceptor, interceptor::InterceptedService}, + transport::Channel, +}; +use uuid::Uuid; + +type Client = OpenShellClient>; + +// Room for a unary session response plus the endpoint, profile and routing hint. +const MAX_HANDOFF_SIZE: usize = 5 * 1024 * 1024; +/// The gateway refused direct admission. End this operation, including automatic recovery. +pub const DIRECT_SSH_REFUSED: u8 = 2; + +#[derive(Debug, thiserror::Error, miette::Diagnostic)] +pub enum SshAdmissionError { + #[error("{0}")] + Rpc(tonic::Status), + #[error("gateway refused direct SSH admission")] + Refused, + #[error("sandbox was replaced before opening the SSH relay")] + Replaced, + #[error("gateway stopped advertising direct SSH")] + CapabilityLost, +} + +impl SshAdmissionError { + pub fn is_retryable(&self) -> bool { + let Self::Rpc(status) = self else { + return false; + }; + match status.code() { + tonic::Code::Unavailable | tonic::Code::DeadlineExceeded => true, + tonic::Code::Unknown | tonic::Code::Internal | tonic::Code::Cancelled => { + std::error::Error::source(status) + .is_some_and(crate::transport_errors::is_expected_transport_close_error) + } + _ => false, + } + } +} + +#[derive(Clone, Debug)] +pub struct SshTarget { + pub endpoint: String, + pub gateway_name: String, + pub name: String, + pub workspace: String, + pub id: String, + /// Capability from the selected sandbox's `GetSandbox` reply. Look it up if unknown. + pub direct_ssh: Option, + pub replica: Option, + pub gateway_insecure: bool, + pub cleanup: SshCleanup, +} + +#[derive(Message)] +pub struct RelayGrant { + #[prost(oneof = "RelayAuthorization", tags = "1, 5")] + pub authorization: Option, + #[prost(string, tag = "2")] + pub endpoint: String, + #[prost(string, tag = "3")] + pub gateway_name: String, + #[prost(string, optional, tag = "4")] + pub replica: Option, +} + +#[derive(prost::Oneof)] +pub enum RelayAuthorization { + #[prost(message, tag = "1")] + Session(CreateSshSessionResponse), + #[prost(message, tag = "5")] + Direct(DirectSshRelay), +} + +#[derive(Message)] +pub struct DirectSshRelay { + #[prost(string, tag = "1")] + pub sandbox_id: String, + #[prost(bool, tag = "2")] + pub gateway_insecure: bool, + #[prost(message, optional, tag = "3")] + pub registration_timeout: Option, +} + +impl DirectSshRelay { + pub fn registration_timeout(&self) -> Result> { + self.registration_timeout + .as_ref() + .map(duration_to_std) + .transpose() + .into_diagnostic() + } +} + +impl RelayGrant { + fn validate(&self) -> Result<&str> { + match &self.authorization { + Some(RelayAuthorization::Session(session)) => { + validate_ssh_session_response(session).map_err(|err| { + miette::miette!("gateway returned invalid SSH session response: {err}") + })?; + Ok(&session.sandbox_id) + } + Some(RelayAuthorization::Direct(direct)) => { + validate_ssh_sandbox_id(&direct.sandbox_id).into_diagnostic()?; + direct.registration_timeout()?; + Ok(&direct.sandbox_id) + } + None => Err(miette::miette!("missing SSH handoff authorization")), + } + } +} + +pub struct PreparedProxy { + command: String, + cancel: oneshot::Sender<()>, + cleanup: tokio::task::JoinHandle>>, +} + +/// Work that must finish before an SSH command or TUI releases its runtime. +#[derive(Clone, Debug, Default)] +pub struct SshCleanup(tokio_util::task::TaskTracker); + +impl SshCleanup { + pub fn spawn( + &self, + future: impl Future + Send + 'static, + ) -> tokio::task::JoinHandle { + self.0.spawn(future) + } + + pub async fn drain(&self) { + self.0.close(); + self.0.wait().await; + } +} + +impl SshTarget { + pub fn new(endpoint: &str, gateway_name: &str, name: &str, workspace: &str, id: &str) -> Self { + Self { + endpoint: endpoint.into(), + gateway_name: gateway_name.into(), + name: name.into(), + workspace: workspace.into(), + id: id.into(), + direct_ssh: None, + replica: None, + gateway_insecure: false, + cleanup: SshCleanup::default(), + } + } + + pub fn lookup_request(&self) -> tonic::Request { + with_owner_hint(GetSandboxRequest { + name: self.name.clone(), + workspace_scope: Some(workspace_selector(self.workspace.clone())), + }) + } + + pub fn observe_lookup<'a>( + &mut self, + response: &'a tonic::Response, + ) -> Result<&'a Sandbox> { + let sandbox = response + .get_ref() + .sandbox + .as_ref() + .ok_or_else(|| miette::miette!("sandbox not found"))?; + if sandbox.object_id() != self.id { + return Err(SshAdmissionError::Replaced.into()); + } + let advertised = supports_direct_ssh(response)?; + if self.direct_ssh == Some(true) && !advertised { + return Err(SshAdmissionError::CapabilityLost.into()); + } + self.direct_ssh = Some(advertised); + self.replica = + owner_replica(response).and_then(|owner| owner.to_str().ok().map(str::to_owned)); + Ok(sandbox) + } + + pub async fn prepare( + &self, + mut client: Client, + registration_timeout: Option, + ) -> Result { + let mut target = Cow::Borrowed(self); + if target.direct_ssh.is_none() { + let response = client + .get_sandbox(target.lookup_request()) + .await + .map_err(SshAdmissionError::Rpc)?; + target.to_mut().observe_lookup(&response)?; + } + let authorization = if target.direct_ssh == Some(true) { + RelayAuthorization::Direct(DirectSshRelay { + sandbox_id: target.id.clone(), + gateway_insecure: target.gateway_insecure, + registration_timeout: registration_timeout + .map(duration_from_std) + .transpose() + .into_diagnostic()?, + }) + } else { + let request = CreateSshSessionRequest { + sandbox: self.name.clone(), + workspace_scope: Some(workspace_selector(self.workspace.clone())), + }; + let started = tokio::time::Instant::now(); + let session = loop { + match client.create_ssh_session(request.clone()).await { + Ok(response) => break response.into_inner(), + Err(status) + if status.code() == tonic::Code::FailedPrecondition + && registration_timeout + .is_some_and(|timeout| started.elapsed() < timeout) => + { + tokio::time::sleep(Duration::from_millis(50)).await; + } + Err(status) => return Err(SshAdmissionError::Rpc(status).into()), + } + }; + RelayAuthorization::Session(session) + }; + let revoke = match &authorization { + RelayAuthorization::Session(session) => { + Some(revoke_grant(client, session.token.clone())) + } + RelayAuthorization::Direct(_) => None, + }; + let grant = RelayGrant { + authorization: Some(authorization), + endpoint: target.endpoint.clone(), + gateway_name: target.gateway_name.clone(), + replica: target.replica.clone(), + }; + let setup = || { + if grant.validate()? != self.id { + return Err(SshAdmissionError::Replaced.into()); + } + if grant.encoded_len() > MAX_HANDOFF_SIZE { + return Err(miette::miette!("SSH handoff exceeds the size limit")); + } + let id = Uuid::new_v4(); + let listener = ipc::Listener::bind(id).into_diagnostic()?; + let handle = format!("{}-{id}", std::process::id()); + let exe = std::env::current_exe().into_diagnostic()?; + let command = + build_proxy_command(&exe.to_string_lossy(), &handle, &self.name, &self.workspace); + Ok((listener, command)) + }; + let (listener, command) = match setup() { + Ok(parts) => parts, + Err(error) => { + if let Some(revoke) = revoke { + self.cleanup.spawn(revoke).await.into_diagnostic()?; + } + return Err(error); + } + }; + let payload = grant.encode_to_vec(); + let (cancel, mut cancelled) = oneshot::channel(); + let cleanup = self.cleanup.spawn(async move { + let direct = revoke.is_none(); + let serve = async { + let mut peer = listener.accept().await?; + peer.write_u32(u32::try_from(payload.len()).map_err(std::io::Error::other)?) + .await?; + peer.write_all(&payload).await?; + let reply = peer.read_u8().await?; + if reply != 1 && (reply != DIRECT_SSH_REFUSED || !direct) { + return Err(std::io::ErrorKind::InvalidData.into()); + } + Ok::<_, std::io::Error>((peer, reply)) + }; + // Keep the peer until the issuing client has attempted revocation. + let peer = tokio::select! { + result = serve => result.ok(), + _ = &mut cancelled => None, + }; + let started = std::time::Instant::now(); + if let Some(revoke) = revoke { + revoke.await; + } + if let Some((mut peer, reply)) = peer { + let _ = peer.write_u8(1).await; + let handshake_wait = started.elapsed(); + if reply == DIRECT_SSH_REFUSED { + return Err(SshAdmissionError::Refused.into()); + } + if direct { + // gRPC can deliver a refusal in trailers after sending response headers. + tokio::select! { + biased; + status = peer.read_u8() => { + if matches!(status, Ok(DIRECT_SSH_REFUSED)) { + let _ = peer.write_u8(1).await; + return Err(SshAdmissionError::Refused.into()); + } + } + _ = cancelled => {} + } + } + Ok(Some(handshake_wait)) + } else { + Ok(None) + } + }); + Ok(PreparedProxy { + command, + cancel, + cleanup, + }) + } +} + +pub async fn revoke_grant(mut client: Client, token: String) { + let request = RevokeSshSessionRequest { + token, + allow_missing: true, + }; + if !matches!( + tokio::time::timeout(Duration::from_secs(2), client.revoke_ssh_session(request)).await, + Ok(Ok(_)) + ) { + eprintln!("Warning: could not revoke the SSH session token"); + } +} + +impl PreparedProxy { + pub fn command(&self) -> &str { + &self.command + } + + pub async fn run(self, operation: impl Future>) -> Result { + self.run_with_admission(operation) + .await + .map(|(value, _)| value) + } + + /// Return the time an admitted proxy spent waiting for any legacy revocation + /// so callers can exclude it from time attached to the sandbox. + pub async fn run_with_admission( + self, + operation: impl Future>, + ) -> Result<(T, Option)> { + let result = operation.await; + drop(self.cancel); + let revocation_wait = self.cleanup.await.into_diagnostic()??; + Ok((result?, revocation_wait)) + } +} + +pub async fn receive(handle: &str) -> Result<(RelayGrant, impl AsyncRead + AsyncWrite + Unpin)> { + let (pid, id) = handle + .split_once('-') + .ok_or_else(|| miette::miette!("invalid SSH handoff"))?; + let pid = pid.parse::().into_diagnostic()?; + let id = Uuid::parse_str(id).into_diagnostic()?; + #[cfg(unix)] + let mut peer = ipc::connect(id, pid).await.into_diagnostic()?; + #[cfg(windows)] + let mut peer = ipc::connect(id, pid).into_diagnostic()?; + let size = peer.read_u32().await.into_diagnostic()? as usize; + if size > MAX_HANDOFF_SIZE { + return Err(miette::miette!("SSH handoff exceeds the size limit")); + } + let mut payload = vec![0; size]; + peer.read_exact(&mut payload).await.into_diagnostic()?; + let grant = RelayGrant::decode(&payload[..]) + .map_err(|_| miette::miette!("invalid SSH handoff message"))?; + grant.validate()?; + Ok((grant, peer)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn transport_loss_requires_a_local_cause_for_ambiguous_statuses() { + let reset = std::io::Error::from(std::io::ErrorKind::ConnectionReset); + let local = tonic::Status::from_error(Box::new(reset)); + assert_eq!(local.code(), tonic::Code::Unknown); + assert!(SshAdmissionError::Rpc(local).is_retryable()); + for code in [ + tonic::Code::Unknown, + tonic::Code::Internal, + tonic::Code::Cancelled, + tonic::Code::PermissionDenied, + ] { + let remote = tonic::Status::new(code, "connection reset"); + assert!(!SshAdmissionError::Rpc(remote).is_retryable()); + } + } + + #[test] + fn a_replacement_cannot_authorize_the_selected_target() { + let mut target = SshTarget::new("endpoint", "gateway", "box", "team", "original"); + let mut response = tonic::Response::new(SandboxResponse { + sandbox: Some(Sandbox { + metadata: Some(crate::proto::datamodel::v1::ObjectMeta { + id: "replacement".into(), + ..Default::default() + }), + ..Default::default() + }), + ..Default::default() + }); + response + .metadata_mut() + .insert(crate::forward::DIRECT_SSH_HEADER, "1".parse().unwrap()); + assert!(target.observe_lookup(&response).is_err()); + assert_eq!(target.direct_ssh, None); + } + + #[tokio::test] + async fn direct_handoff_observes_admission_without_session_rpcs() { + let endpoint = "http://127.0.0.1:0"; + let client = OpenShellClient::with_interceptor( + Channel::from_static(endpoint).connect_lazy(), + |_| panic!("observed direct handoff issued an unexpected gateway RPC"), + ); + let mut target = SshTarget::new(endpoint, "gateway", "box", "team", "id-1"); + target.direct_ssh = Some(true); + target.gateway_insecure = true; + target.replica = Some("owner".into()); + + let timeout = Duration::from_nanos(2_500_003); + let proxy = target.prepare(client.clone(), Some(timeout)).await.unwrap(); + let handle = proxy.command().rsplit_once(' ').unwrap().1.to_owned(); + let ((), admitted) = proxy + .run_with_admission(async { + let (grant, mut peer) = receive(&handle).await?; + let Some(RelayAuthorization::Direct(direct)) = grant.authorization else { + panic!("missing direct SSH target"); + }; + assert_eq!(direct.sandbox_id, "id-1"); + assert!(direct.gateway_insecure); + assert_eq!(direct.registration_timeout()?, Some(timeout)); + assert_eq!(grant.endpoint, endpoint); + assert_eq!(grant.gateway_name, "gateway"); + assert_eq!(grant.replica.as_deref(), Some("owner")); + peer.write_u8(1).await.into_diagnostic()?; + assert_eq!(peer.read_u8().await.into_diagnostic()?, 1); + Ok(()) + }) + .await + .unwrap(); + assert!(admitted.is_some()); + + let proxy = target.prepare(client, None).await.unwrap(); + let ((), admitted) = proxy.run_with_admission(async { Ok(()) }).await.unwrap(); + assert!(admitted.is_none()); + } + + #[tokio::test] + async fn proxy_rejects_a_different_issuer_pid_before_reading_a_grant() { + let id = Uuid::new_v4(); + let listener = ipc::Listener::bind(id).unwrap(); + let handle = format!("{}-{id}", std::process::id() + 1); + // Leave the server alive without writing a frame. A client that trusts + // the handle alone would hang waiting for credentials. + let result = tokio::time::timeout(Duration::from_secs(2), receive(&handle)) + .await + .unwrap(); + let Err(error) = result else { + panic!("accepted an unrelated issuer") + }; + assert!( + error + .to_string() + .contains(&std::io::Error::from(std::io::ErrorKind::PermissionDenied).to_string()) + ); + drop(listener); + } +} diff --git a/crates/openshell-core/src/ssh_handoff/unix.rs b/crates/openshell-core/src/ssh_handoff/unix.rs new file mode 100644 index 0000000000..9fd03b7100 --- /dev/null +++ b/crates/openshell-core/src/ssh_handoff/unix.rs @@ -0,0 +1,55 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +use std::io; +use tokio::net::{UnixListener, UnixStream}; +use uuid::Uuid; + +pub struct Listener { + socket: UnixListener, + #[cfg(not(target_os = "linux"))] + _cleanup: crate::external_driver_socket::SocketCleanup, +} + +fn address(id: Uuid) -> String { + #[cfg(target_os = "linux")] + return format!("\0openshell-ssh-{id}"); + #[cfg(not(target_os = "linux"))] + return format!("/tmp/openshell-ssh-{id}.sock"); +} + +fn same_user(stream: &UnixStream) -> io::Result { + Ok(stream.peer_cred()?.uid() == rustix::process::geteuid().as_raw()) +} + +impl Listener { + pub fn bind(id: Uuid) -> io::Result { + let path = address(id); + let socket = UnixListener::bind(&path)?; + Ok(Self { + socket, + #[cfg(not(target_os = "linux"))] + _cleanup: crate::external_driver_socket::SocketCleanup::new(path.into()), + }) + } + + pub async fn accept(self) -> io::Result { + loop { + let (stream, _) = self.socket.accept().await?; + if same_user(&stream)? { + return Ok(stream); + } + } + } +} + +pub async fn connect(id: Uuid, expected_pid: u32) -> io::Result { + let stream = UnixStream::connect(address(id)).await?; + let peer = stream.peer_cred()?; + if peer.uid() != rustix::process::geteuid().as_raw() + || peer.pid().and_then(|pid| u32::try_from(pid).ok()) != Some(expected_pid) + { + return Err(io::ErrorKind::PermissionDenied.into()); + } + Ok(stream) +} diff --git a/crates/openshell-core/src/ssh_handoff/windows.rs b/crates/openshell-core/src/ssh_handoff/windows.rs new file mode 100644 index 0000000000..8a87dbcb83 --- /dev/null +++ b/crates/openshell-core/src/ssh_handoff/windows.rs @@ -0,0 +1,136 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +use std::{ + ffi::CStr, + io, + mem::MaybeUninit, + os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle}, + ptr, +}; +use tokio::net::windows::named_pipe::{ + ClientOptions, NamedPipeClient, NamedPipeServer, ServerOptions, +}; +use uuid::Uuid; +use windows_sys::Win32::{ + Foundation::LocalFree, + Security::{ + Authorization::{ + ConvertSidToStringSidA, ConvertStringSecurityDescriptorToSecurityDescriptorA, + SDDL_REVISION_1, + }, + GetTokenInformation, SECURITY_ATTRIBUTES, SECURITY_MAX_SID_SIZE, TOKEN_QUERY, TOKEN_USER, + TokenUser, + }, + System::{ + Pipes::GetNamedPipeServerProcessId, + Threading::{GetCurrentProcess, OpenProcessToken}, + }, +}; + +pub struct Listener(NamedPipeServer); + +fn address(id: Uuid) -> String { + format!(r"\\.\pipe\openshell-ssh-{id}") +} + +#[repr(C)] +struct UserInfo { + user: TOKEN_USER, + sid: [u8; SECURITY_MAX_SID_SIZE as usize], +} + +/// Read the process account SID. `TokenOwner` can instead designate a group. +#[allow(unsafe_code)] +fn current_user_sid() -> io::Result { + let mut token = ptr::null_mut(); + // SAFETY: token is writable and becomes an owned handle on success. + if unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &raw mut token) } == 0 { + return Err(io::Error::last_os_error()); + } + // SAFETY: OpenProcessToken returned a new handle. + let token = unsafe { OwnedHandle::from_raw_handle(token) }; + let mut info = MaybeUninit::::uninit(); + let mut len = 0; + // SAFETY: info is aligned and large enough for TOKEN_USER and the largest SID. + if unsafe { + GetTokenInformation( + token.as_raw_handle(), + TokenUser, + info.as_mut_ptr().cast(), + u32::try_from(size_of::()).map_err(io::Error::other)?, + &raw mut len, + ) + } == 0 + { + return Err(io::Error::last_os_error()); + } + let mut text = ptr::null_mut(); + // SAFETY: GetTokenInformation initialized user, whose SID points into info. + if unsafe { ConvertSidToStringSidA((*info.as_ptr()).user.User.Sid, &raw mut text) } == 0 { + return Err(io::Error::last_os_error()); + } + // SAFETY: the function returns a LocalAlloc-owned, NUL-terminated ASCII SID. + let sid = unsafe { CStr::from_ptr(text.cast()).to_string_lossy().into_owned() }; + unsafe { LocalFree(text.cast()) }; + Ok(sid) +} + +impl Listener { + #[allow(unsafe_code)] + pub fn bind(id: Uuid) -> io::Result { + // A protected DACL grants access only to the pipe owner. The default + // pipe DACL also grants read access to Everyone. + let sid = current_user_sid()?; + let sddl = format!("O:{sid}D:P(A;;GA;;;{sid})\0"); + let mut descriptor = ptr::null_mut(); + // SAFETY: the input is NUL terminated and descriptor is a writable out pointer. + if unsafe { + ConvertStringSecurityDescriptorToSecurityDescriptorA( + sddl.as_ptr(), + SDDL_REVISION_1, + &raw mut descriptor, + ptr::null_mut(), + ) + } == 0 + { + return Err(io::Error::last_os_error()); + } + let mut attributes = SECURITY_ATTRIBUTES { + nLength: u32::try_from(size_of::()) + .expect("SECURITY_ATTRIBUTES fits a DWORD"), + lpSecurityDescriptor: descriptor, + bInheritHandle: 0, + }; + // SAFETY: the descriptor and attributes remain valid through CreateNamedPipeW. + let pipe = unsafe { + ServerOptions::new() + .first_pipe_instance(true) + .max_instances(1) + .reject_remote_clients(true) + .create_with_security_attributes_raw(address(id), (&raw mut attributes).cast()) + }; + // SAFETY: the conversion above allocated descriptor with LocalAlloc. + unsafe { LocalFree(descriptor) }; + pipe.map(Self) + } + + pub async fn accept(self) -> io::Result { + self.0.connect().await?; + Ok(self.0) + } +} + +#[allow(unsafe_code)] +pub fn connect(id: Uuid, expected_pid: u32) -> io::Result { + let pipe = ClientOptions::new().open(address(id))?; + let mut pid = 0; + // SAFETY: pipe owns the live handle and pid is a writable DWORD. + if unsafe { GetNamedPipeServerProcessId(pipe.as_raw_handle(), &raw mut pid) } == 0 { + return Err(io::Error::last_os_error()); + } + if pid != expected_pid { + return Err(io::ErrorKind::PermissionDenied.into()); + } + Ok(pipe) +} diff --git a/crates/openshell-server/src/auth/authz.rs b/crates/openshell-server/src/auth/authz.rs index 943d4b79bb..7471ce04de 100644 --- a/crates/openshell-server/src/auth/authz.rs +++ b/crates/openshell-server/src/auth/authz.rs @@ -38,6 +38,16 @@ pub struct AuthzPolicy { pub scopes_enabled: bool, } +impl From<&openshell_core::config::OidcConfig> for AuthzPolicy { + fn from(oidc: &openshell_core::config::OidcConfig) -> Self { + Self { + admin_role: oidc.admin_role.clone(), + user_role: oidc.user_role.clone(), + scopes_enabled: !oidc.scopes_claim.is_empty(), + } + } +} + impl AuthzPolicy { /// Validate the policy configuration. /// diff --git a/crates/openshell-server/src/grpc/mutation_audit.rs b/crates/openshell-server/src/grpc/mutation_audit.rs index c3e56e14a1..8f30e49d43 100644 --- a/crates/openshell-server/src/grpc/mutation_audit.rs +++ b/crates/openshell-server/src/grpc/mutation_audit.rs @@ -503,11 +503,15 @@ pub(super) fn record_forward_relay( sandbox: &Sandbox, channel_id: &str, target: &relay_open::Target, + authenticated_by_principal: bool, ) { let data = match target { relay_open::Target::Tcp(target) => { Some(serde_json::json!({ "host": target.host, "port": target.port })) } + relay_open::Target::Ssh(_) if authenticated_by_principal => { + Some(serde_json::json!({ "target": "ssh", "admission": "gateway_principal" })) + } relay_open::Target::Ssh(_) => None, }; record_relay("forward", sandbox, channel_id, data); @@ -2280,6 +2284,56 @@ mod tests { assert_eq!(repeated["resources"], revoked["resources"]); } + #[tokio::test] + async fn direct_ssh_checks_the_selected_sandbox_and_audits_the_admitted_connection() { + use openshell_core::forward::DIRECT_SSH_HEADER; + use openshell_core::proto::GetSandboxRequest; + let mut state = test_server_state().await; + Arc::get_mut(&mut state).unwrap().admin_role = "openshell-admin".into(); + let mut supervisor = ready_sandbox(&state).await; + let service = OpenShellService::new(state); + let selected = service + .get_sandbox(authed_request(GetSandboxRequest { + name: "agent-01".into(), + workspace_scope: Some(workspace_selector("default")), + })) + .await + .unwrap(); + assert_eq!(selected.metadata().get(DIRECT_SSH_HEADER).unwrap(), "1"); + let forward = |id: &str| { + authed_request(client_stream(&[TcpForwardFrame { + payload: Some(tcp_forward_frame::Payload::Init(TcpForwardInit { + sandbox: "agent-01".into(), + workspace: "default".into(), + target: Some(tcp_forward_init::Target::DirectSshSandboxId(id.into())), + ..Default::default() + })), + }])) + }; + let id = selected.into_inner().sandbox.unwrap().metadata.unwrap().id; + for expected in [&id[..], "old-instance"] { + let mut request = forward(expected); + request + .extensions_mut() + .insert(crate::auth::principal::test_support::user("outsider")); + let result = service.forward_tcp(request).await; + assert_eq!(result.err().unwrap().code(), Code::NotFound); + } + let result = service.forward_tcp(forward("old-instance")).await; + assert_eq!(result.err().unwrap().code(), Code::FailedPrecondition); + assert!(supervisor.try_recv().is_err()); + + let (result, event) = record("ForwardTcp", service.forward_tcp(forward(&id))).await; + result.unwrap(); + assert_eq!( + event["resources"], + json!([ + default_workspace(), agent_sandbox(), + { "type": "forward", "uid": relay_channel(&mut supervisor), "data": {"target":"ssh","admission":"gateway_principal"} } + ]) + ); + } + #[tokio::test] async fn revoking_an_unknown_ssh_session_names_nothing() { let service = OpenShellService::new(test_server_state().await); diff --git a/crates/openshell-server/src/grpc/sandbox.rs b/crates/openshell-server/src/grpc/sandbox.rs index cdc701cbc1..602623fc1f 100644 --- a/crates/openshell-server/src/grpc/sandbox.rs +++ b/crates/openshell-server/src/grpc/sandbox.rs @@ -11,6 +11,8 @@ use crate::ServerState; use crate::auth::authenticator::{AuthFailureReason, AuthMechanism, AuthRejection}; +use crate::auth::authz::AuthzPolicy; +use crate::auth::identity::IdentityProvider; use crate::auth::workspace_authz::{ AuthorizedWorkspaceScope, MinWorkspaceRole, authorize_list_workspace_selector, authorize_sandbox_workspace, authorize_workspace, @@ -23,6 +25,7 @@ use crate::persistence::{ use crate::tracing_bus::CursoredEvent; use crate::watch_cursor::WatchCursor; use futures::future; +use openshell_core::forward::{DIRECT_SSH_HEADER, validate_ssh_sandbox_id}; use openshell_core::net::set_tcp_nodelay_best_effort; use openshell_core::proto::datamodel::v1::ObjectMeta; use openshell_core::proto::{ @@ -1045,6 +1048,33 @@ fn owner_requested(request: &Request) -> bool { .contains_key(openshell_core::replica_routing::OWNER_REQUEST_HEADER) } +/// 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, @@ -1076,6 +1106,12 @@ pub(super) async fn handle_get_sandbox( .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) } @@ -2922,7 +2958,12 @@ pub(super) async fn handle_forward_tcp( ) .await .map_err(|e| Status::unavailable(format!("supervisor relay failed: {e}")))?; - super::mutation_audit::record_forward_relay(&sandbox, &channel_id, &target); + 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(); @@ -2997,16 +3038,9 @@ impl Drop for ForwardConnectionGuard { } } -/// Reserve a relay slot for one `ForwardTcp` stream. -/// -/// `target.tcp` streams are authorized by the caller's gateway principal, which -/// `handle_forward_tcp` has already checked against the sandbox's workspace, so -/// they carry no session token and touch no store: the only per-connection -/// state is the in-memory per-sandbox connection count, kept in a budget apart -/// from SSH relays (see [`RelayBudget`]). `target.ssh` streams -/// keep requiring the `CreateSshSession` token because the process that opens -/// them is an ssh `ProxyCommand` that holds nothing else. A token supplied with -/// a TCP target (older clients) is still validated and counted per token. +/// 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, @@ -3016,36 +3050,47 @@ async fn acquire_forward_connection_guard( let sandbox_id = sandbox.object_id().to_string(); let budget = RelayBudget::of(init); let token = init.authorization_token.trim(); - if token.is_empty() { - if budget == RelayBudget::Ssh { - return Err(crate::auth::audit::reject_credential( - Some(principal), - AuthRejection::new( - AuthMechanism::SshSessionToken, - AuthFailureReason::MissingCredential, - Status::unauthenticated("authorization_token is required for SSH targets"), - ), + 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", )); } - acquire_sandbox_connection_slot(state, budget, &sandbox_id)?; - return Ok(ForwardConnectionGuard { - state: state.clone(), - token: None, - budget, - sandbox_id, - }); + 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 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)?; + 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: Some(token.to_string()), + token, budget, sandbox_id, }) @@ -3167,6 +3212,14 @@ fn validate_tcp_forward_init(init: &TcpForwardInit) -> Result { 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)?, )), @@ -4758,6 +4811,60 @@ mod tests { }) } + #[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") + )); + } + + #[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 + ); + } + } + fn sandbox_connection_count(state: &ServerState, budget: RelayBudget, sandbox_id: &str) -> u32 { budget .counts(state) @@ -5103,7 +5210,7 @@ mod tests { "sandbox service forward connection limit reached" ); - let _ssh = acquire(ssh("canary-ssh-token-a")) + 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")) @@ -5112,6 +5219,25 @@ mod tests { .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 @@ -5120,6 +5246,8 @@ mod tests { sandbox_connection_count(&state, RelayBudget::Service, sandbox.object_id()), 2 ); + drop(direct_guard); + assert!(acquire(ssh("canary-ssh-token-a")).await.is_ok()); } #[test] diff --git a/crates/openshell-server/src/multiplex.rs b/crates/openshell-server/src/multiplex.rs index 0479e7a443..685e070e97 100644 --- a/crates/openshell-server/src/multiplex.rs +++ b/crates/openshell-server/src/multiplex.rs @@ -321,11 +321,7 @@ impl MultiplexService { self.state.gateway_interceptors.clone(), Some(self.state.clone()), ); - let authz_policy = self.state.config.oidc.as_ref().map(|oidc| AuthzPolicy { - admin_role: oidc.admin_role.clone(), - user_role: oidc.user_role.clone(), - scopes_enabled: !oidc.scopes_claim.is_empty(), - }); + let authz_policy = self.state.config.oidc.as_ref().map(AuthzPolicy::from); let authenticator_chain = build_authenticator_chain(&self.state); let grpc_service = AuthGrpcRouter::with_peer_identity( GrpcRouter::new(openshell, reflection) @@ -1716,7 +1712,8 @@ mod tests { use tower::Service; #[derive(Clone)] - struct PostCommitTestInterceptor; + struct PostCommitTestInterceptor(&'static str); + const CREATE_SANDBOX_RPC: &str = "openshell.v1.OpenShell/CreateSandbox"; #[tonic::async_trait] impl GatewayInterceptor for PostCommitTestInterceptor { @@ -1730,7 +1727,7 @@ mod tests { bindings: vec![InterceptorBinding { id: "audit-create-sandbox".to_string(), selector: Some(InterceptorSelector { - rpc: "openshell.v1.OpenShell/CreateSandbox".to_string(), + rpc: self.0.to_string(), service: String::new(), method: String::new(), }), @@ -1774,13 +1771,16 @@ mod tests { Bytes::from(frame) } - async fn post_commit_test_runtime() -> (GatewayInterceptorRuntime, tokio::task::JoinHandle<()>) - { + async fn post_commit_test_runtime( + rpc: &'static str, + ) -> (GatewayInterceptorRuntime, tokio::task::JoinHandle<()>) { let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let address = listener.local_addr().unwrap(); let task = tokio::spawn(async move { tonic::transport::Server::builder() - .add_service(GatewayInterceptorServer::new(PostCommitTestInterceptor)) + .add_service(GatewayInterceptorServer::new(PostCommitTestInterceptor( + rpc, + ))) .serve_with_incoming(TcpListenerStream::new(listener)) .await .unwrap(); @@ -1796,6 +1796,66 @@ mod tests { (runtime, task) } + #[tokio::test] + async fn direct_ssh_preserves_ssh_session_interceptor_bindings() { + use openshell_core::forward::DIRECT_SSH_HEADER; + use openshell_core::proto::{ + GetSandboxRequest, Sandbox, SandboxPhase, TcpForwardFrame, TcpForwardInit, + datamodel::v1::ObjectMeta, open_shell_client::OpenShellClient, tcp_forward_frame, + tcp_forward_init, workspace_selector, + }; + for rpc in [ + "openshell.v1.OpenShell/CreateSshSession", + "openshell.v1.OpenShell/RevokeSshSession", + CREATE_SANDBOX_RPC, + ] { + let (runtime, task) = post_commit_test_runtime(rpc).await; + let mut state = crate::grpc::test_support::test_server_state().await; + Arc::get_mut(&mut state).unwrap().gateway_interceptors = Some(runtime); + let mut sandbox = Sandbox { + metadata: Some(ObjectMeta { + id: "sb-1".into(), + name: "agent".into(), + workspace: "default".into(), + ..Default::default() + }), + ..Default::default() + }; + sandbox.set_phase(SandboxPhase::Ready as i32); + state.store.put_message(&sandbox).await.unwrap(); + let mut client = OpenShellClient::new(OpenShellServer::with_interceptor( + OpenShellService::new(state), + crate::test_support::authenticate_as_dev_user, + )); + let lookup = GetSandboxRequest { + name: "agent".into(), + workspace_scope: Some(workspace_selector("default")), + }; + let response = client.get_sandbox(lookup).await.unwrap(); + assert_eq!( + response.metadata().contains_key(DIRECT_SSH_HEADER), + rpc == CREATE_SANDBOX_RPC, + "{rpc}" + ); + if rpc != CREATE_SANDBOX_RPC { + let frame = TcpForwardFrame { + payload: Some(tcp_forward_frame::Payload::Init(TcpForwardInit { + workspace: "default".into(), + sandbox: "agent".into(), + target: Some(tcp_forward_init::Target::DirectSshSandboxId("sb-1".into())), + ..Default::default() + })), + }; + let denied = client + .forward_tcp(tokio_stream::iter([frame])) + .await + .unwrap_err(); + assert_eq!(denied.code(), tonic::Code::PermissionDenied, "{rpc}"); + } + task.abort(); + } + } + #[test] fn uuid_request_id_generates_valid_uuid() { let mut maker = UuidRequestId; @@ -1995,7 +2055,7 @@ mod tests { #[tokio::test] async fn post_commit_decode_failure_preserves_committed_response() { - let (runtime, interceptor_task) = post_commit_test_runtime().await; + let (runtime, interceptor_task) = post_commit_test_runtime(CREATE_SANDBOX_RPC).await; let committed = Arc::new(AtomicUsize::new(0)); let committed_for_service = committed.clone(); let committed_body = Bytes::from_static(b"malformed committed gRPC response"); @@ -2043,7 +2103,7 @@ mod tests { &self, request: tonic::Request, ) -> Result, tonic::Status> { - let mut manifest = PostCommitTestInterceptor + let mut manifest = PostCommitTestInterceptor(CREATE_SANDBOX_RPC) .describe(request) .await? .into_inner(); @@ -2101,7 +2161,7 @@ mod tests { &self, request: tonic::Request, ) -> Result, tonic::Status> { - PostCommitTestInterceptor + PostCommitTestInterceptor(CREATE_SANDBOX_RPC) .snapshot_provider_profiles(request) .await } diff --git a/crates/openshell-tui/src/app.rs b/crates/openshell-tui/src/app.rs index a83fbdce55..35ba6b5823 100644 --- a/crates/openshell-tui/src/app.rs +++ b/crates/openshell-tui/src/app.rs @@ -324,8 +324,7 @@ pub struct CreateSandboxForm { /// When the create animation started (for pacman timing). pub anim_start: Option, /// Buffered create result — held until min display time elapses. - /// `Ok((name, workspace))` or `Err(message)`. - pub create_result: Option>, + pub create_result: Option>, } // --------------------------------------------------------------------------- @@ -605,6 +604,7 @@ pub struct App { // Active gateway connection pub gateway_name: String, pub endpoint: String, + pub gateway_insecure: bool, pub client: OpenShellClient>, pub status_text: String, @@ -994,6 +994,7 @@ impl App { splash_start: Some(Instant::now()), gateway_name, endpoint, + gateway_insecure: false, client, status_text: String::from("connecting..."), gateways: Vec::new(), diff --git a/crates/openshell-tui/src/event.rs b/crates/openshell-tui/src/event.rs index f24ab54ed7..36831d6b48 100644 --- a/crates/openshell-tui/src/event.rs +++ b/crates/openshell-tui/src/event.rs @@ -24,8 +24,8 @@ pub enum Event { ListRefreshCompleted(crate::ListRefreshResult), /// Completed per-sandbox draft-count refresh from a background task. DraftCountsRefreshCompleted(crate::DraftCountsRefreshResult), - /// Result of a create sandbox request: `Ok((name, workspace))` or `Err(message)`. - CreateResult(Result<(String, String), String>), + /// Identity returned by the create sandbox request. + CreateResult(Result), /// Result of creating a provider on the gateway: `Ok(name)` or `Err(message)`. ProviderCreateResult(Result), /// Provider detail fetched from gateway. diff --git a/crates/openshell-tui/src/lib.rs b/crates/openshell-tui/src/lib.rs index 0e807cd452..3f65e31a26 100644 --- a/crates/openshell-tui/src/lib.rs +++ b/crates/openshell-tui/src/lib.rs @@ -25,6 +25,7 @@ use openshell_core::auth::EdgeAuthInterceptor; use openshell_core::metadata::{ObjectId, ObjectLabels, ObjectName, ObjectWorkspace}; use openshell_core::proto::open_shell_client::OpenShellClient; use openshell_core::proto::{SandboxPhase, SandboxRestartPolicy}; +use openshell_core::ssh_handoff::{SshCleanup, SshTarget}; use ratatui::Terminal; use ratatui::backend::CrosstermBackend; use tokio::sync::mpsc; @@ -98,6 +99,28 @@ pub async fn run( endpoint: &str, workspace: &str, theme_mode: ThemeMode, +) -> Result<()> { + run_with_gateway_insecure( + channel, + interceptor, + gateway_name, + endpoint, + workspace, + theme_mode, + false, + ) + .await +} + +/// Launch the TUI with the TLS verification setting used to open its initial channel. +pub async fn run_with_gateway_insecure( + channel: Channel, + interceptor: EdgeAuthInterceptor, + gateway_name: &str, + endpoint: &str, + workspace: &str, + theme_mode: ThemeMode, + gateway_insecure: bool, ) -> Result<()> { // Detect theme *before* entering raw/alternate-screen mode. // The OSC 11 query temporarily enters raw mode itself; calling it @@ -112,6 +135,7 @@ pub async fn run( workspace.to_string(), detected_theme, ); + app.gateway_insecure = gateway_insecure; enable_raw_mode().into_diagnostic()?; let mut stdout = io::stdout(); @@ -128,6 +152,8 @@ pub async fn run( refresh_global_settings(&mut app).await; spawn_list_refresh(&mut app, events.sender()); + let ssh_cleanup = SshCleanup::default(); + let mut create_tasks = tokio::task::JoinSet::new(); while app.running { terminal .draw(|frame| ui::draw(frame, &mut app)) @@ -150,7 +176,12 @@ pub async fn run( } if app.pending_create_sandbox { app.pending_create_sandbox = false; - spawn_create_sandbox(&mut app, events.sender()); + spawn_create_sandbox( + &mut app, + events.sender(), + &mut create_tasks, + &ssh_cleanup, + ); start_anim_ticker(&mut app, events.sender()); } // --- Provider CRUD --- @@ -195,7 +226,8 @@ pub async fn run( } if app.pending_shell_connect { app.pending_shell_connect = false; - handle_shell_connect(&mut app, &mut terminal, &mut events).await?; + handle_shell_connect(&mut app, &mut terminal, &mut events, &ssh_cleanup) + .await?; } // --- Draft actions --- if app.pending_draft_approve { @@ -413,7 +445,7 @@ pub async fn run( h.abort(); } match result { - Some(Ok((name, create_workspace))) => { + Some(Ok(target)) => { app.create_form = None; let ports = std::mem::take(&mut app.pending_forward_ports); let command = std::mem::take(&mut app.pending_exec_command); @@ -427,17 +459,17 @@ pub async fn run( .join(", "); format!(" (forwarding port(s) {list})") }; - app.status_text = format!("Created sandbox: {name}{port_info}"); + app.status_text = + format!("Created sandbox: {}{port_info}", target.name); // If a command was specified, suspend TUI and exec it. if !command.is_empty() { - handle_exec_command( + run_sandbox_ssh( &mut app, &mut terminal, &mut events, - &name, + &target, &command, - &create_workspace, ) .await?; } @@ -497,6 +529,8 @@ pub async fn run( // Cancel any running background tasks. app.cancel_log_stream(); app.stop_anim(); + create_tasks.shutdown().await; + ssh_cleanup.drain().await; disable_raw_mode().into_diagnostic()?; execute!( @@ -559,6 +593,7 @@ async fn handle_gateway_switch(app: &mut App, tx: mpsc::UnboundedSender) app.client = OpenShellClient::with_interceptor(channel, interceptor); app.gateway_name = name; app.endpoint = endpoint; + app.gateway_insecure = false; app.reset_sandbox_state(); refresh_health(app).await; refresh_global_settings(app).await; @@ -945,243 +980,103 @@ async fn handle_shell_connect( app: &mut App, terminal: &mut Terminal>, events: &mut EventHandler, + cleanup: &SshCleanup, ) -> Result<()> { let sandbox_name = match app.selected_sandbox_name() { Some(n) => n.to_string(), None => return Ok(()), }; - let workspace = app.selected_sandbox_workspace(); - let session = { - let req = openshell_core::proto::CreateSshSessionRequest { - sandbox: sandbox_name.clone(), - workspace_scope: Some(openshell_core::proto::workspace_selector(workspace.clone())), - }; - match tokio::time::timeout(Duration::from_secs(5), app.client.create_ssh_session(req)).await - { - Ok(Ok(resp)) => resp.into_inner(), - Ok(Err(e)) => { - app.status_text = format!("SSH session failed: {}", e.message()); - return Ok(()); - } - Err(_) => { - app.status_text = "SSH session request timed out".to_string(); - return Ok(()); - } - } - }; - if let Err(err) = validate_ssh_session_response(&session) { - app.status_text = format!("gateway returned invalid SSH session response: {err}"); + let Some(id) = app.sandbox_ids.get(app.sandbox_selected) else { return Ok(()); - } - - // Step 3: Resolve gateway address (handle loopback override). - #[allow(clippy::cast_possible_truncation)] - let gateway_port_u16 = session.gateway_port as u16; - let (gateway_scheme, gateway_host, gateway_port) = resolve_ssh_gateway( - &session.gateway_scheme, - &session.gateway_host, - gateway_port_u16, - &app.endpoint, - ); - let gateway_url = format_gateway_url(&gateway_scheme, &gateway_host, gateway_port); - - // Step 4: Build the ProxyCommand using our own binary. - let exe = match std::env::current_exe() { - Ok(p) => p, - Err(e) => { - app.status_text = format!("failed to find executable: {e}"); - return Ok(()); - } }; - let proxy_command = build_proxy_command( - &exe.to_string_lossy(), - &gateway_url, - &sandbox_name, - &workspace, - &session.token, + let mut target = SshTarget::new( + &app.endpoint, &app.gateway_name, + &sandbox_name, + &app.selected_sandbox_workspace(), + id, ); - // Step 5: Build the SSH command. - let mut command = std::process::Command::new("ssh"); - command - .args(sandbox_ssh_args(&proxy_command, "ERROR")) - .arg("-tt") - .arg("-o") - .arg("RequestTTY=force") - .arg("-o") - .arg("SetEnv=TERM=xterm-256color") - .arg("sandbox") - .stdin(std::process::Stdio::inherit()) - .stdout(std::process::Stdio::inherit()) - .stderr(std::process::Stdio::inherit()); - - // Step 6: Cancel log stream and pause event handler before suspending. - app.cancel_log_stream(); - app.cancel_list_refresh(); - events.pause(); - // Wait for the reader task to finish its current poll cycle (tick_rate = 2s max). - tokio::time::sleep(Duration::from_millis(100)).await; - - // Step 7: Suspend TUI — leave alternate screen, disable raw mode. - execute!( - terminal.backend_mut(), - LeaveAlternateScreen, - DisableMouseCapture - ) - .into_diagnostic()?; - disable_raw_mode().into_diagnostic()?; - - // Step 8: Spawn SSH as child process and wait. - let status = tokio::task::spawn_blocking(move || command.status()).await; - match &status { - Ok(Ok(s)) if !s.success() => { - app.status_text = format!("ssh exited with status {s}"); - } - Ok(Err(e)) => { - app.status_text = format!("failed to launch ssh: {e}"); - } - Err(e) => { - app.status_text = format!("shell task failed: {e}"); - } - _ => { - app.status_text = format!("Disconnected from {sandbox_name}"); - } - } - - // Step 9: Resume and draw the TUI before accepting new terminal input. - enable_raw_mode().into_diagnostic()?; - execute!( - terminal.backend_mut(), - EnterAlternateScreen, - EnableMouseCapture - ) - .into_diagnostic()?; - terminal.clear().into_diagnostic()?; - terminal - .draw(|frame| ui::draw(frame, app)) - .into_diagnostic()?; - events.discard_pending(); - events.resume(); - spawn_list_refresh(app, events.sender()); - - Ok(()) + target.cleanup.clone_from(cleanup); + target.gateway_insecure = app.gateway_insecure; + run_sandbox_ssh(app, terminal, events, &target, &[]).await } -/// Suspend the TUI, execute a command on a sandbox via SSH, then resume. -/// -/// Mirrors `handle_shell_connect` but passes the user's command to SSH -/// instead of opening an interactive shell. The TUI is suspended while -/// the command runs; press Ctrl-C to stop and return to the TUI. -async fn handle_exec_command( +async fn run_sandbox_ssh( app: &mut App, terminal: &mut Terminal>, events: &mut EventHandler, - sandbox_name: &str, - command: &[String], - workspace: &str, + target: &SshTarget, + args: &[String], ) -> Result<()> { - let session = { - let req = openshell_core::proto::CreateSshSessionRequest { - sandbox: sandbox_name.to_string(), - workspace_scope: Some(openshell_core::proto::workspace_selector( - workspace.to_string(), - )), - }; - match tokio::time::timeout(Duration::from_secs(5), app.client.create_ssh_session(req)).await - { - Ok(Ok(resp)) => resp.into_inner(), - Ok(Err(e)) => { - app.status_text = format!("exec: SSH session failed: {}", e.message()); - return Ok(()); - } - Err(_) => { - app.status_text = "exec: SSH session timed out".to_string(); - return Ok(()); - } - } - }; - if let Err(err) = validate_ssh_session_response(&session) { - app.status_text = format!("exec: gateway returned invalid SSH session response: {err}"); + if target.gateway_name != app.gateway_name + || target.endpoint != app.endpoint + || target.gateway_insecure != app.gateway_insecure + { + app.status_text = "Gateway changed before SSH startup".into(); return Ok(()); } - - // Step 2: Resolve gateway and build ProxyCommand (same as handle_shell_connect). - #[allow(clippy::cast_possible_truncation)] - let gateway_port_u16 = session.gateway_port as u16; - let (gateway_scheme, gateway_host, gateway_port) = resolve_ssh_gateway( - &session.gateway_scheme, - &session.gateway_host, - gateway_port_u16, - &app.endpoint, - ); - let gateway_url = format_gateway_url(&gateway_scheme, &gateway_host, gateway_port); - - let exe = match std::env::current_exe() { - Ok(p) => p, - Err(e) => { - app.status_text = format!("exec: failed to find executable: {e}"); + let proxy = match tokio::time::timeout( + Duration::from_secs(5), + target.prepare(app.client.clone(), None), + ) + .await + { + Ok(Ok(proxy)) => proxy, + Ok(Err(error)) => { + app.status_text = format!("SSH session failed: {error}"); + return Ok(()); + } + Err(_) => { + app.status_text = "SSH session request timed out".into(); return Ok(()); } }; - let proxy_command = build_proxy_command( - &exe.to_string_lossy(), - &gateway_url, - sandbox_name, - workspace, - &session.token, - &app.gateway_name, - ); - - // Step 3: Build SSH command — same flags as handle_shell_connect but with - // the parsed command appended. Each argument is escaped individually so the - // remote shell parses it correctly. - let command_str = build_exec_command(command); - let mut ssh = std::process::Command::new("ssh"); - ssh.args(sandbox_ssh_args(&proxy_command, "ERROR")) + let mut command = std::process::Command::new("ssh"); + command + .args(sandbox_ssh_args(proxy.command(), "ERROR")) .arg("-tt") .arg("-o") .arg("RequestTTY=force") .arg("-o") .arg("SetEnv=TERM=xterm-256color") - .arg("sandbox") - .arg(command_str) - .stdin(std::process::Stdio::inherit()) - .stdout(std::process::Stdio::inherit()) - .stderr(std::process::Stdio::inherit()); - - // Step 4: Suspend TUI. - app.cancel_log_stream(); - app.cancel_list_refresh(); - events.pause(); - tokio::time::sleep(Duration::from_millis(100)).await; - - execute!( - terminal.backend_mut(), - LeaveAlternateScreen, - DisableMouseCapture - ) - .into_diagnostic()?; - disable_raw_mode().into_diagnostic()?; - - // Step 5: Run command — blocks until user Ctrl-C's or command exits. - let status = tokio::task::spawn_blocking(move || ssh.status()).await; - match &status { - Ok(Ok(s)) if !s.success() => { - app.status_text = format!("command exited with status {s}"); - } - Ok(Err(e)) => { - app.status_text = format!("failed to launch command: {e}"); - } - Err(e) => { - app.status_text = format!("exec task failed: {e}"); - } - _ => { - app.status_text = format!("Command finished on {sandbox_name}"); - } + .arg("sandbox"); + if !args.is_empty() { + command.arg(build_exec_command(args)); } + let result = proxy + .run(async { + // Cancel log stream and pause event handler before suspending. + app.cancel_log_stream(); + app.cancel_list_refresh(); + events.pause(); + // Wait for the reader task to finish its current poll cycle (tick_rate = 2s max). + tokio::time::sleep(Duration::from_millis(100)).await; + + // Suspend TUI — leave alternate screen, disable raw mode. + execute!( + terminal.backend_mut(), + LeaveAlternateScreen, + DisableMouseCapture + ) + .into_diagnostic()?; + disable_raw_mode().into_diagnostic()?; + + tokio::process::Command::from(command) + .kill_on_drop(true) + .status() + .await + .into_diagnostic() + }) + .await; + app.status_text = match result { + Ok(status) if !status.success() => format!("ssh exited with status {status}"), + Ok(_) if args.is_empty() => format!("Disconnected from {}", target.name), + Ok(_) => format!("Command finished on {}", target.name), + Err(error) => format!("failed to launch ssh: {error}"), + }; - // Step 6: Resume TUI. + // Resume and draw the TUI before accepting new terminal input. enable_raw_mode().into_diagnostic()?; execute!( terminal.backend_mut(), @@ -1190,6 +1085,9 @@ async fn handle_exec_command( ) .into_diagnostic()?; terminal.clear().into_diagnostic()?; + terminal + .draw(|frame| ui::draw(frame, app)) + .into_diagnostic()?; events.discard_pending(); events.resume(); spawn_list_refresh(app, events.sender()); @@ -1198,10 +1096,7 @@ async fn handle_exec_command( } // SSH utility functions are shared via openshell_core::forward. -use openshell_core::forward::{ - build_proxy_command, format_gateway_url, resolve_ssh_gateway, sandbox_ssh_args, shell_escape, - validate_ssh_session_response, -}; +use openshell_core::forward::{sandbox_ssh_args, shell_escape}; fn build_exec_command(command: &[String]) -> String { command @@ -1445,7 +1340,12 @@ fn start_anim_ticker(app: &mut App, tx: mpsc::UnboundedSender) { // Create sandbox (simplified — uses pre-selected provider names) // --------------------------------------------------------------------------- -fn spawn_create_sandbox(app: &mut App, tx: mpsc::UnboundedSender) { +fn spawn_create_sandbox( + app: &mut App, + tx: mpsc::UnboundedSender, + create_tasks: &mut tokio::task::JoinSet<()>, + cleanup: &SshCleanup, +) { let mut client = app.client.clone(); let Some((name, image, selected_providers, ports)) = app.create_form_data() else { return; @@ -1456,10 +1356,13 @@ fn spawn_create_sandbox(app: &mut App, tx: mpsc::UnboundedSender) { let endpoint = app.endpoint.clone(); let gateway_name = app.gateway_name.clone(); + let gateway_insecure = app.gateway_insecure; let need_ready = !ports.is_empty() || !app.pending_exec_command.is_empty(); let workspace = app.current_workspace.clone(); - tokio::spawn(async move { + while create_tasks.try_join_next().is_some() {} + let cleanup = cleanup.clone(); + create_tasks.spawn(async move { let has_custom_image = !image.is_empty(); let template = if has_custom_image { Some(openshell_core::proto::SandboxTemplate { @@ -1497,19 +1400,9 @@ fn spawn_create_sandbox(app: &mut App, tx: mpsc::UnboundedSender) { service_exposures: Vec::new(), }; - let sandbox_name = + let created = match tokio::time::timeout(Duration::from_secs(30), client.create_sandbox(req)).await { - Ok(Ok(resp)) => resp.into_inner().sandbox.map_or_else( - || "unknown".to_string(), - |s| { - let name = s.object_name().to_string(); - if name.is_empty() { - "unknown".to_string() - } else { - name - } - }, - ), + Ok(Ok(resp)) => resp.into_inner().sandbox, Ok(Err(e)) => { let _ = tx.send(Event::CreateResult(Err(e.message().to_string()))); return; @@ -1520,149 +1413,113 @@ fn spawn_create_sandbox(app: &mut App, tx: mpsc::UnboundedSender) { } }; + let Some(created) = + created.filter(|s| !s.object_id().is_empty() && !s.object_name().is_empty()) + else { + let _ = tx.send(Event::CreateResult(Err( + "gateway returned no sandbox identity".into(), + ))); + return; + }; + let mut target = SshTarget::new( + &endpoint, + &gateway_name, + created.object_name(), + &workspace, + created.object_id(), + ); + target.cleanup = cleanup; + target.gateway_insecure = gateway_insecure; // If ports or command are set, wait for Ready before finishing. if need_ready { - let mut attempts = 0; - let _sandbox_id = loop { - attempts += 1; - if attempts > 150 { - let _ = tx.send(Event::CreateResult(Err( - "timed out waiting for sandbox to be ready".to_string(), - ))); - return; - } - tokio::time::sleep(Duration::from_secs(2)).await; - - let req = openshell_core::proto::GetSandboxRequest { - name: sandbox_name.clone(), - workspace_scope: Some(openshell_core::proto::workspace_selector( - workspace.clone(), - )), - }; - // Retry on transient errors. - if let Ok(resp) = client.get_sandbox(req).await - && let Some(sandbox) = resp.into_inner().sandbox - { - if sandbox.phase() == SandboxPhase::Ready as i32 { - break sandbox.object_id().to_string(); - } - if sandbox.phase() == SandboxPhase::Error as i32 { - let _ = tx.send(Event::CreateResult(Err( - "sandbox entered error state".to_string() - ))); - return; - } - } - }; + if let Err(error) = wait_for_ssh_target(&mut client, &mut target).await { + let _ = tx.send(Event::CreateResult(Err(error.to_string()))); + return; + } // Start port forwards if requested. if !ports.is_empty() { - let forward_warnings = start_port_forwards( - &mut client, - &endpoint, - &gateway_name, - &sandbox_name, - &workspace, - &ports, - ) - .await; + let forward_warnings = start_port_forwards(&target, &client, &ports).await; if !forward_warnings.is_empty() { let _ = tx.send(Event::ForwardWarnings(forward_warnings)); } } } - let _ = tx.send(Event::CreateResult(Ok((sandbox_name, workspace)))); + let _ = tx.send(Event::CreateResult(Ok(target))); }); } +async fn wait_for_ssh_target(client: &mut TuiClient, target: &mut SshTarget) -> Result<()> { + tokio::time::timeout(Duration::from_mins(5), async { + loop { + tokio::time::sleep(Duration::from_secs(2)).await; + let response = match client.get_sandbox(target.lookup_request()).await { + Ok(response) => response, + Err(status) + if matches!( + status.code(), + Code::NotFound | Code::Unavailable | Code::DeadlineExceeded | Code::Aborted + ) => + { + continue; + } + Err(status) => return Err(status).into_diagnostic(), + }; + let phase = target.observe_lookup(&response)?.phase(); + if phase == SandboxPhase::Ready as i32 { + return Ok(()); + } + if phase == SandboxPhase::Error as i32 { + return Err(miette::miette!("sandbox entered error state")); + } + } + }) + .await + .map_err(|_| miette::miette!("timed out waiting for sandbox to be ready"))? +} + /// Start SSH port forwards for a sandbox that is already Ready. /// /// This is called from within the create-sandbox task so the pacman animation /// keeps running while forwards are being established. async fn start_port_forwards( - client: &mut TuiClient, - endpoint: &str, - gateway_name: &str, - sandbox_name: &str, - workspace: &str, + target: &SshTarget, + client: &TuiClient, specs: &[openshell_core::forward::ForwardSpec], ) -> Vec { let mut warnings = Vec::new(); - - // Create SSH session. - let session = { - let req = openshell_core::proto::CreateSshSessionRequest { - sandbox: sandbox_name.to_string(), - workspace_scope: Some(openshell_core::proto::workspace_selector( - workspace.to_string(), - )), - }; - match tokio::time::timeout(Duration::from_secs(10), client.create_ssh_session(req)).await { - Ok(Ok(resp)) => resp.into_inner(), - Ok(Err(e)) => { - warnings.push(format!("SSH session failed for forwards: {}", e.message())); - return warnings; + let sandbox_id = &target.id; + for spec in specs { + let proxy = match tokio::time::timeout( + Duration::from_secs(10), + target.prepare(client.clone(), None), + ) + .await + { + Ok(Ok(proxy)) => proxy, + Ok(Err(error)) => { + warnings.push(format!("SSH session failed for forwards: {error}")); + break; } Err(_) => { - warnings.push("SSH session timed out for forwards".to_string()); - return warnings; + warnings.push("SSH session timed out for forwards".into()); + break; } - } - }; - if let Err(err) = validate_ssh_session_response(&session) { - warnings.push(format!( - "gateway returned invalid SSH session response for forwards: {err}" - )); - return warnings; - } - - // Resolve gateway address. - #[allow(clippy::cast_possible_truncation)] - let gateway_port_u16 = session.gateway_port as u16; - let (gateway_scheme, gateway_host, gateway_port) = resolve_ssh_gateway( - &session.gateway_scheme, - &session.gateway_host, - gateway_port_u16, - endpoint, - ); - let gateway_url = format_gateway_url(&gateway_scheme, &gateway_host, gateway_port); - - // Build ProxyCommand. - let exe = match std::env::current_exe() { - Ok(p) => p, - Err(e) => { - warnings.push(format!("failed to find executable for forwards: {e}")); - return warnings; - } - }; - let proxy_command = build_proxy_command( - &exe.to_string_lossy(), - &gateway_url, - sandbox_name, - workspace, - &session.token, - gateway_name, - ); - - // Start a forward for each spec. - for spec in specs { + }; let ssh_forward_arg = spec.ssh_forward_arg(); let port_val = spec.port; let bind_addr = spec.bind_addr.clone(); let mut command = std::process::Command::new("ssh"); command - .args(sandbox_ssh_args(&proxy_command, "ERROR")) + .args(sandbox_ssh_args(proxy.command(), "ERROR")) .arg("-o") .arg("ConnectTimeout=15") .arg("-N") .arg("-f") .arg("-o") - .arg(format!( - "SetEnv=OPENSHELL_FORWARD_SANDBOX_ID={}", - session.sandbox_id - )) + .arg(format!("SetEnv=OPENSHELL_FORWARD_SANDBOX_ID={sandbox_id}")) .arg("-L") .arg(&ssh_forward_arg) .arg("sandbox") @@ -1670,56 +1527,42 @@ async fn start_port_forwards( .stdout(std::process::Stdio::null()) .stderr(std::process::Stdio::null()); - let sid = session.sandbox_id.clone(); - let name = sandbox_name.to_string(); - - // Use spawn (not status) so we don't block if SSH hangs during auth. - // SSH with -f forks to background after auth, but if auth stalls the - // parent process blocks indefinitely. We use spawn + wait_with_timeout - // to avoid freezing the create flow. - let result = tokio::task::spawn_blocking(move || { - match command.spawn() { - Ok(mut child) => { - // Wait up to 20 seconds for SSH to authenticate and fork. - let deadline = std::time::Instant::now() + Duration::from_secs(20); - loop { - match child.try_wait() { - Ok(Some(status)) => return Ok(status.success()), - Ok(None) => { - if std::time::Instant::now() >= deadline { - let _ = child.kill(); - return Err("timed out".to_string()); - } - std::thread::sleep(Duration::from_millis(200)); - } - Err(e) => return Err(e.to_string()), - } - } - } - Err(e) => Err(e.to_string()), - } - }) - .await; + let result = proxy + .run(async move { + let mut child = tokio::process::Command::from(command) + .kill_on_drop(true) + .spawn() + .into_diagnostic()?; + let status = tokio::time::timeout(Duration::from_secs(20), child.wait()) + .await + .into_diagnostic()? + .into_diagnostic()?; + Ok(status.success()) + }) + .await; match result { - Ok(Ok(true)) => { - if let Some(pid) = - openshell_core::forward::find_ssh_forward_pid(workspace, &name, &sid, port_val) - { + Ok(true) => { + if let Some(pid) = openshell_core::forward::find_ssh_forward_pid( + &target.workspace, + &target.name, + sandbox_id, + port_val, + ) { let _ = openshell_core::forward::write_forward_pid( - workspace, &name, port_val, pid, &sid, &bind_addr, + &target.workspace, + &target.name, + port_val, + pid, + sandbox_id, + &bind_addr, ); } } - Ok(Ok(false)) => { + Ok(false) => { warnings.push(format!("SSH forward exited with error for port {port_val}")); } - Ok(Err(e)) => { - warnings.push(format!("forward failed for port {port_val}: {e}")); - } - Err(e) => { - warnings.push(format!("forward task panicked for port {port_val}: {e}")); - } + Err(e) => warnings.push(format!("forward failed for port {port_val}: {e}")), } } diff --git a/crates/openshell-tui/src/ui/create_sandbox.rs b/crates/openshell-tui/src/ui/create_sandbox.rs index 5628dffc53..83ce8683ca 100644 --- a/crates/openshell-tui/src/ui/create_sandbox.rs +++ b/crates/openshell-tui/src/ui/create_sandbox.rs @@ -282,7 +282,7 @@ fn draw_creating(frame: &mut Frame<'_>, app: &App, area: Rect) { // Header — changes once result arrives. let (header, header_style) = match &form.create_result { - Some(Ok((name, _workspace))) => (format!("Created sandbox: {name}"), t.status_ok), + Some(Ok(target)) => (format!("Created sandbox: {}", target.name), t.status_ok), Some(Err(msg)) => (format!("Failed: {msg}"), t.status_err), None => ("Creating sandbox...".to_string(), t.text), }; diff --git a/docs/how-it-works/gateways/authentication.mdx b/docs/how-it-works/gateways/authentication.mdx index 84579be562..558203acbf 100644 --- a/docs/how-it-works/gateways/authentication.mdx +++ b/docs/how-it-works/gateways/authentication.mdx @@ -14,11 +14,13 @@ This page describes how the CLI resolves a gateway, authenticates with it, and w When any CLI command needs to talk to the gateway, it resolves the target through a priority chain: -1. `--gateway-endpoint ` flag (direct URL). +1. `--gateway-endpoint ` flag or `OPENSHELL_GATEWAY_ENDPOINT` environment variable (direct URL). 2. `-g ` flag. 3. `OPENSHELL_GATEWAY` environment variable. 4. Active gateway from `~/.config/openshell/active_gateway`, falling back to `/etc/openshell/active_gateway` when no user selection exists. +If you specify a profile on the command line and inherit an endpoint from the environment, or vice versa, the CLI uses credentials registered for the endpoint. To use a profile through a different address, such as a local tunnel, pass both `--gateway ` and `--gateway-endpoint ` together. + The CLI loads gateway metadata from `~/.config/openshell/gateways//metadata.json` first and falls back to `/etc/openshell/gateways//metadata.json` when no user entry exists. ## Authentication Status diff --git a/docs/how-it-works/sandboxes/overview.mdx b/docs/how-it-works/sandboxes/overview.mdx index b2cb2f13a5..7213b4a635 100644 --- a/docs/how-it-works/sandboxes/overview.mdx +++ b/docs/how-it-works/sandboxes/overview.mdx @@ -908,6 +908,7 @@ openshell sandbox ssh-config my-sandbox ``` Append the output to `~/.ssh/config` or use `--editor` on `sandbox create`/`sandbox connect` for automatic setup. +If the gateway URL contains credentials, a path, a query, or a fragment, register it under a gateway name and use that name when generating the SSH config. ## Transfer Files diff --git a/docs/observability/ocsf-json-export.mdx b/docs/observability/ocsf-json-export.mdx index 48047e68b8..5cec141c0b 100644 --- a/docs/observability/ocsf-json-export.mdx +++ b/docs/observability/ocsf-json-export.mdx @@ -66,6 +66,8 @@ The gateway also emits an API Activity event for each call a user or mTLS operat `resources` names the workspace and the resources the call acted on. An exec's `exec` resource has as its `uid` the `channel_id` from the exec's `command started` line in the gateway's sandbox logs, so you can match the record to the command's log lines. +For a direct SSH connection, the `ForwardTcp` event records the sandbox ID and a `forward` resource with the channel ID, `target: "ssh"` and `admission: "gateway_principal"`. The caller authenticates with its gateway credential. + Records never include credentials, tokens, environment variables, or standard input. Setting values and exec command arguments appear only when [enabled](/how-it-works/gateways/configuration#gateway-mutation-records). Without JSONL enabled, gateway OCSF events still appear as shorthand in console output, subject to the diagnostic log filter. Events associated with a sandbox also appear in its gateway log stream; gateway-wide events have no sandbox association. diff --git a/docs/security/best-practices.mdx b/docs/security/best-practices.mdx index b432124ce0..89df4157b7 100644 --- a/docs/security/best-practices.mdx +++ b/docs/security/best-practices.mdx @@ -290,13 +290,15 @@ Gateway transport uses TLS, with client certificate checks available where the d ### SSH Tunnel Authentication -SSH connections to sandboxes travel through the gateway over the sandbox supervisor's authenticated control path. Each SSH connect call also carries a short-lived session token scoped to a specific sandbox. The sandbox never exposes an SSH port on the network. Its SSH daemon listens on a local Unix socket that only the sandbox's own supervisor process can reach. +SSH connections travel through the gateway and the supervisor's authenticated control path. When the gateway advertises direct SSH, the CLI opens the relay with its gateway credentials and the immutable ID of the selected sandbox. The gateway checks SSH access, workspace membership and sandbox identity on each connection. A refusal ends the attempt. + +Older gateways, local-development identities and deployments that intercept SSH session creation or revocation use sandbox-scoped session tokens. Older clients can continue to use those tokens on a new gateway. Both modes share the per-sandbox SSH connection limit. The sandbox SSH daemon listens on a local Unix socket accessible to its supervisor. Service forwards (`openshell forward`) use the same relay path but carry no session token. The gateway authorizes each forwarded connection against the caller's gateway identity and workspace membership, and the per-sandbox service forward limit applies. | Aspect | Detail | |---|---| -| Default | Session tokens expire after 24 hours. Concurrent connections are limited to 3 per token, 20 SSH relays per sandbox, and 20 service forwards per sandbox. | +| Default | Concurrent connections are limited to 20 SSH relays and 20 service forwards per sandbox. Where session tokens are used, they expire after 24 hours and allow 3 concurrent connections per token. | | What you can change | Configure `ssh_session_ttl_secs` (set to 0 for no expiry), `max_ssh_connections_per_sandbox`, and `max_service_connections_per_sandbox`. | | Risk if relaxed | Longer TTLs or no expiry increase the window for stolen token reuse. Higher connection limits increase the blast radius of a compromised token. | | Recommendation | Keep the 24-hour default. Monitor connection counts through the TUI. | diff --git a/e2e/rust/Cargo.lock b/e2e/rust/Cargo.lock index 30897d9dee..b22918a9d1 100644 --- a/e2e/rust/Cargo.lock +++ b/e2e/rust/Cargo.lock @@ -2381,6 +2381,7 @@ dependencies = [ "thiserror", "tokio", "tokio-stream", + "tokio-util", "tonic", "tonic-prost", "tonic-prost-build", @@ -2388,6 +2389,7 @@ dependencies = [ "tracing", "url", "uuid", + "windows-sys 0.61.2", "zeroize", ] @@ -4149,6 +4151,7 @@ dependencies = [ "bytes", "futures-core", "futures-sink", + "futures-util", "libc", "pin-project-lite", "slab", diff --git a/examples/governance-interceptor/Cargo.lock b/examples/governance-interceptor/Cargo.lock index 1bb9facc7a..e2e510538d 100644 --- a/examples/governance-interceptor/Cargo.lock +++ b/examples/governance-interceptor/Cargo.lock @@ -2008,6 +2008,7 @@ dependencies = [ "thiserror", "tokio", "tokio-stream", + "tokio-util", "tonic", "tonic-prost", "tonic-prost-build", @@ -2015,6 +2016,7 @@ dependencies = [ "tracing", "url", "uuid", + "windows-sys 0.61.2", ] [[package]] @@ -3460,6 +3462,7 @@ dependencies = [ "bytes", "futures-core", "futures-sink", + "futures-util", "libc", "pin-project-lite", "slab", diff --git a/examples/isolation-backend-v8/Cargo.lock b/examples/isolation-backend-v8/Cargo.lock index 63edb47fa7..15ace00409 100644 --- a/examples/isolation-backend-v8/Cargo.lock +++ b/examples/isolation-backend-v8/Cargo.lock @@ -2337,6 +2337,7 @@ dependencies = [ "thiserror", "tokio", "tokio-stream", + "tokio-util", "tonic", "tonic-prost", "tonic-prost-build", @@ -2344,6 +2345,7 @@ dependencies = [ "tracing", "url", "uuid", + "windows-sys 0.61.2", "zeroize", ] @@ -3890,6 +3892,7 @@ dependencies = [ "bytes", "futures-core", "futures-sink", + "futures-util", "libc", "pin-project-lite", "slab", diff --git a/examples/supervisor-middleware-content-guard/Cargo.lock b/examples/supervisor-middleware-content-guard/Cargo.lock index 7a3c26f767..baf520a22f 100644 --- a/examples/supervisor-middleware-content-guard/Cargo.lock +++ b/examples/supervisor-middleware-content-guard/Cargo.lock @@ -2156,6 +2156,7 @@ dependencies = [ "thiserror", "tokio", "tokio-stream", + "tokio-util", "tonic", "tonic-prost", "tonic-prost-build", @@ -2163,6 +2164,7 @@ dependencies = [ "tracing", "url", "uuid", + "windows-sys 0.61.2", ] [[package]] @@ -3579,6 +3581,7 @@ dependencies = [ "bytes", "futures-core", "futures-sink", + "futures-util", "libc", "pin-project-lite", "slab", diff --git a/proto/openshell.proto b/proto/openshell.proto index 6ad3e9e5cd..4b6b626020 100644 --- a/proto/openshell.proto +++ b/proto/openshell.proto @@ -70,7 +70,9 @@ service OpenShell { }; } - // Fetch a sandbox by name. + // Fetch a sandbox by name. Response metadata x-openshell-direct-ssh: 1 + // advertises support for TcpForwardInit.direct_ssh_sandbox_id for this + // caller. ForwardTcp authorizes each connection independently. rpc GetSandbox(GetSandboxRequest) returns (SandboxResponse) { option (openshell.options.v1.authorization) = { auth_mode: "bearer" @@ -1950,11 +1952,9 @@ message CreateSshSessionRequest { // Create SSH session response. // -// Fields are interpolated into an SSH `ProxyCommand` string that OpenSSH -// executes through `/bin/sh -c` on the caller's workstation. Servers MUST -// uphold the charset contract below; clients MUST reject responses that -// violate it. The client's own escaping provides defense-in-depth, but -// narrow charsets close injection vectors at the trust boundary. +// Servers MUST uphold the charset contract below. Clients MUST validate the +// response before using it to open a relay. Send the session token only in the +// authenticated gateway RPCs that use it. Keep it out of SSH command lines. message CreateSshSessionResponse { reserved 8; reserved "expires_at_ms"; @@ -2179,9 +2179,14 @@ message TcpForwardInit { oneof target { SshRelayTarget ssh = 5; TcpRelayTarget tcp = 6; + // Open SSH using the authenticated gateway caller. Set this to the + // immutable ID returned by GetSandbox and leave authorization_token empty. + // Use only when GetSandbox advertises x-openshell-direct-ssh: 1. A denied + // direct connection must not be retried with a session token. + string direct_ssh_sandbox_id = 8; } - // Optional target-specific authorization token. SSH targets use this as the - // short-lived SSH session token issued by CreateSshSession. + // The ssh target requires the session token issued by CreateSshSession. + // The tcp target accepts tokens from older clients. string authorization_token = 7 [(openshell.options.v1.secret) = true]; } diff --git a/tests/suites/conformance/Cargo.lock b/tests/suites/conformance/Cargo.lock index 76506381c3..379e24d7be 100644 --- a/tests/suites/conformance/Cargo.lock +++ b/tests/suites/conformance/Cargo.lock @@ -2305,6 +2305,7 @@ dependencies = [ "thiserror 2.0.20", "tokio", "tokio-stream", + "tokio-util", "tonic", "tonic-prost", "tonic-prost-build", @@ -2312,6 +2313,7 @@ dependencies = [ "tracing", "url", "uuid", + "windows-sys 0.61.2", ] [[package]] @@ -3969,6 +3971,7 @@ dependencies = [ "bytes", "futures-core", "futures-sink", + "futures-util", "libc", "pin-project-lite", "slab", diff --git a/tests/suites/continuity/Cargo.lock b/tests/suites/continuity/Cargo.lock index 26179cb602..72692ffdb3 100644 --- a/tests/suites/continuity/Cargo.lock +++ b/tests/suites/continuity/Cargo.lock @@ -2292,6 +2292,7 @@ dependencies = [ "thiserror 2.0.20", "tokio", "tokio-stream", + "tokio-util", "tonic", "tonic-prost", "tonic-prost-build", @@ -2299,6 +2300,7 @@ dependencies = [ "tracing", "url", "uuid", + "windows-sys 0.61.2", ] [[package]] @@ -3956,6 +3958,7 @@ dependencies = [ "bytes", "futures-core", "futures-sink", + "futures-util", "libc", "pin-project-lite", "slab", diff --git a/tests/suites/drivers/podman/Cargo.lock b/tests/suites/drivers/podman/Cargo.lock index 560b02aa72..3476458392 100644 --- a/tests/suites/drivers/podman/Cargo.lock +++ b/tests/suites/drivers/podman/Cargo.lock @@ -2293,6 +2293,7 @@ dependencies = [ "thiserror 2.0.20", "tokio", "tokio-stream", + "tokio-util", "tonic", "tonic-prost", "tonic-prost-build", @@ -2300,6 +2301,7 @@ dependencies = [ "tracing", "url", "uuid", + "windows-sys 0.61.2", ] [[package]] @@ -3974,6 +3976,7 @@ dependencies = [ "bytes", "futures-core", "futures-sink", + "futures-util", "libc", "pin-project-lite", "slab", diff --git a/tests/suites/features/Cargo.lock b/tests/suites/features/Cargo.lock index b16d3fb67d..5ad17851b1 100644 --- a/tests/suites/features/Cargo.lock +++ b/tests/suites/features/Cargo.lock @@ -2365,6 +2365,7 @@ dependencies = [ "thiserror 2.0.20", "tokio", "tokio-stream", + "tokio-util", "tonic", "tonic-prost", "tonic-prost-build", @@ -2372,6 +2373,7 @@ dependencies = [ "tracing", "url", "uuid", + "windows-sys 0.61.2", ] [[package]] @@ -4041,6 +4043,7 @@ dependencies = [ "bytes", "futures-core", "futures-sink", + "futures-util", "libc", "pin-project-lite", "slab", diff --git a/tests/support/Cargo.lock b/tests/support/Cargo.lock index 0883511b5c..9dce973b48 100644 --- a/tests/support/Cargo.lock +++ b/tests/support/Cargo.lock @@ -2311,6 +2311,7 @@ dependencies = [ "thiserror 2.0.20", "tokio", "tokio-stream", + "tokio-util", "tonic", "tonic-prost", "tonic-prost-build", @@ -2318,6 +2319,7 @@ dependencies = [ "tracing", "url", "uuid", + "windows-sys 0.61.2", ] [[package]] @@ -3993,6 +3995,7 @@ dependencies = [ "bytes", "futures-core", "futures-sink", + "futures-util", "libc", "pin-project-lite", "slab", diff --git a/tests/testkit/Cargo.lock b/tests/testkit/Cargo.lock index bad3c82e89..6268ad101a 100644 --- a/tests/testkit/Cargo.lock +++ b/tests/testkit/Cargo.lock @@ -2284,6 +2284,7 @@ dependencies = [ "thiserror 2.0.20", "tokio", "tokio-stream", + "tokio-util", "tonic", "tonic-prost", "tonic-prost-build", @@ -2291,6 +2292,7 @@ dependencies = [ "tracing", "url", "uuid", + "windows-sys 0.61.2", ] [[package]] @@ -3948,6 +3950,7 @@ dependencies = [ "bytes", "futures-core", "futures-sink", + "futures-util", "libc", "pin-project-lite", "slab",