From 21da343c9f838bd9ac85dc61bf44889de1a72873 Mon Sep 17 00:00:00 2001 From: Evan Lezar Date: Fri, 24 Jul 2026 11:19:01 +0200 Subject: [PATCH 1/7] refactor(supervisor): pass agent proposal state explicitly (#2421) * test(supervisor-network): default L7 eval context in tests Signed-off-by: Evan Lezar * refactor(supervisor): pass agent proposal state explicitly Signed-off-by: Evan Lezar --------- Signed-off-by: Evan Lezar --- crates/openshell-core/Cargo.toml | 4 - crates/openshell-core/src/proposals.rs | 93 ++---- crates/openshell-sandbox/Cargo.toml | 1 - crates/openshell-sandbox/src/lib.rs | 303 +++++++++++++----- .../openshell-sandbox/src/sidecar_control.rs | 95 +++++- .../openshell-supervisor-network/Cargo.toml | 1 - .../src/l7/graphql.rs | 4 +- .../src/l7/middleware.rs | 16 +- .../src/l7/relay.rs | 139 +++----- .../src/l7/rest.rs | 126 +++++++- .../src/l7/token_grant_injection.rs | 4 +- .../src/l7/websocket.rs | 4 +- .../src/policy_local.rs | 77 +++-- .../openshell-supervisor-network/src/proxy.rs | 51 +-- .../openshell-supervisor-network/src/run.rs | 3 + .../openshell-supervisor-process/src/run.rs | 23 +- 16 files changed, 600 insertions(+), 344 deletions(-) diff --git a/crates/openshell-core/Cargo.toml b/crates/openshell-core/Cargo.toml index 53735a6bb8..495d069b68 100644 --- a/crates/openshell-core/Cargo.toml +++ b/crates/openshell-core/Cargo.toml @@ -34,10 +34,6 @@ default = ["telemetry"] ## `--no-default-features` (plus any other features you need) for a build that ## contains no telemetry endpoint, no HTTP client, and no emission code at all. telemetry = ["dep:reqwest", "dep:chrono"] -## Expose proposals::test_helpers (`ProposalsFlagGuard`) to downstream test -## code in other crates. Enabled by openshell-sandbox and -## openshell-supervisor-network dev builds. -test-helpers = [] [build-dependencies] tonic-prost-build = { workspace = true } diff --git a/crates/openshell-core/src/proposals.rs b/crates/openshell-core/src/proposals.rs index fcb6b110ce..53586629ca 100644 --- a/crates/openshell-core/src/proposals.rs +++ b/crates/openshell-core/src/proposals.rs @@ -1,83 +1,50 @@ // SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -//! Process-wide flag controlling agent-driven policy proposals. +//! Shared state controlling agent-driven policy proposals. //! //! Initialised once during sandbox start from the `agent_policy_proposals_enabled` -//! setting and updated by the policy poll loop when the setting changes. Read -//! by the `policy.local` route handler and by the skills installer to gate the -//! agent-controlled mutation surface. Tests use [`test_helpers::ProposalsFlagGuard`] -//! to flip the flag through a serialized guard. +//! setting and updated by the policy poll loop or authoritative sidecar control +//! when the setting changes. Read by the `policy.local` route handler and by +//! the skills installer to gate the agent-controlled mutation surface. use std::sync::Arc; -use std::sync::OnceLock; use std::sync::atomic::{AtomicBool, Ordering}; -/// Process-wide handle to the agent-proposals flag. +/// Shared handle for the agent-driven policy proposal surface. /// -/// Set once by `run_sandbox()` during start; subsequent attempts to set it are -/// ignored. The contained `AtomicBool` is updated by the policy poll loop. -pub static AGENT_PROPOSALS_ENABLED: OnceLock> = OnceLock::new(); - -/// Read the current value of the agent proposals feature flag. -/// -/// Returns `false` if the flag has not been initialized (e.g. during unit -/// tests), matching the documented default for the setting. -pub fn agent_proposals_enabled() -> bool { - AGENT_PROPOSALS_ENABLED - .get() - .is_some_and(|flag| flag.load(Ordering::Relaxed)) +/// Clones point at the same atomic value, so the sandbox orchestrator can pass +/// this into the process and network supervisors and then update it from the +/// settings poll loop or sidecar control. +#[derive(Clone, Debug)] +pub struct AgentProposals { + enabled: Arc, } -/// Test-only helpers shared across crates' test modules. -#[cfg(any(test, feature = "test-helpers"))] -pub mod test_helpers { - use std::sync::Arc; - use std::sync::LazyLock; - use std::sync::atomic::{AtomicBool, Ordering}; - use tokio::sync::MutexGuard; - - static PROPOSALS_FLAG_LOCK: LazyLock> = - LazyLock::new(|| tokio::sync::Mutex::new(())); - - /// Guard for tests that toggle the process-wide flag. - /// - /// Acquires a process-wide async mutex, swaps in the requested value, and - /// restores the previous value on drop. Hold the guard for the duration of - /// any code that reads `agent_proposals_enabled()`. - pub struct ProposalsFlagGuard { - prev: bool, - flag: Arc, - _lock: MutexGuard<'static, ()>, +impl AgentProposals { + #[must_use] + pub fn new(enabled: bool) -> Self { + Self { + enabled: Arc::new(AtomicBool::new(enabled)), + } } - impl ProposalsFlagGuard { - pub async fn set(enabled: bool) -> Self { - let lock = PROPOSALS_FLAG_LOCK.lock().await; - Self::with_lock(enabled, lock) - } + #[must_use] + pub fn enabled(&self) -> bool { + self.enabled.load(Ordering::Relaxed) + } - pub fn set_blocking(enabled: bool) -> Self { - let lock = PROPOSALS_FLAG_LOCK.blocking_lock(); - Self::with_lock(enabled, lock) - } + pub fn set_enabled(&self, enabled: bool) { + self.enabled.store(enabled, Ordering::Relaxed); + } - fn with_lock(enabled: bool, lock: MutexGuard<'static, ()>) -> Self { - let flag = super::AGENT_PROPOSALS_ENABLED - .get_or_init(|| Arc::new(AtomicBool::new(false))) - .clone(); - let prev = flag.swap(enabled, Ordering::Relaxed); - Self { - prev, - flag, - _lock: lock, - } - } + pub fn swap_enabled(&self, enabled: bool) -> bool { + self.enabled.swap(enabled, Ordering::Relaxed) } +} - impl Drop for ProposalsFlagGuard { - fn drop(&mut self) { - self.flag.store(self.prev, Ordering::Relaxed); - } +impl Default for AgentProposals { + fn default() -> Self { + Self::new(false) } } diff --git a/crates/openshell-sandbox/Cargo.toml b/crates/openshell-sandbox/Cargo.toml index f9c23cf60f..6a51635b14 100644 --- a/crates/openshell-sandbox/Cargo.toml +++ b/crates/openshell-sandbox/Cargo.toml @@ -60,7 +60,6 @@ default = ["telemetry"] telemetry = ["openshell-core/telemetry"] [dev-dependencies] -openshell-core = { path = "../openshell-core", features = ["test-helpers"] } tempfile = "3" temp-env = "0.3" tokio-tungstenite = { workspace = true } diff --git a/crates/openshell-sandbox/src/lib.rs b/crates/openshell-sandbox/src/lib.rs index 347e1509b6..271f82710c 100644 --- a/crates/openshell-sandbox/src/lib.rs +++ b/crates/openshell-sandbox/src/lib.rs @@ -52,17 +52,9 @@ use openshell_ocsf::{ /// `run_sandbox()` startup via `openshell_ocsf::ctx::set_ctx`. pub(crate) use openshell_ocsf::ctx::ctx as ocsf_ctx; -/// Process-wide flag for the agent-driven policy proposal surface. -/// Set once during `run_sandbox()` startup and updated by the settings poll -/// loop when `agent_policy_proposals_enabled` changes. Read by the -/// `policy.local` route handler and the L7 deny body's `next_steps` builder -/// to gate the agent-controlled mutation surface. Exposed `pub(crate)` so -/// unit tests in sibling modules can flip the flag through a serialized -/// guard (see `policy_local::tests::ProposalsFlagGuard`). -pub(crate) use openshell_core::proposals::AGENT_PROPOSALS_ENABLED; - use openshell_core::denial::DenialEvent; use openshell_core::policy::{NetworkMode, NetworkPolicy, ProxyPolicy, SandboxPolicy}; +use openshell_core::proposals::AgentProposals; use openshell_core::provider_credentials::ProviderCredentialState; use openshell_supervisor_network::opa::OpaEngine; use openshell_supervisor_process::process::ProcessEnforcementMode; @@ -160,27 +152,34 @@ pub async fn run_sandbox( // Load policy and initialize OPA engine let openshell_endpoint_for_proxy = openshell_endpoint.clone(); let sandbox_name_for_agg = sandbox.clone(); - let (mut policy, opa_engine, retained_proto, middleware_registry_status, loaded_policy_origin) = - if let Some(bootstrap) = sidecar_bootstrap.as_ref() { - let (policy, opa_engine, retained_proto, loaded_policy_origin) = - load_policy_from_sidecar_bootstrap(bootstrap)?; - ( - policy, - opa_engine, - retained_proto, - MiddlewareRegistryStatus::Synchronized, - loaded_policy_origin, - ) - } else { - load_policy( - sandbox_id.clone(), - sandbox, - openshell_endpoint.clone(), - policy_rules, - policy_data, - ) - .await? - }; + let ( + mut policy, + opa_engine, + retained_proto, + middleware_registry_status, + loaded_policy_origin, + initial_agent_proposals_enabled, + ) = if let Some(bootstrap) = sidecar_bootstrap.as_ref() { + let (policy, opa_engine, retained_proto, loaded_policy_origin) = + load_policy_from_sidecar_bootstrap(bootstrap)?; + ( + policy, + opa_engine, + retained_proto, + MiddlewareRegistryStatus::Synchronized, + loaded_policy_origin, + bootstrap.agent_proposals_enabled, + ) + } else { + load_policy( + sandbox_id.clone(), + sandbox, + openshell_endpoint.clone(), + policy_rules, + policy_data, + ) + .await? + }; // Override the policy's process identity with the driver-resolved UID/GID // from the pod environment. The policy defaults to the name "sandbox" which @@ -290,25 +289,23 @@ pub async fn run_sandbox( let provider_env = provider_credentials.child_env_with_gcp_resolved(); (provider_credentials, provider_env) }; + + // Shared agent-proposals feature flag. Seed from the same initial settings + // snapshot that produced the policy so networking and process setup agree + // before the poll loop starts reconciling later changes. + let agent_proposals = AgentProposals::new(initial_agent_proposals_enabled); + let process_control_writer = process_control_connection .as_ref() .map(|connection| connection.writer.clone()); let mut process_control_closed = None; if let Some(connection) = process_control_connection { process_control_closed = Some(connection.closed); - spawn_sidecar_control_update_watcher(connection.updates, provider_credentials.clone()); - } - - // Initialize the agent-proposals feature flag. Default false until the - // initial settings fetch (or the poll loop) tells us otherwise. The flag - // gates the skill install, the policy.local route handler, and the L7 - // deny body's `next_steps` field — see `agent_proposals_enabled()`. - let proposals_enabled = Arc::new(std::sync::atomic::AtomicBool::new(false)); - if AGENT_PROPOSALS_ENABLED - .set(proposals_enabled.clone()) - .is_err() - { - debug!("agent proposals flag already initialized, keeping existing"); + spawn_sidecar_control_update_watcher( + connection.updates, + provider_credentials.clone(), + agent_proposals.clone(), + ); } // Shared PID: set after process spawn so the proxy can look up @@ -389,6 +386,7 @@ pub async fn run_sandbox( inference_routes.as_deref(), denial_tx, activity_tx, + agent_proposals.clone(), workspace_rx.clone(), ) .await?, @@ -422,6 +420,7 @@ pub async fn run_sandbox( policy_proto: proto.clone(), provider_env_revision: provider_credentials.snapshot().revision, provider_child_env: provider_env.clone(), + agent_proposals_enabled: agent_proposals.enabled(), proxy_ca_cert_path: ca_paths.as_ref().map(|paths| paths.0.clone()), proxy_ca_bundle_path: ca_paths.as_ref().map(|paths| paths.1.clone()), }, @@ -591,6 +590,7 @@ pub async fn run_sandbox( ocsf_enabled: poll_ocsf_enabled, provider_credentials: poll_provider_credentials, policy_local_ctx: poll_policy_local, + agent_proposals: agent_proposals.clone(), middleware_registry_status, sidecar_control_publisher: sidecar_control_publisher.clone(), workspace_tx, @@ -710,6 +710,7 @@ pub async fn run_sandbox( provider_credentials, provider_env, ca_file_paths, + agent_proposals.clone(), #[cfg(target_os = "linux")] netns.as_ref(), #[cfg(target_os = "linux")] @@ -870,11 +871,12 @@ fn load_policy_from_sidecar_bootstrap( fn spawn_sidecar_control_update_watcher( mut updates: tokio::sync::mpsc::UnboundedReceiver, provider_credentials: ProviderCredentialState, + agent_proposals: AgentProposals, ) -> tokio::task::JoinHandle<()> { tokio::spawn(async move { while let Some(update) = updates.recv().await { match update { - sidecar_control::ControlUpdate::ProviderEnvUpdated { + sidecar_control::ControlUpdate::ProviderEnv { revision, provider_child_env, } => { @@ -895,7 +897,7 @@ fn spawn_sidecar_control_update_watcher( .build() ); } - sidecar_control::ControlUpdate::PolicyUpdated { + sidecar_control::ControlUpdate::Policy { policy_proto, policy_hash, config_revision, @@ -907,6 +909,19 @@ fn spawn_sidecar_control_update_watcher( "Received sidecar policy update for process supervisor" ); } + sidecar_control::ControlUpdate::AgentProposals { + enabled, + config_revision, + } => { + apply_agent_proposals_enabled( + &agent_proposals, + enabled, + "sidecar control", + Some(config_revision), + None, + skills::install_static_skills, + ); + } } } }) @@ -1831,6 +1846,7 @@ async fn load_policy( Option, MiddlewareRegistryStatus, LoadedPolicyOrigin, + bool, )> { // File mode: load OPA engine from rego rules + YAML data (dev override) if let (Some(policy_file), Some(data_file)) = (&policy_rules, &policy_data) { @@ -1879,6 +1895,7 @@ async fn load_policy( None, MiddlewareRegistryStatus::Synchronized, LoadedPolicyOrigin::LocalOverride, + false, )); } @@ -2060,6 +2077,7 @@ async fn load_policy( LoadedPolicyOrigin::Gateway { revision: loaded_policy_revision, }, + agent_proposals_enabled_from_settings(&snapshot.settings), )); } @@ -2504,6 +2522,7 @@ struct PolicyPollLoopContext { ocsf_enabled: Arc, provider_credentials: ProviderCredentialState, policy_local_ctx: Option>, + agent_proposals: AgentProposals, middleware_registry_status: MiddlewareRegistryStatus, sidecar_control_publisher: Option, workspace_tx: tokio::sync::watch::Sender, @@ -2623,6 +2642,14 @@ async fn run_policy_poll_loop(ctx: PolicyPollLoopContext) -> Result<()> { match initial_poll_disposition(&ctx.loaded_policy_origin, &result) { InitialPollDisposition::Acknowledge(candidate) => { apply_ocsf_json_setting(&ctx.ocsf_enabled, &result.settings); + apply_agent_proposals_enabled( + &ctx.agent_proposals, + agent_proposals_enabled_from_settings(&result.settings), + "initial settings poll", + Some(candidate.config_revision), + ctx.sidecar_control_publisher.as_ref(), + skills::install_static_skills, + ); current_config_revision = candidate.config_revision; current_policy_hash.clone_from(&candidate.policy_hash); current_middleware_services = result.supervisor_middleware_services; @@ -2639,6 +2666,14 @@ async fn run_policy_poll_loop(ctx: PolicyPollLoopContext) -> Result<()> { InitialPollDisposition::Reconcile => pending_result = Some(result), InitialPollDisposition::TrackOnly => { apply_ocsf_json_setting(&ctx.ocsf_enabled, &result.settings); + apply_agent_proposals_enabled( + &ctx.agent_proposals, + agent_proposals_enabled_from_settings(&result.settings), + "initial settings poll", + Some(result.config_revision), + ctx.sidecar_control_publisher.as_ref(), + skills::install_static_skills, + ); current_config_revision = result.config_revision; current_policy_hash = result.policy_hash.clone(); current_middleware_services = result.supervisor_middleware_services; @@ -2913,34 +2948,16 @@ async fn run_policy_poll_loop(ctx: PolicyPollLoopContext) -> Result<()> { // off picks up the surface without a recreate. We never uninstall on // a true→false transition: stale skill content on disk is harmless // because route_request and agent_next_steps both gate on the live - // atomic, so the agent that reads the skill will see 404s and an + // shared flag, so the agent that reads the skill will see 404s and an // empty `next_steps` array regardless. - if let Some(flag) = AGENT_PROPOSALS_ENABLED.get() { - let new_proposals = extract_bool_setting( - &result.settings, - openshell_core::settings::AGENT_POLICY_PROPOSALS_ENABLED_KEY, - ) - .unwrap_or(false); - let prev_proposals = flag.swap(new_proposals, Ordering::Relaxed); - if new_proposals != prev_proposals { - info!( - agent_policy_proposals_enabled = new_proposals, - "agent-driven policy proposals toggled" - ); - if new_proposals && !prev_proposals { - match skills::install_static_skills() { - Ok(installed) => info!( - path = %installed.policy_advisor.display(), - "Installed sandbox agent skill on toggle-on" - ), - Err(error) => warn!( - error = %error, - "Failed to install sandbox agent skill on toggle-on" - ), - } - } - } - } + apply_agent_proposals_enabled( + &ctx.agent_proposals, + agent_proposals_enabled_from_settings(&result.settings), + "settings poll", + Some(result.config_revision), + ctx.sidecar_control_publisher.as_ref(), + skills::install_static_skills, + ); current_config_revision = result.config_revision; if !reloads_gateway_policy { @@ -2979,6 +2996,52 @@ fn extract_bool_setting( }) } +fn agent_proposals_enabled_from_settings( + settings: &std::collections::HashMap, +) -> bool { + extract_bool_setting( + settings, + openshell_core::settings::AGENT_POLICY_PROPOSALS_ENABLED_KEY, + ) + .unwrap_or(false) +} + +fn apply_agent_proposals_enabled( + agent_proposals: &AgentProposals, + enabled: bool, + source: &'static str, + config_revision: Option, + sidecar_control_publisher: Option<&sidecar_control::Publisher>, + install_static_skills: impl FnOnce() -> Result, +) { + let previously_enabled = agent_proposals.swap_enabled(enabled); + if enabled == previously_enabled { + return; + } + + info!( + agent_policy_proposals_enabled = enabled, + source, config_revision, "agent-driven policy proposals toggled" + ); + + if let (Some(publisher), Some(config_revision)) = (sidecar_control_publisher, config_revision) { + publisher.publish_agent_proposals(enabled, config_revision); + } + + if enabled && !previously_enabled { + match install_static_skills() { + Ok(installed) => info!( + path = %installed.policy_advisor.display(), + "Installed sandbox agent skill on toggle-on" + ), + Err(error) => warn!( + error = %error, + "Failed to install sandbox agent skill on toggle-on" + ), + } + } +} + /// Log individual setting changes between two snapshots. fn log_setting_changes( old: &std::collections::HashMap, @@ -3060,7 +3123,7 @@ mod tests { use openshell_core::policy::{ FilesystemPolicy, LandlockPolicy, NetworkMode, NetworkPolicy, ProcessPolicy, ProxyPolicy, }; - use std::sync::atomic::{AtomicBool, Ordering}; + use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; fn proxy_policy(http_addr: Option) -> SandboxPolicy { SandboxPolicy { @@ -3132,9 +3195,13 @@ mod tests { 1, std::collections::HashMap::from([("TOKEN".to_string(), "old".to_string())]), ); - let handle = spawn_sidecar_control_update_watcher(rx, provider_credentials.clone()); + let handle = spawn_sidecar_control_update_watcher( + rx, + provider_credentials.clone(), + AgentProposals::default(), + ); - tx.send(sidecar_control::ControlUpdate::ProviderEnvUpdated { + tx.send(sidecar_control::ControlUpdate::ProviderEnv { revision: 2, provider_child_env: std::collections::HashMap::from([( "TOKEN".to_string(), @@ -3160,7 +3227,7 @@ mod tests { Some("new") ); - tx.send(sidecar_control::ControlUpdate::ProviderEnvUpdated { + tx.send(sidecar_control::ControlUpdate::ProviderEnv { revision: 1, provider_child_env: std::collections::HashMap::from([( "TOKEN".to_string(), @@ -3180,6 +3247,72 @@ mod tests { handle.abort(); } + #[tokio::test] + async fn sidecar_control_agent_proposals_update_flips_shared_state() { + let (tx, rx) = tokio::sync::mpsc::unbounded_channel(); + let provider_credentials = + ProviderCredentialState::from_child_env_snapshot(0, std::collections::HashMap::new()); + let agent_proposals = AgentProposals::new(true); + let handle = + spawn_sidecar_control_update_watcher(rx, provider_credentials, agent_proposals.clone()); + + tx.send(sidecar_control::ControlUpdate::AgentProposals { + enabled: false, + config_revision: 5, + }) + .unwrap(); + + timeout(Duration::from_secs(1), async { + loop { + if !agent_proposals.enabled() { + break; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .unwrap(); + handle.abort(); + } + + #[test] + fn apply_agent_proposals_enabled_installs_only_on_false_to_true() { + let agent_proposals = AgentProposals::default(); + let installs = AtomicUsize::new(0); + + apply_agent_proposals_enabled(&agent_proposals, true, "test", Some(1), None, || { + installs.fetch_add(1, Ordering::Relaxed); + Ok(skills::InstalledSkills { + policy_advisor: std::path::PathBuf::from("/tmp/policy_advisor.md"), + policy_advisor_skill: std::path::PathBuf::from("/tmp/SKILL.md"), + agents: None, + }) + }); + assert!(agent_proposals.enabled()); + assert_eq!(installs.load(Ordering::Relaxed), 1); + + apply_agent_proposals_enabled(&agent_proposals, true, "test", Some(2), None, || { + installs.fetch_add(1, Ordering::Relaxed); + Ok(skills::InstalledSkills { + policy_advisor: std::path::PathBuf::from("/tmp/policy_advisor.md"), + policy_advisor_skill: std::path::PathBuf::from("/tmp/SKILL.md"), + agents: None, + }) + }); + assert_eq!(installs.load(Ordering::Relaxed), 1); + + apply_agent_proposals_enabled(&agent_proposals, false, "test", Some(3), None, || { + installs.fetch_add(1, Ordering::Relaxed); + Ok(skills::InstalledSkills { + policy_advisor: std::path::PathBuf::from("/tmp/policy_advisor.md"), + policy_advisor_skill: std::path::PathBuf::from("/tmp/SKILL.md"), + agents: None, + }) + }); + assert!(!agent_proposals.enabled()); + assert_eq!(installs.load(Ordering::Relaxed), 1); + } + #[test] fn apply_ocsf_json_setting_enables_from_initial_settings_snapshot() { let enabled = AtomicBool::new(false); @@ -3201,6 +3334,24 @@ mod tests { assert!(!enabled.load(Ordering::Relaxed)); } + #[test] + fn agent_proposals_setting_enables_from_initial_settings_snapshot() { + let mut settings = std::collections::HashMap::new(); + settings.insert( + openshell_core::settings::AGENT_POLICY_PROPOSALS_ENABLED_KEY.to_string(), + effective_bool(true), + ); + + assert!(agent_proposals_enabled_from_settings(&settings)); + } + + #[test] + fn agent_proposals_setting_defaults_false_when_unset() { + let settings = std::collections::HashMap::new(); + + assert!(!agent_proposals_enabled_from_settings(&settings)); + } + // ---- Policy disk discovery tests ---- #[test] diff --git a/crates/openshell-sandbox/src/sidecar_control.rs b/crates/openshell-sandbox/src/sidecar_control.rs index c98dbc33bf..8cc2854e41 100644 --- a/crates/openshell-sandbox/src/sidecar_control.rs +++ b/crates/openshell-sandbox/src/sidecar_control.rs @@ -25,6 +25,7 @@ pub struct BootstrapData { pub policy_proto: openshell_core::proto::SandboxPolicy, pub provider_env_revision: u64, pub provider_child_env: HashMap, + pub agent_proposals_enabled: bool, pub proxy_ca_cert_path: Option, pub proxy_ca_bundle_path: Option, } @@ -44,15 +45,19 @@ pub struct ExpectedPeer { #[derive(Debug, Clone)] pub enum ControlUpdate { - ProviderEnvUpdated { + ProviderEnv { revision: u64, provider_child_env: HashMap, }, - PolicyUpdated { + Policy { policy_proto: Box, policy_hash: String, config_revision: u64, }, + AgentProposals { + enabled: bool, + config_revision: u64, + }, } #[derive(Clone)] @@ -95,6 +100,21 @@ impl Publisher { config_revision, }); } + + pub fn publish_agent_proposals(&self, enabled: bool, config_revision: u64) { + { + let mut state = self.state.write().expect("sidecar control state poisoned"); + if state.agent_proposals_enabled == enabled { + return; + } + state.agent_proposals_enabled = enabled; + } + + let _ = self.updates.send(WireServerMessage::AgentProposalsUpdated { + enabled, + config_revision, + }); + } } pub struct ServerHandle { @@ -145,6 +165,7 @@ enum WireServerMessage { policy_proto: Vec, provider_env_revision: u64, provider_child_env: HashMap, + agent_proposals_enabled: bool, proxy_ca_cert_path: Option, proxy_ca_bundle_path: Option, }, @@ -157,6 +178,10 @@ enum WireServerMessage { policy_hash: String, config_revision: u64, }, + AgentProposalsUpdated { + enabled: bool, + config_revision: u64, + }, } impl BootstrapData { @@ -166,6 +191,7 @@ impl BootstrapData { policy_proto: self.policy_proto.encode_to_vec(), provider_env_revision: self.provider_env_revision, provider_child_env: self.provider_child_env.clone(), + agent_proposals_enabled: self.agent_proposals_enabled, proxy_ca_cert_path: self .proxy_ca_cert_path .as_ref() @@ -186,6 +212,7 @@ impl TryFrom for BootstrapData { policy_proto, provider_env_revision, provider_child_env, + agent_proposals_enabled, proxy_ca_cert_path, proxy_ca_bundle_path, } = message @@ -203,6 +230,7 @@ impl TryFrom for BootstrapData { policy_proto, provider_env_revision, provider_child_env, + agent_proposals_enabled, proxy_ca_cert_path: proxy_ca_cert_path.map(PathBuf::from), proxy_ca_bundle_path: proxy_ca_bundle_path.map(PathBuf::from), }) @@ -217,7 +245,7 @@ impl TryFrom for ControlUpdate { WireServerMessage::ProviderEnvUpdated { revision, provider_child_env, - } => Ok(Self::ProviderEnvUpdated { + } => Ok(Self::ProviderEnv { revision, provider_child_env, }), @@ -230,12 +258,19 @@ impl TryFrom for ControlUpdate { openshell_core::proto::SandboxPolicy::decode(policy_proto.as_slice()) .into_diagnostic() .wrap_err("failed to decode sidecar policy update")?; - Ok(Self::PolicyUpdated { + Ok(Self::Policy { policy_proto: Box::new(policy_proto), policy_hash, config_revision, }) } + WireServerMessage::AgentProposalsUpdated { + enabled, + config_revision, + } => Ok(Self::AgentProposals { + enabled, + config_revision, + }), WireServerMessage::BootstrapResponse { .. } => Err(miette::miette!( "unexpected sidecar bootstrap response after initial handshake" )), @@ -407,13 +442,16 @@ async fn handle_connection( } } + // Subscribe before taking the bootstrap snapshot so an update can neither + // be missed between the snapshot and the live update stream nor omitted + // from the snapshot itself. + let mut update_rx = updates.subscribe(); let bootstrap = { let state = state.read().expect("sidecar control state poisoned"); state.to_wire() }; write_json_line(&mut writer, &bootstrap).await?; - let mut update_rx = updates.subscribe(); loop { tokio::select! { line = lines.next_line() => { @@ -583,6 +621,7 @@ mod tests { }, provider_env_revision: 3, provider_child_env: env.clone(), + agent_proposals_enabled: true, proxy_ca_cert_path: Some(PathBuf::from("/tmp/ca.pem")), proxy_ca_bundle_path: Some(PathBuf::from("/tmp/bundle.pem")), }; @@ -595,6 +634,7 @@ mod tests { assert_eq!(received.policy_proto.version, 7); assert_eq!(received.provider_env_revision, 3); assert_eq!(received.provider_child_env, env); + assert!(received.agent_proposals_enabled); assert_eq!( received.proxy_ca_cert_path, Some(PathBuf::from("/tmp/ca.pem")) @@ -605,6 +645,46 @@ mod tests { ); } + #[tokio::test] + async fn agent_proposals_update_is_delivered_to_process_client() { + let dir = tempfile::tempdir().unwrap(); + let socket = dir.path().join("control.sock"); + let server = spawn_server( + &socket, + BootstrapData { + policy_proto: SandboxPolicy::default(), + provider_env_revision: 0, + provider_child_env: HashMap::new(), + agent_proposals_enabled: false, + proxy_ca_cert_path: None, + proxy_ca_bundle_path: None, + }, + current_peer(), + ) + .unwrap(); + let publisher = server.publisher(); + let (_bootstrap, mut connection) = connect_process_client(&socket, Duration::from_secs(1)) + .await + .unwrap(); + + publisher.publish_agent_proposals(true, 9); + + let update = tokio::time::timeout(Duration::from_secs(1), connection.updates.recv()) + .await + .unwrap() + .unwrap(); + match update { + ControlUpdate::AgentProposals { + enabled, + config_revision, + } => { + assert!(enabled); + assert_eq!(config_revision, 9); + } + other => panic!("unexpected sidecar update: {other:?}"), + } + } + #[tokio::test] async fn entrypoint_started_is_delivered_to_server() { let dir = tempfile::tempdir().unwrap(); @@ -615,6 +695,7 @@ mod tests { policy_proto: SandboxPolicy::default(), provider_env_revision: 0, provider_child_env: HashMap::new(), + agent_proposals_enabled: false, proxy_ca_cert_path: None, proxy_ca_bundle_path: None, }, @@ -655,6 +736,7 @@ mod tests { policy_proto: SandboxPolicy::default(), provider_env_revision: 0, provider_child_env: HashMap::new(), + agent_proposals_enabled: false, proxy_ca_cert_path: None, proxy_ca_bundle_path: None, }, @@ -688,6 +770,7 @@ mod tests { policy_proto: SandboxPolicy::default(), provider_env_revision: 0, provider_child_env: HashMap::new(), + agent_proposals_enabled: false, proxy_ca_cert_path: None, proxy_ca_bundle_path: None, }, @@ -716,6 +799,7 @@ mod tests { policy_proto: SandboxPolicy::default(), provider_env_revision: 0, provider_child_env: HashMap::new(), + agent_proposals_enabled: false, proxy_ca_cert_path: None, proxy_ca_bundle_path: None, }, @@ -745,6 +829,7 @@ mod tests { policy_proto: SandboxPolicy::default(), provider_env_revision: 0, provider_child_env: HashMap::new(), + agent_proposals_enabled: false, proxy_ca_cert_path: None, proxy_ca_bundle_path: None, }, diff --git a/crates/openshell-supervisor-network/Cargo.toml b/crates/openshell-supervisor-network/Cargo.toml index 1449276f4f..008bf1104b 100644 --- a/crates/openshell-supervisor-network/Cargo.toml +++ b/crates/openshell-supervisor-network/Cargo.toml @@ -50,7 +50,6 @@ uuid = { workspace = true } webpki-roots = { workspace = true } [dev-dependencies] -openshell-core = { path = "../openshell-core", features = ["test-helpers"] } openshell-supervisor-middleware-builtins = { path = "../openshell-supervisor-middleware-builtins" } tempfile = "3" tonic = { workspace = true } diff --git a/crates/openshell-supervisor-network/src/l7/graphql.rs b/crates/openshell-supervisor-network/src/l7/graphql.rs index 12979f0b19..2569bc68fa 100644 --- a/crates/openshell-supervisor-network/src/l7/graphql.rs +++ b/crates/openshell-supervisor-network/src/l7/graphql.rs @@ -801,9 +801,7 @@ network_policies: ancestors: Vec::new(), cmdline_paths: Vec::new(), secret_resolver: None, - activity_tx: None, - dynamic_credentials: None, - token_grant_resolver: None, + ..Default::default() }; let request_info = crate::l7::L7RequestInfo { action: req.action, diff --git a/crates/openshell-supervisor-network/src/l7/middleware.rs b/crates/openshell-supervisor-network/src/l7/middleware.rs index 263d886f28..28f91c3bb7 100644 --- a/crates/openshell-supervisor-network/src/l7/middleware.rs +++ b/crates/openshell-supervisor-network/src/l7/middleware.rs @@ -215,11 +215,7 @@ pub async fn send_middleware_rejection_response, redacted_target: &str, ) -> Result<()> { - let context = Some(crate::l7::rest::DenyResponseContext { - host: Some(&ctx.host), - port: Some(ctx.port), - binary: Some(&ctx.binary_path), - }); + let context = Some(crate::l7::rest::DenyResponseContext::from_l7_context(ctx)); if let Some(denial) = denial { crate::l7::rest::send_middleware_deny_response( req, @@ -562,9 +558,7 @@ mod tests { ancestors: Vec::new(), cmdline_paths: Vec::new(), secret_resolver: None, - activity_tx: None, - dynamic_credentials: None, - token_grant_resolver: None, + ..Default::default() }; let req = crate::l7::provider::L7Request { action: "POST".into(), @@ -602,8 +596,6 @@ mod tests { #[tokio::test] async fn middleware_failure_uses_platform_response_without_policy_guidance() { - let _proposals = - openshell_core::proposals::test_helpers::ProposalsFlagGuard::set(true).await; let ctx = L7EvalContext { host: "api.example.test".into(), port: 443, @@ -612,9 +604,7 @@ mod tests { ancestors: Vec::new(), cmdline_paths: Vec::new(), secret_resolver: None, - activity_tx: None, - dynamic_credentials: None, - token_grant_resolver: None, + ..Default::default() }; let req = crate::l7::provider::L7Request { action: "POST".into(), diff --git a/crates/openshell-supervisor-network/src/l7/relay.rs b/crates/openshell-supervisor-network/src/l7/relay.rs index 4bf1bb0bc0..fa2eab4ad7 100644 --- a/crates/openshell-supervisor-network/src/l7/relay.rs +++ b/crates/openshell-supervisor-network/src/l7/relay.rs @@ -34,6 +34,7 @@ use tokio::io::{AsyncRead, AsyncWrite, AsyncWriteExt}; use tracing::{debug, warn}; /// Context for L7 request policy evaluation. +#[cfg_attr(test, derive(Default))] pub struct L7EvalContext { /// Host from the CONNECT request. pub host: String, @@ -62,6 +63,8 @@ pub struct L7EvalContext { /// Dynamic token grant resolver for endpoint-bound credentials. pub(crate) token_grant_resolver: Option>, + /// Shared feature state for agent-driven policy proposals. + pub(crate) agent_proposals: openshell_core::proposals::AgentProposals, } #[derive(Default)] @@ -176,11 +179,13 @@ where engine_type_for_protocol(config.protocol), ); crate::l7::rest::RestProvider::default() - .deny( + .deny_with_redacted_target( req, &ctx.policy_name, crate::l7::rest::UNSUPPORTED_H2C_UPGRADE_DETAIL, client, + None, + Some(crate::l7::rest::DenyResponseContext::from_l7_context(ctx)), ) .await?; Ok(true) @@ -296,11 +301,13 @@ where let Some(config) = select_l7_config_for_path(configs, &req.target) else { crate::l7::rest::RestProvider::default() - .deny( + .deny_with_redacted_target( &req, &ctx.policy_name, "no L7 endpoint path matched request", client, + None, + Some(crate::l7::rest::DenyResponseContext::from_l7_context(ctx)), ) .await?; return Ok(()); @@ -416,11 +423,7 @@ where "websocket endpoint requires a valid WebSocket upgrade request", client, Some(&redacted_target), - Some(crate::l7::rest::DenyResponseContext { - host: Some(&ctx.host), - port: Some(ctx.port), - binary: Some(&ctx.binary_path), - }), + Some(crate::l7::rest::DenyResponseContext::from_l7_context(ctx)), ) .await?; return Ok(()); @@ -551,11 +554,7 @@ where &reason, client, Some(&redacted_target), - Some(crate::l7::rest::DenyResponseContext { - host: Some(&ctx.host), - port: Some(ctx.port), - binary: Some(&ctx.binary_path), - }), + Some(crate::l7::rest::DenyResponseContext::from_l7_context(ctx)), ) .await?; return Ok(()); @@ -884,11 +883,7 @@ where "websocket endpoint requires a valid WebSocket upgrade request", client, Some(&redacted_target), - Some(crate::l7::rest::DenyResponseContext { - host: Some(&ctx.host), - port: Some(ctx.port), - binary: Some(&ctx.binary_path), - }), + Some(crate::l7::rest::DenyResponseContext::from_l7_context(ctx)), ) .await?; return Ok(()); @@ -1067,11 +1062,7 @@ where &reason, client, Some(&redacted_target), - Some(crate::l7::rest::DenyResponseContext { - host: Some(&ctx.host), - port: Some(ctx.port), - binary: Some(&ctx.binary_path), - }), + Some(crate::l7::rest::DenyResponseContext::from_l7_context(ctx)), ) .await?; return Ok(()); @@ -1299,11 +1290,7 @@ where &reason, client, Some(&redacted_target), - Some(crate::l7::rest::DenyResponseContext { - host: Some(&ctx.host), - port: Some(ctx.port), - binary: Some(&ctx.binary_path), - }), + Some(crate::l7::rest::DenyResponseContext::from_l7_context(ctx)), ) .await?; return Ok(()); @@ -1535,11 +1522,7 @@ where &reason, client, Some(&redacted_target), - Some(crate::l7::rest::DenyResponseContext { - host: Some(&ctx.host), - port: Some(ctx.port), - binary: Some(&ctx.binary_path), - }), + Some(crate::l7::rest::DenyResponseContext::from_l7_context(ctx)), ) .await?; return Ok(()); @@ -2294,9 +2277,9 @@ network_policies: ancestors: vec![], cmdline_paths: vec![], secret_resolver: None, - activity_tx: None, dynamic_credentials: Some(fixture.dynamic_credentials()), token_grant_resolver: Some(fixture.resolver()), + ..Default::default() }; (config, tunnel_engine, ctx, fixture) @@ -2361,9 +2344,7 @@ network_policies: ancestors: vec![], cmdline_paths: vec![], secret_resolver: None, - activity_tx: None, - dynamic_credentials: None, - token_grant_resolver: None, + ..Default::default() }; (config, tunnel_engine, ctx) @@ -2404,9 +2385,9 @@ network_policies: ancestors: vec![], cmdline_paths: vec![], secret_resolver: None, - activity_tx: None, dynamic_credentials: Some(fixture.dynamic_credentials()), token_grant_resolver: Some(fixture.resolver()), + ..Default::default() }; (generation_guard, ctx, fixture) @@ -2451,9 +2432,7 @@ network_policies: ancestors: vec![], cmdline_paths: vec![], secret_resolver: None, - activity_tx: None, - dynamic_credentials: None, - token_grant_resolver: None, + ..Default::default() }; (config, tunnel_engine, ctx) } @@ -2497,9 +2476,7 @@ network_policies: ancestors: vec![], cmdline_paths: vec![], secret_resolver: None, - activity_tx: None, - dynamic_credentials: None, - token_grant_resolver: None, + ..Default::default() }; (config, tunnel_engine, ctx) } @@ -3012,9 +2989,7 @@ network_policies: ancestors: vec![], cmdline_paths: vec![], secret_resolver: None, - activity_tx: None, - dynamic_credentials: None, - token_grant_resolver: None, + ..Default::default() }; let (mut app, mut relay_client) = tokio::io::duplex(8192); let (mut relay_upstream, mut upstream) = tokio::io::duplex(8192); @@ -3129,9 +3104,7 @@ network_policies: ancestors: vec![], cmdline_paths: vec![], secret_resolver: None, - activity_tx: None, - dynamic_credentials: None, - token_grant_resolver: None, + ..Default::default() }; let req = || crate::l7::provider::L7Request { action: "POST".into(), @@ -3342,9 +3315,7 @@ network_policies: ancestors: vec![], cmdline_paths: vec![], secret_resolver: None, - activity_tx: None, - dynamic_credentials: None, - token_grant_resolver: None, + ..Default::default() }; (config, tunnel_engine, ctx) } @@ -3506,9 +3477,7 @@ network_policies: ancestors: vec![], cmdline_paths: vec![], secret_resolver: None, - activity_tx: None, - dynamic_credentials: None, - token_grant_resolver: None, + ..Default::default() }; let (mut app, mut relay_client) = tokio::io::duplex(8192); let (mut relay_upstream, mut upstream) = tokio::io::duplex(8192); @@ -3607,9 +3576,7 @@ network_policies: ancestors: vec![], cmdline_paths: vec![], secret_resolver: None, - activity_tx: None, - dynamic_credentials: None, - token_grant_resolver: None, + ..Default::default() }; (config, tunnel_engine, ctx) } @@ -3962,9 +3929,7 @@ network_policies: ancestors: Vec::new(), cmdline_paths: Vec::new(), secret_resolver: None, - activity_tx: None, - dynamic_credentials: None, - token_grant_resolver: None, + ..Default::default() }; let input = middleware_request_input( @@ -3996,9 +3961,7 @@ network_policies: ancestors: vec![], cmdline_paths: vec![], secret_resolver: None, - activity_tx: None, - dynamic_credentials: None, - token_grant_resolver: None, + ..Default::default() }; let req = crate::l7::provider::L7Request { action: "POST".into(), @@ -4187,9 +4150,7 @@ network_policies: ancestors: vec![], cmdline_paths: vec![], secret_resolver: None, - activity_tx: None, - dynamic_credentials: None, - token_grant_resolver: None, + ..Default::default() }; let (mut app, mut relay_client) = tokio::io::duplex(8192); @@ -4299,9 +4260,7 @@ network_policies: ancestors: vec![], cmdline_paths: vec![], secret_resolver: None, - activity_tx: None, - dynamic_credentials: None, - token_grant_resolver: None, + ..Default::default() }; let (mut app, mut relay_client) = tokio::io::duplex(8192); @@ -4514,9 +4473,7 @@ network_policies: ancestors: vec![], cmdline_paths: vec![], secret_resolver: None, - activity_tx: None, - dynamic_credentials: None, - token_grant_resolver: None, + ..Default::default() }; let request = L7RequestInfo { action: "WEBSOCKET_TEXT".into(), @@ -4591,9 +4548,7 @@ network_policies: ancestors: vec![], cmdline_paths: vec![], secret_resolver: None, - activity_tx: None, - dynamic_credentials: None, - token_grant_resolver: None, + ..Default::default() }; let mut request = L7RequestInfo { action: "POST".into(), @@ -4714,9 +4669,7 @@ network_policies: ancestors: vec![], cmdline_paths: vec![], secret_resolver: None, - activity_tx: None, - dynamic_credentials: None, - token_grant_resolver: None, + ..Default::default() }; let mut request = L7RequestInfo { action: "POST".into(), @@ -4779,9 +4732,7 @@ network_policies: ancestors: vec![], cmdline_paths: vec![], secret_resolver: None, - activity_tx: None, - dynamic_credentials: None, - token_grant_resolver: None, + ..Default::default() }; let mut request = L7RequestInfo { action: "POST".into(), @@ -4942,9 +4893,7 @@ network_policies: ancestors: vec![], cmdline_paths: vec![], secret_resolver: None, - activity_tx: None, - dynamic_credentials: None, - token_grant_resolver: None, + ..Default::default() }; let (mut app, mut relay_client) = tokio::io::duplex(8192); let (mut relay_upstream, mut upstream) = tokio::io::duplex(8192); @@ -5041,9 +4990,7 @@ network_policies: ancestors: vec![], cmdline_paths: vec![], secret_resolver: None, - activity_tx: None, - dynamic_credentials: None, - token_grant_resolver: None, + ..Default::default() }; let (mut app, mut relay_client) = tokio::io::duplex(8192); @@ -5153,9 +5100,7 @@ network_policies: ancestors: vec![], cmdline_paths: vec![], secret_resolver: resolver.map(Arc::new), - activity_tx: None, - dynamic_credentials: None, - token_grant_resolver: None, + ..Default::default() }; let (mut app, mut relay_client) = tokio::io::duplex(8192); @@ -5278,9 +5223,7 @@ network_policies: ancestors: vec![], cmdline_paths: vec![], secret_resolver: resolver.map(Arc::new), - activity_tx: None, - dynamic_credentials: None, - token_grant_resolver: None, + ..Default::default() }; let (mut app, mut relay_client) = tokio::io::duplex(8192); @@ -5451,9 +5394,7 @@ network_policies: ancestors: vec![], cmdline_paths: vec![], secret_resolver: None, - activity_tx: None, - dynamic_credentials: None, - token_grant_resolver: None, + ..Default::default() }; let (mut app, mut relay_client) = tokio::io::duplex(8192); @@ -5544,9 +5485,7 @@ network_policies: ancestors: vec![], cmdline_paths: vec![], secret_resolver: None, - activity_tx: None, - dynamic_credentials: None, - token_grant_resolver: None, + ..Default::default() }; let (mut app, mut relay_client) = tokio::io::duplex(8192); diff --git a/crates/openshell-supervisor-network/src/l7/rest.rs b/crates/openshell-supervisor-network/src/l7/rest.rs index 0c1346bf2e..fd9d373f81 100644 --- a/crates/openshell-supervisor-network/src/l7/rest.rs +++ b/crates/openshell-supervisor-network/src/l7/rest.rs @@ -130,6 +130,19 @@ pub(crate) struct DenyResponseContext<'a> { pub(crate) host: Option<&'a str>, pub(crate) port: Option, pub(crate) binary: Option<&'a str>, + pub(crate) agent_proposals_enabled: bool, +} + +impl<'a> DenyResponseContext<'a> { + #[must_use] + pub(crate) fn from_l7_context(ctx: &'a crate::l7::relay::L7EvalContext) -> Self { + Self { + host: Some(&ctx.host), + port: Some(ctx.port), + binary: Some(&ctx.binary_path), + agent_proposals_enabled: ctx.agent_proposals.enabled(), + } + } } impl RestProvider { @@ -2360,9 +2373,10 @@ fn deny_response_body( // module; this side picks up the change automatically. body.insert( "next_steps".to_string(), - crate::policy_local::agent_next_steps(), + crate::policy_local::agent_next_steps(context.agent_proposals_enabled), ); - if let Some(guidance) = crate::policy_local::agent_guidance() { + if let Some(guidance) = crate::policy_local::agent_guidance_for(context.agent_proposals_enabled) + { body.insert("agent_guidance".to_string(), serde_json::json!(guidance)); } @@ -3183,6 +3197,7 @@ mod tests { use super::*; use crate::opa::OpaEngine; use flate2::{Compress, Compression, Decompress, FlushCompress, FlushDecompress, Status}; + use openshell_core::proposals::AgentProposals; use openshell_core::secrets::SecretResolver; use std::pin::Pin; use std::sync::Arc; @@ -3350,6 +3365,31 @@ mod tests { .expect("WebSocket frame should arrive") } + async fn policy_local_json_response( + ctx: Arc, + ) -> serde_json::Value { + let (mut client, mut server) = tokio::io::duplex(4096); + let task = tokio::spawn(async move { + crate::policy_local::handle_forward_request( + ctx.as_ref(), + "GET", + "/v1/policy/current", + b"GET http://policy.local/v1/policy/current HTTP/1.1\r\nHost: policy.local\r\n\r\n", + &mut server, + ) + .await + .unwrap(); + }); + + let mut received = Vec::new(); + client.read_to_end(&mut received).await.unwrap(); + task.await.unwrap(); + + let response = String::from_utf8(received).unwrap(); + let (_, body) = response.split_once("\r\n\r\n").unwrap(); + serde_json::from_str(body).unwrap() + } + fn masked_frame_with_rsv(opcode: u8, rsv: u8, payload: &[u8]) -> Vec { let mask_key = [0x37, 0xfa, 0x21, 0x3d]; let mut frame = Vec::new(); @@ -3565,9 +3605,6 @@ mod tests { #[test] fn deny_response_body_is_agent_readable_and_redacted() { - // Agent-readable next_steps is gated on the proposals feature flag. - let _proposals = - openshell_core::proposals::test_helpers::ProposalsFlagGuard::set_blocking(true); let req = L7Request { action: "PUT".to_string(), target: "/repos/NVIDIA/OpenShell/contents/README.md?access_token=secret-token" @@ -3586,6 +3623,7 @@ mod tests { host: Some("api.github.com"), port: Some(443), binary: Some("/usr/bin/gh"), + agent_proposals_enabled: true, }), ); @@ -3632,8 +3670,6 @@ mod tests { #[test] fn deny_response_body_omits_agent_guidance_when_policy_advisor_is_off() { - let _proposals = - openshell_core::proposals::test_helpers::ProposalsFlagGuard::set_blocking(false); let req = L7Request { action: "GET".to_string(), target: "/gists".to_string(), @@ -3651,6 +3687,7 @@ mod tests { host: Some("api.github.com"), port: Some(443), binary: Some("/usr/bin/gh"), + agent_proposals_enabled: false, }), ); @@ -3662,10 +3699,76 @@ mod tests { ); } + #[tokio::test] + async fn shared_agent_proposals_state_gates_policy_local_and_l7_next_steps() { + let agent_proposals = AgentProposals::new(false); + let (_workspace_tx, workspace_rx) = tokio::sync::watch::channel(String::new()); + let policy_local_ctx = Arc::new(crate::policy_local::PolicyLocalContext::new( + Some(openshell_core::proto::SandboxPolicy { + version: 1, + ..Default::default() + }), + None, + None, + agent_proposals.clone(), + workspace_rx, + )); + let l7_ctx = crate::l7::relay::L7EvalContext { + host: "api.github.com".to_string(), + port: 443, + binary_path: "/usr/bin/gh".to_string(), + agent_proposals: agent_proposals.clone(), + ..Default::default() + }; + let req = L7Request { + action: "POST".to_string(), + target: "/user/repos".to_string(), + query_params: HashMap::new(), + raw_header: Vec::new(), + body_length: BodyLength::None, + }; + + let policy_body = policy_local_json_response(policy_local_ctx.clone()).await; + assert_eq!(policy_body["error"], "feature_disabled"); + let deny_body = deny_response_body( + &req, + "github-readonly", + "no matching L7 allow rule", + None, + Some(DenyResponseContext::from_l7_context(&l7_ctx)), + ); + assert_eq!(deny_body["next_steps"], serde_json::json!([])); + assert!(deny_body.get("agent_guidance").is_none()); + + agent_proposals.set_enabled(true); + + let policy_body = policy_local_json_response(policy_local_ctx).await; + assert_eq!(policy_body["format"], "yaml"); + assert!( + policy_body["policy_yaml"] + .as_str() + .unwrap() + .contains("version: 1") + ); + let deny_body = deny_response_body( + &req, + "github-readonly", + "no matching L7 allow rule", + None, + Some(DenyResponseContext::from_l7_context(&l7_ctx)), + ); + assert_eq!(deny_body["next_steps"][0]["action"], "read_skill"); + assert_eq!(deny_body["next_steps"][3]["action"], "submit_proposal"); + assert!( + deny_body["agent_guidance"] + .as_str() + .unwrap() + .contains("http://policy.local/v1/proposals") + ); + } + #[test] fn middleware_deny_response_identifies_config_without_policy_remediation() { - let _proposals = - openshell_core::proposals::test_helpers::ProposalsFlagGuard::set_blocking(true); let req = L7Request { action: "POST".to_string(), target: "/v1/messages?token=secret-token".to_string(), @@ -3687,6 +3790,7 @@ mod tests { host: Some("api.example.com"), port: Some(443), binary: Some("/usr/bin/curl"), + agent_proposals_enabled: true, }), ); @@ -3705,9 +3809,6 @@ mod tests { #[tokio::test] async fn send_deny_response_writes_structured_json_403() { - // Agent-readable next_steps is gated on the proposals feature flag. - let _proposals = - openshell_core::proposals::test_helpers::ProposalsFlagGuard::set(true).await; let (mut client, mut server) = tokio::io::duplex(4096); let send = tokio::spawn(async move { let req = L7Request { @@ -3727,6 +3828,7 @@ mod tests { host: Some("api.github.com"), port: Some(443), binary: Some("/usr/bin/gh"), + agent_proposals_enabled: true, }), ) .await diff --git a/crates/openshell-supervisor-network/src/l7/token_grant_injection.rs b/crates/openshell-supervisor-network/src/l7/token_grant_injection.rs index 07a8c641f1..2ca25e6e81 100644 --- a/crates/openshell-supervisor-network/src/l7/token_grant_injection.rs +++ b/crates/openshell-supervisor-network/src/l7/token_grant_injection.rs @@ -721,9 +721,9 @@ mod tests { ancestors: vec![], cmdline_paths: vec![], secret_resolver: None, - activity_tx: None, dynamic_credentials: Some(fixture.dynamic_credentials()), token_grant_resolver: Some(fixture.resolver()), + ..Default::default() }; let req = L7Request { action: "GET".to_string(), @@ -758,9 +758,9 @@ mod tests { ancestors: vec![], cmdline_paths: vec![], secret_resolver: None, - activity_tx: None, dynamic_credentials: Some(fixture.dynamic_credentials()), token_grant_resolver: Some(fixture.resolver()), + ..Default::default() }; let req = L7Request { action: "GET".to_string(), diff --git a/crates/openshell-supervisor-network/src/l7/websocket.rs b/crates/openshell-supervisor-network/src/l7/websocket.rs index e1f92e6ece..bb59c5227b 100644 --- a/crates/openshell-supervisor-network/src/l7/websocket.rs +++ b/crates/openshell-supervisor-network/src/l7/websocket.rs @@ -1273,9 +1273,7 @@ network_policies: ancestors: vec![], cmdline_paths: vec![], secret_resolver: None, - activity_tx: None, - dynamic_credentials: None, - token_grant_resolver: None, + ..Default::default() }; let (mut client_write, mut relay_read) = tokio::io::duplex(MAX_TEXT_MESSAGE_BYTES + 1024); let (mut relay_write, mut upstream_read) = tokio::io::duplex(MAX_TEXT_MESSAGE_BYTES + 1024); diff --git a/crates/openshell-supervisor-network/src/policy_local.rs b/crates/openshell-supervisor-network/src/policy_local.rs index 53c038dec1..e915c18c9b 100644 --- a/crates/openshell-supervisor-network/src/policy_local.rs +++ b/crates/openshell-supervisor-network/src/policy_local.rs @@ -4,6 +4,7 @@ //! Sandbox-local policy advisor HTTP API. use miette::{IntoDiagnostic, Result}; +use openshell_core::proposals::AgentProposals; use openshell_core::proto::{ L7Allow, L7DenyRule, L7Rule, NetworkBinary, NetworkEndpoint, NetworkPolicyRule, PolicyChunk, SandboxPolicy as ProtoSandboxPolicy, @@ -85,6 +86,7 @@ const MAX_DENIAL_LINE_BYTES: usize = 4096; #[derive(Debug)] pub struct PolicyLocalContext { current_policy: Arc>>, + agent_proposals: AgentProposals, gateway_endpoint: Option, sandbox_name: Option, shorthand_log_dir: PathBuf, @@ -96,12 +98,14 @@ impl PolicyLocalContext { current_policy: Option, gateway_endpoint: Option, sandbox_name: Option, + agent_proposals: AgentProposals, workspace_rx: tokio::sync::watch::Receiver, ) -> Self { Self::with_log_dir( current_policy, gateway_endpoint, sandbox_name, + agent_proposals, PathBuf::from(LOG_DIR), workspace_rx, ) @@ -111,11 +115,13 @@ impl PolicyLocalContext { current_policy: Option, gateway_endpoint: Option, sandbox_name: Option, + agent_proposals: AgentProposals, shorthand_log_dir: PathBuf, workspace_rx: tokio::sync::watch::Receiver, ) -> Self { Self { current_policy: Arc::new(RwLock::new(current_policy)), + agent_proposals, gateway_endpoint, sandbox_name, shorthand_log_dir, @@ -126,6 +132,16 @@ impl PolicyLocalContext { pub async fn set_current_policy(&self, policy: ProtoSandboxPolicy) { *self.current_policy.write().await = Some(policy); } + + #[must_use] + pub fn agent_proposals(&self) -> AgentProposals { + self.agent_proposals.clone() + } + + #[must_use] + pub fn agent_proposals_enabled(&self) -> bool { + self.agent_proposals.enabled() + } } pub async fn handle_forward_request( @@ -154,7 +170,7 @@ async fn route_request( // when the flag is off — including the diagnostic `current_policy` and // `denials` routes. The skill is also not installed in that mode, so a // disabled sandbox has no entry point into this API at all. - if !openshell_core::proposals::agent_proposals_enabled() { + if !ctx.agent_proposals_enabled() { return ( 404, serde_json::json!({ @@ -223,12 +239,12 @@ fn not_found_payload(path: &str) -> (u16, serde_json::Value) { /// the deny body and the actual route table from drifting — adding or /// renaming a route only requires touching the route constants above. /// -/// Returns an empty array when `agent_proposals_enabled()` is false so a +/// Returns an empty array when agent policy proposals are disabled so a /// disabled sandbox doesn't advertise a surface that 404s. The deny body /// caller still emits the field (with `[]`) so the wire shape is stable. #[must_use] -pub fn agent_next_steps() -> serde_json::Value { - if !openshell_core::proposals::agent_proposals_enabled() { +pub fn agent_next_steps(agent_proposals_enabled: bool) -> serde_json::Value { + if !agent_proposals_enabled { return serde_json::json!([]); } let host = POLICY_LOCAL_HOST; @@ -258,8 +274,8 @@ pub fn agent_next_steps() -> serde_json::Value { /// Build the optional natural-language guidance embedded in L7 deny bodies. #[must_use] -pub fn agent_guidance() -> Option<&'static str> { - openshell_core::proposals::agent_proposals_enabled().then_some(AGENT_GUIDANCE) +pub fn agent_guidance_for(agent_proposals_enabled: bool) -> Option<&'static str> { + agent_proposals_enabled.then_some(AGENT_GUIDANCE) } async fn current_policy_response(ctx: &PolicyLocalContext) -> (u16, serde_json::Value) { @@ -1355,6 +1371,7 @@ struct L7DenyRuleJson { #[cfg(test)] mod tests { use super::*; + use openshell_core::proposals::AgentProposals; fn test_workspace_rx() -> tokio::sync::watch::Receiver { tokio::sync::watch::channel(String::new()).1 @@ -1505,6 +1522,7 @@ mod tests { None, None, None, + AgentProposals::new(true), dir.path().to_path_buf(), test_workspace_rx(), ); @@ -1542,6 +1560,7 @@ mod tests { None, None, None, + AgentProposals::new(true), dir.path().to_path_buf(), test_workspace_rx(), ); @@ -1558,6 +1577,7 @@ mod tests { None, None, None, + AgentProposals::new(true), dir.path().to_path_buf(), test_workspace_rx(), ); @@ -1627,6 +1647,7 @@ mod tests { None, None, None, + AgentProposals::new(true), dir.path().to_path_buf(), test_workspace_rx(), ); @@ -1638,12 +1659,9 @@ mod tests { assert!(surfaced.ends_with("...[truncated]")); } - use openshell_core::proposals::test_helpers::ProposalsFlagGuard; - #[test] fn agent_next_steps_returns_empty_when_flag_off() { - let _guard = ProposalsFlagGuard::set_blocking(false); - let steps = agent_next_steps(); + let steps = agent_next_steps(false); let arr = steps.as_array().expect("agent_next_steps is an array"); assert!( arr.is_empty(), @@ -1653,8 +1671,7 @@ mod tests { #[test] fn agent_next_steps_returns_full_array_when_flag_on() { - let _guard = ProposalsFlagGuard::set_blocking(true); - let steps = agent_next_steps(); + let steps = agent_next_steps(true); let arr = steps.as_array().expect("agent_next_steps is an array"); assert_eq!(arr.len(), 4, "expected 4 next_steps when feature is on"); let actions: Vec<&str> = arr @@ -1667,14 +1684,12 @@ mod tests { #[test] fn agent_guidance_is_absent_when_flag_off() { - let _guard = ProposalsFlagGuard::set_blocking(false); - assert!(agent_guidance().is_none()); + assert!(agent_guidance_for(false).is_none()); } #[test] fn agent_guidance_points_to_policy_advisor_when_flag_on() { - let _guard = ProposalsFlagGuard::set_blocking(true); - let guidance = agent_guidance().expect("guidance when proposals are enabled"); + let guidance = agent_guidance_for(true).expect("guidance when proposals are enabled"); assert!(guidance.contains("do not stop")); assert!(guidance.contains("/etc/openshell/skills/policy_advisor.md")); assert!(guidance.contains("http://policy.local/v1/proposals")); @@ -1683,7 +1698,6 @@ mod tests { #[tokio::test] async fn route_request_returns_feature_disabled_when_flag_off() { - let _guard = ProposalsFlagGuard::set(false).await; let ctx = PolicyLocalContext::new( Some(ProtoSandboxPolicy { version: 1, @@ -1691,6 +1705,7 @@ mod tests { }), None, None, + AgentProposals::new(false), test_workspace_rx(), ); @@ -1711,7 +1726,6 @@ mod tests { #[tokio::test] async fn current_policy_route_returns_yaml_envelope() { - let _guard = ProposalsFlagGuard::set(true).await; let ctx = PolicyLocalContext::new( Some(ProtoSandboxPolicy { version: 1, @@ -1719,6 +1733,7 @@ mod tests { }), None, None, + AgentProposals::new(true), test_workspace_rx(), ); @@ -1812,8 +1827,13 @@ mod tests { #[tokio::test] async fn proposal_routes_reject_malformed_paths() { - let _guard = ProposalsFlagGuard::set(true).await; - let ctx = PolicyLocalContext::new(None, None, None, test_workspace_rx()); + let ctx = PolicyLocalContext::new( + None, + None, + None, + AgentProposals::new(true), + test_workspace_rx(), + ); // Empty chunk_id after the prefix is 404, not a wildcard list. let (status, _) = route_request(&ctx, "GET", "/v1/proposals/", &[]).await; @@ -1833,11 +1853,11 @@ mod tests { #[tokio::test] async fn proposal_status_route_returns_503_when_no_gateway() { - let _guard = ProposalsFlagGuard::set(true).await; let ctx = PolicyLocalContext::new( None, None, Some("test-sandbox".to_string()), + AgentProposals::new(true), test_workspace_rx(), ); @@ -1848,11 +1868,11 @@ mod tests { #[tokio::test] async fn proposal_wait_route_returns_503_when_no_gateway() { - let _guard = ProposalsFlagGuard::set(true).await; let ctx = PolicyLocalContext::new( None, None, Some("test-sandbox".to_string()), + AgentProposals::new(true), test_workspace_rx(), ); @@ -1864,11 +1884,11 @@ mod tests { #[tokio::test] async fn proposal_routes_return_feature_disabled_when_flag_off() { - let _guard = ProposalsFlagGuard::set(false).await; let ctx = PolicyLocalContext::new( None, None, Some("test-sandbox".to_string()), + AgentProposals::new(false), test_workspace_rx(), ); @@ -1950,6 +1970,7 @@ mod tests { Some(policy_with_rule(proposed.clone())), None, None, + AgentProposals::new(false), test_workspace_rx(), ); let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(2); @@ -1977,7 +1998,13 @@ mod tests { version: 1, ..Default::default() }; - let ctx = PolicyLocalContext::new(Some(initial), None, None, test_workspace_rx()); + let ctx = PolicyLocalContext::new( + Some(initial), + None, + None, + AgentProposals::new(false), + test_workspace_rx(), + ); // Concurrently, an unrelated rule lands. We must not return. let unrelated_load = { @@ -2028,6 +2055,7 @@ mod tests { }), None, None, + AgentProposals::new(false), test_workspace_rx(), ); @@ -2066,6 +2094,7 @@ mod tests { }), None, None, + AgentProposals::new(false), test_workspace_rx(), ); let deadline = tokio::time::Instant::now() + std::time::Duration::from_millis(300); diff --git a/crates/openshell-supervisor-network/src/proxy.rs b/crates/openshell-supervisor-network/src/proxy.rs index c0cbe3005d..d29296a8f3 100644 --- a/crates/openshell-supervisor-network/src/proxy.rs +++ b/crates/openshell-supervisor-network/src/proxy.rs @@ -239,6 +239,9 @@ impl ProxyHandle { host-gateway aliases exempt from SSRF always-blocked check" ); } + let agent_proposals = policy_local_ctx + .as_ref() + .map_or_else(Default::default, |ctx| ctx.agent_proposals()); let join = tokio::spawn(async move { // Wait for the OPA engine's symlink resolution reload to complete @@ -274,6 +277,7 @@ impl ProxyHandle { let tls = tls_state.clone(); let inf = inference_ctx.clone(); let policy_local = policy_local_ctx.clone(); + let proposals = agent_proposals.clone(); let gw = trusted_host_gateway.clone(); let resolver = provider_credentials .as_ref() @@ -295,6 +299,7 @@ impl ProxyHandle { tls, inf, policy_local, + proposals, gw, resolver, dynamic_credentials, @@ -626,6 +631,7 @@ async fn handle_tcp_connection( tls_state: Option>, inference_ctx: Option>, policy_local_ctx: Option>, + agent_proposals: openshell_core::proposals::AgentProposals, trusted_host_gateway: Arc>, secret_resolver: Option>, dynamic_credentials: Option< @@ -694,6 +700,7 @@ async fn handle_tcp_connection( identity_cache, entrypoint_pid, policy_local_ctx, + agent_proposals, trusted_host_gateway, secret_resolver, dynamic_credentials, @@ -1242,6 +1249,7 @@ async fn handle_tcp_connection( token_grant_resolver: dynamic_credentials .as_ref() .map(|_| crate::l7::token_grant_injection::default_resolver()), + agent_proposals, }; if effective_tls_skip { @@ -3542,6 +3550,7 @@ async fn handle_forward_proxy( identity_cache: Arc, entrypoint_pid: Arc, policy_local_ctx: Option>, + agent_proposals: openshell_core::proposals::AgentProposals, trusted_host_gateway: Arc>, secret_resolver: Option>, dynamic_credentials: Option< @@ -3821,6 +3830,7 @@ async fn handle_forward_proxy( token_grant_resolver: dynamic_credentials .as_ref() .map(|_| crate::l7::token_grant_injection::default_resolver()), + agent_proposals, }; let mut l7_activity_pending = false; @@ -5035,6 +5045,7 @@ fn is_benign_relay_error(err: &miette::Report) -> bool { )] mod tests { use super::*; + use openshell_core::proposals::AgentProposals; use std::future::Future; use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; use std::sync::Arc; @@ -5071,6 +5082,7 @@ network_policies: {} None, None, None, + AgentProposals::default(), Arc::new(None), None, None, @@ -5579,9 +5591,7 @@ network_policies: ancestors: vec![], cmdline_paths: vec![], secret_resolver: None, - activity_tx: None, - dynamic_credentials: None, - token_grant_resolver: None, + ..Default::default() }; let runner = openshell_supervisor_middleware::ChainRunner::new( openshell_supervisor_middleware_builtins::services() @@ -5808,9 +5818,9 @@ network_policies: ancestors: vec![], cmdline_paths: vec![], secret_resolver: None, - activity_tx: None, dynamic_credentials: Some(fixture.dynamic_credentials()), token_grant_resolver: Some(fixture.resolver()), + ..Default::default() }; (ctx, fixture) @@ -5866,9 +5876,7 @@ network_policies: ancestors: vec![], cmdline_paths: vec![], secret_resolver: None, - activity_tx: None, - dynamic_credentials: None, - token_grant_resolver: None, + ..Default::default() }; (config, tunnel_engine, ctx) } @@ -6041,9 +6049,7 @@ network_policies: ancestors: vec![], cmdline_paths: vec![], secret_resolver: resolver, - activity_tx: None, - dynamic_credentials: None, - token_grant_resolver: None, + ..Default::default() }; let query_params = std::collections::HashMap::new(); @@ -6084,9 +6090,7 @@ network_policies: ancestors: vec![], cmdline_paths: vec![], secret_resolver: None, - activity_tx: None, - dynamic_credentials: None, - token_grant_resolver: None, + ..Default::default() }; let query_params = std::collections::HashMap::new(); let config = websocket_l7_config(crate::l7::L7Protocol::Rest, false); @@ -8492,9 +8496,7 @@ network_policies: ancestors: vec![], cmdline_paths: vec![], secret_resolver: None, - activity_tx: None, - dynamic_credentials: None, - token_grant_resolver: None, + ..Default::default() }; let runner = openshell_supervisor_middleware::ChainRunner::new( openshell_supervisor_middleware_builtins::services() @@ -9396,14 +9398,15 @@ network_policies: engine, cache, entrypoint_pid, - None, // tls_state — ephemeral CA unavailable - None, // inference_ctx - None, // policy_local_ctx - Arc::new(None), // trusted_host_gateway - None, // secret_resolver - None, // dynamic_credentials - Some(denial_tx), // denial_tx — positive allow/deny signal - None, // activity_tx + None, // tls_state — ephemeral CA unavailable + None, // inference_ctx + None, // policy_local_ctx + AgentProposals::default(), // agent_proposals + Arc::new(None), // trusted_host_gateway + None, // secret_resolver + None, // dynamic_credentials + Some(denial_tx), // denial_tx — positive allow/deny signal + None, // activity_tx )), ) .await diff --git a/crates/openshell-supervisor-network/src/run.rs b/crates/openshell-supervisor-network/src/run.rs index 9284a55ca1..f8f38a440b 100644 --- a/crates/openshell-supervisor-network/src/run.rs +++ b/crates/openshell-supervisor-network/src/run.rs @@ -26,6 +26,7 @@ use openshell_ocsf::{ use openshell_core::activity::ActivitySender; use openshell_core::denial::DenialEvent; +use openshell_core::proposals::AgentProposals; use tokio::sync::mpsc::UnboundedSender; use crate::identity::BinaryIdentityCache; @@ -86,6 +87,7 @@ pub async fn run_networking( #[allow(unused_variables)] inference_routes: Option<&str>, denial_tx: Option>, activity_tx: Option, + agent_proposals: AgentProposals, workspace_rx: tokio::sync::watch::Receiver, ) -> Result { // Build the policy-local route context. The orchestrator's policy poll @@ -97,6 +99,7 @@ pub async fn run_networking( sandbox_name .map(str::to_string) .or_else(|| sandbox_id.map(str::to_string)), + agent_proposals, workspace_rx, )); diff --git a/crates/openshell-supervisor-process/src/run.rs b/crates/openshell-supervisor-process/src/run.rs index 5a06d97a8f..3cb29d1e6b 100644 --- a/crates/openshell-supervisor-process/src/run.rs +++ b/crates/openshell-supervisor-process/src/run.rs @@ -24,6 +24,7 @@ use openshell_ocsf::{ #[cfg(target_os = "linux")] use crate::netns::NetworkNamespace; use openshell_core::policy::{NetworkMode, SandboxPolicy}; +use openshell_core::proposals::AgentProposals; use openshell_core::provider_credentials::ProviderCredentialState; #[cfg(target_os = "linux")] @@ -64,6 +65,7 @@ pub async fn run_process( provider_credentials: ProviderCredentialState, provider_env: std::collections::HashMap, ca_file_paths: Option<(std::path::PathBuf, std::path::PathBuf)>, + agent_proposals: AgentProposals, #[cfg(target_os = "linux")] netns: Option<&NetworkNamespace>, #[cfg(target_os = "linux")] bypass_denial_tx: Option< tokio::sync::mpsc::UnboundedSender, @@ -99,7 +101,7 @@ pub async fn run_process( // proposals flag is on at startup, rather than waiting for the policy // poll loop's first tick. In offline/file-mode there is no gateway, so // the flag stays at its default (false) and no skill is installed. - install_initial_agent_skill(sandbox_id, openshell_endpoint).await; + install_initial_agent_skill(sandbox_id, openshell_endpoint, &agent_proposals).await; // Install the supervisor seccomp prelude before spawning any workload-side // tasks. By this point the orchestrator has finished privileged startup @@ -416,17 +418,12 @@ fn ssh_proxy_url_for_policy( /// /// Best-effort: any failure (no gateway, RPC error, install failure) is /// logged but does not fail sandbox startup. -async fn install_initial_agent_skill(sandbox_id: Option<&str>, openshell_endpoint: Option<&str>) { +async fn install_initial_agent_skill( + sandbox_id: Option<&str>, + openshell_endpoint: Option<&str>, + agent_proposals: &AgentProposals, +) { use openshell_core::proto::setting_value; - use std::sync::atomic::Ordering; - - let Some(flag) = openshell_core::proposals::AGENT_PROPOSALS_ENABLED.get() else { - // The orchestrator is responsible for setting the OnceLock before - // calling run_process. If it isn't set, behave as if the flag is - // off and skip the install. - tracing::debug!("AGENT_PROPOSALS_ENABLED not initialized; skipping skill install"); - return; - }; if let (Some(id), Some(endpoint)) = (sandbox_id, openshell_endpoint) && let Ok(client) = @@ -443,10 +440,10 @@ async fn install_initial_agent_skill(sandbox_id: Option<&str>, openshell_endpoin _ => None, }) .unwrap_or(false); - flag.store(initial, Ordering::Relaxed); + agent_proposals.set_enabled(initial); } - if openshell_core::proposals::agent_proposals_enabled() { + if agent_proposals.enabled() { match crate::skills::install_static_skills() { Ok(installed) => info!( path = %installed.policy_advisor.display(), From f7cd910829c0dfcc0ef19dd8b47e53d95a47702c Mon Sep 17 00:00:00 2001 From: Piotr Mlocek Date: Fri, 24 Jul 2026 08:47:44 -0700 Subject: [PATCH 2/7] fix: eliminate parallel Rust test flakes (#2434) * fix: eliminate parallel Rust test flakes Signed-off-by: Piotr Mlocek * refactor(supervisor-network): name workload proxy TCP connection Signed-off-by: Evan Lezar * refactor(supervisor-network): name procfs address family Signed-off-by: Piotr Mlocek --------- Signed-off-by: Piotr Mlocek Signed-off-by: Evan Lezar Co-authored-by: Evan Lezar --- architecture/sandbox.md | 5 +- crates/openshell-cli/src/ssh.rs | 34 ++- .../src/runtime.rs | 7 +- crates/openshell-server/src/multiplex.rs | 25 +- .../src/procfs.rs | 229 ++++++++++++++---- .../openshell-supervisor-network/src/proxy.rs | 114 ++++----- 6 files changed, 288 insertions(+), 126 deletions(-) diff --git a/architecture/sandbox.md b/architecture/sandbox.md index d2cb44d7b8..bfb1c14741 100644 --- a/architecture/sandbox.md +++ b/architecture/sandbox.md @@ -53,7 +53,10 @@ paths, such as proxy support files or GPU device paths when a GPU is present. All ordinary agent egress is routed through the sandbox proxy. The proxy identifies the calling binary, checks trust-on-first-use binary identity, rejects -unsafe internal destinations, and evaluates the active policy. +unsafe internal destinations, and evaluates the active policy. On Linux, it +maps an accepted proxy connection back to the workload socket by matching the +complete local-to-remote TCP tuple before resolving every process that owns the +socket inode. For inspected HTTP traffic, the proxy can enforce REST method/path rules, WebSocket upgrade and text-message rules, GraphQL operation rules, and MCP method, tool, and supported params rules or generic JSON-RPC method rules diff --git a/crates/openshell-cli/src/ssh.rs b/crates/openshell-cli/src/ssh.rs index 50bc2bbee9..d277804bf1 100644 --- a/crates/openshell-cli/src/ssh.rs +++ b/crates/openshell-cli/src/ssh.rs @@ -18,6 +18,7 @@ use openshell_core::proto::{ }; use owo_colors::OwoColorize; use std::fs; +use std::future::Future; use std::io::{IsTerminal, Write}; #[cfg(unix)] use std::os::unix::process::CommandExt; @@ -447,9 +448,24 @@ async fn wait_for_forward_start(child: &mut Child, spec: &ForwardSpec) -> Result /// last probe error is folded into the timeout diagnostic, so a failure reports /// why the listener never opened, not just that it timed out. async fn wait_for_forward_listener(spec: &ForwardSpec, wait_for: Duration) -> Result<()> { + wait_for_forward_listener_with_probe(spec, wait_for, |spec| async move { + probe_forward_listener(&spec).await + }) + .await +} + +async fn wait_for_forward_listener_with_probe( + spec: &ForwardSpec, + wait_for: Duration, + mut probe: F, +) -> Result<()> +where + F: FnMut(ForwardSpec) -> Fut, + Fut: Future>, +{ let deadline = tokio::time::Instant::now() + wait_for; loop { - let probe_error = match probe_forward_listener(spec).await { + let probe_error = match probe(spec.clone()).await { Ok(()) => return Ok(()), Err(err) => err, }; @@ -1816,17 +1832,17 @@ mod tests { } #[tokio::test] - async fn wait_for_forward_listener_rejects_missing_listener() { - let listener = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap(); - let port = listener.local_addr().unwrap().port(); - drop(listener); - let spec = ForwardSpec::new(port); + async fn wait_for_forward_listener_reports_failed_probe() { + let spec = ForwardSpec::new(12345); - let err = wait_for_forward_listener(&spec, Duration::from_millis(20)) - .await - .unwrap_err(); + let err = wait_for_forward_listener_with_probe(&spec, Duration::ZERO, |_| { + std::future::ready(Err("connection refused".to_string())) + }) + .await + .unwrap_err(); let text = format!("{err:?}"); assert!(text.contains("local forward listener did not open")); + assert!(text.contains("connection refused")); } #[test] diff --git a/crates/openshell-gateway-interceptors/src/runtime.rs b/crates/openshell-gateway-interceptors/src/runtime.rs index 04c9aba603..d510956aed 100644 --- a/crates/openshell-gateway-interceptors/src/runtime.rs +++ b/crates/openshell-gateway-interceptors/src/runtime.rs @@ -911,7 +911,6 @@ mod tests { .with_ansi(false) .without_time(); let subscriber = tracing_subscriber::registry().with(fmt_layer); - let dispatch = tracing::Dispatch::new(subscriber); let plan = BindingPlan { interceptor_name: "test".to_string(), binding_id: "binding".to_string(), @@ -940,7 +939,11 @@ mod tests { ..InterceptorResult::default() }; - tracing::dispatcher::with_default(&dispatch, || { + tracing::subscriber::with_default(subscriber, || { + // Other parallel tests may register this callsite while no subscriber + // is active. Refresh the process-wide cache after installing this + // thread-local subscriber so the event cannot remain disabled. + tracing::callsite::rebuild_interest_cache(); emit_evaluation_log(&plan, &result, "allow", 2); }); diff --git a/crates/openshell-server/src/multiplex.rs b/crates/openshell-server/src/multiplex.rs index 83e27d27cb..a58f66c916 100644 --- a/crates/openshell-server/src/multiplex.rs +++ b/crates/openshell-server/src/multiplex.rs @@ -1724,16 +1724,21 @@ mod tests { .with_span_events(FmtSpan::CLOSE); let subscriber = tracing_subscriber::registry().with(fmt_layer); - let _guard = tracing::subscriber::set_default(subscriber); - - let req = Request::builder() - .uri("/test-path") - .header("x-request-id", "trace-test-id-12345") - .body(Empty::::new()) - .unwrap(); - let span = make_request_span(&req); - drop(span.enter()); - drop(span); + tracing::subscriber::with_default(subscriber, || { + // Other parallel tests may register this callsite while no subscriber + // is active. Refresh the process-wide cache after installing this + // thread-local subscriber so the span cannot remain disabled. + tracing::callsite::rebuild_interest_cache(); + + let req = Request::builder() + .uri("/test-path") + .header("x-request-id", "trace-test-id-12345") + .body(Empty::::new()) + .unwrap(); + let span = make_request_span(&req); + drop(span.enter()); + drop(span); + }); let output = String::from_utf8(log_buf.lock().unwrap().clone()).unwrap(); assert!( diff --git a/crates/openshell-supervisor-network/src/procfs.rs b/crates/openshell-supervisor-network/src/procfs.rs index 3ac8dbe141..8bc2fbb110 100644 --- a/crates/openshell-supervisor-network/src/procfs.rs +++ b/crates/openshell-supervisor-network/src/procfs.rs @@ -9,6 +9,9 @@ use miette::Result; #[cfg(target_os = "linux")] use std::collections::HashSet; +use std::net::SocketAddr; +#[cfg(target_os = "linux")] +use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; use std::path::Path; #[cfg(target_os = "linux")] use std::path::PathBuf; @@ -40,6 +43,46 @@ pub struct TcpPeerSocketOwners { pub owners: Vec, } +/// TCP endpoints for a workload connection accepted by the sandbox proxy. +/// +/// `/proc//net/tcp{,6}` reports the socket from the workload side, so its +/// local endpoint should match `workload` and its remote endpoint should match +/// `proxy`. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct WorkloadProxyTcpConnection { + pub workload: SocketAddr, + pub proxy: SocketAddr, +} + +impl WorkloadProxyTcpConnection { + pub fn new(workload: SocketAddr, proxy: SocketAddr) -> Self { + Self { workload, proxy } + } +} + +impl std::fmt::Display for WorkloadProxyTcpConnection { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{} -> {}", self.workload, self.proxy) + } +} + +#[cfg(target_os = "linux")] +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum ProcTcpAddressFamily { + Ipv4, + Ipv6, +} + +#[cfg(target_os = "linux")] +impl ProcTcpAddressFamily { + fn table_name(self) -> &'static str { + match self { + Self::Ipv4 => "tcp", + Self::Ipv6 => "tcp6", + } + } +} + #[cfg(target_os = "linux")] #[derive(Clone, Debug, Eq, PartialEq)] struct DescendantPid { @@ -116,11 +159,14 @@ pub fn binary_path(pid: i32) -> Result { /// Resolve the binary path of the TCP peer inside a sandbox network namespace. /// /// Uses `/proc//net/tcp` to find the socket inode for the given -/// ephemeral port, then scans the entrypoint process tree to find which PID owns -/// that socket, and finally reads `/proc//exe` to get the binary path. +/// connection tuple, then scans the entrypoint process tree to find which PID +/// owns that socket, and finally reads `/proc//exe` to get the binary path. #[cfg(target_os = "linux")] -pub fn resolve_tcp_peer_binary(entrypoint_pid: u32, peer_port: u16) -> Result { - let owner = resolve_single_tcp_peer_owner(entrypoint_pid, peer_port)?; +pub fn resolve_tcp_peer_binary( + entrypoint_pid: u32, + connection: WorkloadProxyTcpConnection, +) -> Result { + let owner = resolve_single_tcp_peer_owner(entrypoint_pid, connection)?; binary_path(owner.pid.cast_signed()) } @@ -132,17 +178,20 @@ pub fn resolve_tcp_peer_binary(entrypoint_pid: u32, peer_port: u16) -> Result Result { - let inode = parse_proc_net_tcp(entrypoint_pid, peer_port)?; + let inode = parse_proc_net_tcp(entrypoint_pid, connection)?; let owners = find_socket_inode_owners(inode, entrypoint_pid)?; Ok(TcpPeerSocketOwners { inode, owners }) } /// Resolve exactly one owner for the TCP peer, failing closed on ambiguity. #[cfg(target_os = "linux")] -fn resolve_single_tcp_peer_owner(entrypoint_pid: u32, peer_port: u16) -> Result { - let socket_owners = resolve_tcp_peer_socket_owners(entrypoint_pid, peer_port)?; +fn resolve_single_tcp_peer_owner( + entrypoint_pid: u32, + connection: WorkloadProxyTcpConnection, +) -> Result { + let socket_owners = resolve_tcp_peer_socket_owners(entrypoint_pid, connection)?; match socket_owners.owners.as_slice() { [owner] => Ok(owner.clone()), owners => { @@ -164,8 +213,11 @@ fn resolve_single_tcp_peer_owner(entrypoint_pid: u32, peer_port: u16) -> Result< /// /// Needed for the ancestor walk: we must know the PID to walk `/proc//status` `PPid` chain. #[cfg(target_os = "linux")] -pub fn resolve_tcp_peer_identity(entrypoint_pid: u32, peer_port: u16) -> Result<(PathBuf, u32)> { - let owner = resolve_single_tcp_peer_owner(entrypoint_pid, peer_port)?; +pub fn resolve_tcp_peer_identity( + entrypoint_pid: u32, + connection: WorkloadProxyTcpConnection, +) -> Result<(PathBuf, u32)> { + let owner = resolve_single_tcp_peer_owner(entrypoint_pid, connection)?; let path = binary_path(owner.pid.cast_signed())?; Ok((path, owner.pid)) } @@ -274,7 +326,7 @@ pub fn collect_cmdline_paths(pid: u32, stop_pid: u32, exclude: &[PathBuf]) -> Ve } /// Parse `/proc//net/tcp` (and `/proc//net/tcp6`) to find the socket -/// inode for a given local port. +/// inode for a complete local-to-remote TCP tuple. /// /// Checks both IPv4 and IPv6 tables because some clients (notably gRPC C-core) /// use `AF_INET6` sockets with IPv4-mapped addresses even for IPv4 connections. @@ -288,52 +340,96 @@ pub fn collect_cmdline_paths(pid: u32, stop_pid: u32, exclude: &[PathBuf]) -> Ve /// - State `01` = ESTABLISHED /// - Inode is field index 9 (0-indexed) #[cfg(target_os = "linux")] -fn parse_proc_net_tcp(pid: u32, peer_port: u16) -> Result { +fn parse_proc_net_tcp(pid: u32, connection: WorkloadProxyTcpConnection) -> Result { // Check IPv4 first (most common), then IPv6. - for suffix in &["tcp", "tcp6"] { - let path = format!("/proc/{pid}/net/{suffix}"); + for address_family in [ProcTcpAddressFamily::Ipv4, ProcTcpAddressFamily::Ipv6] { + let path = format!("/proc/{pid}/net/{}", address_family.table_name()); let Ok(content) = std::fs::read_to_string(&path) else { continue; }; - for line in content.lines().skip(1) { - let fields: Vec<&str> = line.split_whitespace().collect(); - if fields.len() < 10 { - continue; - } + if let Some(inode) = find_proc_net_tcp_inode(&content, address_family, connection)? { + return Ok(inode); + } + } - // Parse local_address to extract port. - // IPv4 format: AABBCCDD:PORT - // IPv6 format: 00000000000000000000000000000000:PORT - let local_addr = fields[1]; - let local_port = match local_addr.rsplit_once(':') { - Some((_, port_hex)) => u16::from_str_radix(port_hex, 16).unwrap_or(0), - None => continue, - }; - - // Check state is ESTABLISHED (01) - let state = fields[3]; - if state != "01" { - continue; - } + Err(miette::miette!( + "No ESTABLISHED TCP connection found for {connection} in /proc/{pid}/net/tcp{{,6}}" + )) +} - if local_port == peer_port { - let inode: u64 = fields[9] - .parse() - .map_err(|_| miette::miette!("Failed to parse inode from {}", fields[9]))?; - if inode == 0 { - continue; - } - return Ok(inode); +#[cfg(target_os = "linux")] +fn find_proc_net_tcp_inode( + content: &str, + address_family: ProcTcpAddressFamily, + connection: WorkloadProxyTcpConnection, +) -> Result> { + for line in content.lines().skip(1) { + let fields: Vec<&str> = line.split_whitespace().collect(); + if fields.len() < 10 || fields[3] != "01" { + continue; + } + + let Some(local_addr) = parse_proc_socket_addr(fields[1], address_family) else { + continue; + }; + let Some(remote_addr) = parse_proc_socket_addr(fields[2], address_family) else { + continue; + }; + + if socket_addrs_match(local_addr, connection.workload) + && socket_addrs_match(remote_addr, connection.proxy) + { + let inode: u64 = fields[9] + .parse() + .map_err(|_| miette::miette!("Failed to parse inode from {}", fields[9]))?; + if inode != 0 { + return Ok(Some(inode)); } } } - Err(miette::miette!( - "No ESTABLISHED TCP connection found for port {} in /proc/{}/net/tcp{{,6}}", - peer_port, - pid - )) + Ok(None) +} + +#[cfg(target_os = "linux")] +fn parse_proc_socket_addr(value: &str, address_family: ProcTcpAddressFamily) -> Option { + let (address, port) = value.rsplit_once(':')?; + let port = u16::from_str_radix(port, 16).ok()?; + + let ip = match address_family { + ProcTcpAddressFamily::Ipv4 => { + let address = u32::from_str_radix(address, 16).ok()?; + IpAddr::V4(Ipv4Addr::from(address.to_le_bytes())) + } + ProcTcpAddressFamily::Ipv6 => { + if address.len() != 32 { + return None; + } + let mut bytes = [0u8; 16]; + for (index, chunk) in address.as_bytes().chunks_exact(8).enumerate() { + let chunk = std::str::from_utf8(chunk).ok()?; + let word = u32::from_str_radix(chunk, 16).ok()?; + bytes[index * 4..index * 4 + 4].copy_from_slice(&word.to_le_bytes()); + } + IpAddr::V6(Ipv6Addr::from(bytes)) + } + }; + + Some(SocketAddr::new(ip, port)) +} + +#[cfg(target_os = "linux")] +fn socket_addrs_match(left: SocketAddr, right: SocketAddr) -> bool { + left.port() == right.port() && normalize_ip(left.ip()) == normalize_ip(right.ip()) +} + +#[cfg(target_os = "linux")] +fn normalize_ip(ip: IpAddr) -> IpAddr { + match ip { + IpAddr::V6(ipv6) => ipv6.to_ipv4_mapped().map_or(IpAddr::V6(ipv6), IpAddr::V4), + ipv4 @ IpAddr::V4(_) => ipv4, + } } /// Scan `/proc` to find every PID that owns a given socket inode. @@ -756,6 +852,38 @@ mod tests { assert_eq!(pids.len(), unique.len()); } + #[cfg(target_os = "linux")] + #[test] + fn parse_proc_socket_addr_decodes_ipv4_and_mapped_ipv6() { + let ipv4 = parse_proc_socket_addr("0100007F:C350", ProcTcpAddressFamily::Ipv4).unwrap(); + let mapped_ipv6 = parse_proc_socket_addr( + "0000000000000000FFFF00000100007F:C350", + ProcTcpAddressFamily::Ipv6, + ) + .unwrap(); + + assert_eq!(ipv4, "127.0.0.1:50000".parse().unwrap()); + assert!(socket_addrs_match(ipv4, mapped_ipv6)); + } + + #[cfg(target_os = "linux")] + #[test] + fn find_proc_net_tcp_inode_matches_complete_tuple() { + let content = "\ + sl local_address rem_address st tx_queue:rx_queue tr:tm->when retrnsmt uid timeout inode\n\ + 0: 0100007F:C350 0100007F:1F91 01 00000000:00000000 00:00000000 00000000 1000 0 11111\n\ + 1: 0100007F:C350 0100007F:1F90 01 00000000:00000000 00:00000000 00000000 1000 0 22222\n"; + let connection = WorkloadProxyTcpConnection::new( + "127.0.0.1:50000".parse().unwrap(), + "127.0.0.1:8080".parse().unwrap(), + ); + + let inode = + find_proc_net_tcp_inode(content, ProcTcpAddressFamily::Ipv4, connection).unwrap(); + + assert_eq!(inode, Some(22222)); + } + #[cfg(target_os = "linux")] #[test] fn resolve_tcp_peer_socket_owners_returns_all_forked_socket_holders() { @@ -774,9 +902,10 @@ mod tests { } let listener = TcpListener::bind("127.0.0.1:0").expect("bind listener"); - let listener_port = listener.local_addr().unwrap().port(); - let stream = TcpStream::connect(("127.0.0.1", listener_port)).expect("connect"); - let peer_port = stream.local_addr().unwrap().port(); + let proxy_addr = listener.local_addr().unwrap(); + let stream = TcpStream::connect(proxy_addr).expect("connect"); + let workload_addr = stream.local_addr().unwrap(); + let connection = WorkloadProxyTcpConnection::new(workload_addr, proxy_addr); let (_accepted, _) = listener.accept().expect("accept"); // libc/syscall FFI requires unsafe @@ -797,7 +926,7 @@ mod tests { let entrypoint_pid = std::process::id(); let deadline = Instant::now() + Duration::from_secs(5); let owners = loop { - let owners = resolve_tcp_peer_socket_owners(entrypoint_pid, peer_port) + let owners = resolve_tcp_peer_socket_owners(entrypoint_pid, connection) .expect("resolve socket owners"); let owner_pids = owners .owners diff --git a/crates/openshell-supervisor-network/src/proxy.rs b/crates/openshell-supervisor-network/src/proxy.rs index d29296a8f3..7a842af977 100644 --- a/crates/openshell-supervisor-network/src/proxy.rs +++ b/crates/openshell-supervisor-network/src/proxy.rs @@ -740,8 +740,9 @@ async fn handle_tcp_connection( return Ok(()); } - let peer_addr = client.peer_addr().into_diagnostic()?; - let _local_addr = client.local_addr().into_diagnostic()?; + let workload_addr = client.peer_addr().into_diagnostic()?; + let proxy_addr = client.local_addr().into_diagnostic()?; + let connection = crate::procfs::WorkloadProxyTcpConnection::new(workload_addr, proxy_addr); // Evaluate OPA policy with process-identity binding. // Wrapped in spawn_blocking because identity resolution does heavy sync I/O: @@ -752,7 +753,7 @@ async fn handle_tcp_connection( let host_clone = host_lc.clone(); let decision = tokio::task::spawn_blocking(move || { evaluate_opa_tcp( - peer_addr, + connection, &opa_clone, &cache_clone, &pid_clone, @@ -810,7 +811,7 @@ async fn handle_tcp_connection( .severity(SeverityId::Medium) .status(StatusId::Failure) .dst_endpoint(Endpoint::from_domain(&host_lc, port)) - .src_endpoint_addr(peer_addr.ip(), peer_addr.port()) + .src_endpoint_addr(workload_addr.ip(), workload_addr.port()) .actor_process( Process::from_bypass(&binary_str, &pid_str, &ancestors_str) .with_cmd_line(&cmdline_str), @@ -893,7 +894,7 @@ async fn handle_tcp_connection( .severity(SeverityId::Medium) .status(StatusId::Failure) .dst_endpoint(Endpoint::from_domain(&host_lc, port)) - .src_endpoint_addr(peer_addr.ip(), peer_addr.port()) + .src_endpoint_addr(workload_addr.ip(), workload_addr.port()) .actor_process( Process::from_bypass(&binary_str, &pid_str, &ancestors_str) .with_cmd_line(&cmdline_str), @@ -947,7 +948,7 @@ async fn handle_tcp_connection( .severity(SeverityId::Medium) .status(StatusId::Failure) .dst_endpoint(Endpoint::from_domain(&host_lc, port)) - .src_endpoint_addr(peer_addr.ip(), peer_addr.port()) + .src_endpoint_addr(workload_addr.ip(), workload_addr.port()) .actor_process( Process::from_bypass(&binary_str, &pid_str, &ancestors_str) .with_cmd_line(&cmdline_str), @@ -995,7 +996,7 @@ async fn handle_tcp_connection( .severity(SeverityId::Medium) .status(StatusId::Failure) .dst_endpoint(Endpoint::from_domain(&host_lc, port)) - .src_endpoint_addr(peer_addr.ip(), peer_addr.port()) + .src_endpoint_addr(workload_addr.ip(), workload_addr.port()) .actor_process( Process::from_bypass(&binary_str, &pid_str, &ancestors_str) .with_cmd_line(&cmdline_str), @@ -1047,7 +1048,7 @@ async fn handle_tcp_connection( .severity(SeverityId::Medium) .status(StatusId::Failure) .dst_endpoint(Endpoint::from_domain(&host_lc, port)) - .src_endpoint_addr(peer_addr.ip(), peer_addr.port()) + .src_endpoint_addr(workload_addr.ip(), workload_addr.port()) .actor_process( Process::from_bypass(&binary_str, &pid_str, &ancestors_str) .with_cmd_line(&cmdline_str), @@ -1097,7 +1098,7 @@ async fn handle_tcp_connection( .severity(SeverityId::Medium) .status(StatusId::Failure) .dst_endpoint(Endpoint::from_domain(&host_lc, port)) - .src_endpoint_addr(peer_addr.ip(), peer_addr.port()) + .src_endpoint_addr(workload_addr.ip(), workload_addr.port()) .actor_process( Process::from_bypass(&binary_str, &pid_str, &ancestors_str) .with_cmd_line(&cmdline_str), @@ -1152,7 +1153,7 @@ async fn handle_tcp_connection( .severity(SeverityId::High) .status(StatusId::Failure) .dst_endpoint(Endpoint::from_domain(&host_lc, port)) - .src_endpoint_addr(peer_addr.ip(), peer_addr.port()) + .src_endpoint_addr(workload_addr.ip(), workload_addr.port()) .actor_process( Process::from_bypass(&binary_str, &pid_str, &ancestors_str) .with_cmd_line(&cmdline_str), @@ -1208,7 +1209,7 @@ async fn handle_tcp_connection( .severity(SeverityId::Informational) .status(StatusId::Success) .dst_endpoint(Endpoint::from_domain(&host_lc, port)) - .src_endpoint_addr(peer_addr.ip(), peer_addr.port()) + .src_endpoint_addr(workload_addr.ip(), workload_addr.port()) .actor_process( Process::from_bypass(&binary_str, &pid_str, &ancestors_str) .with_cmd_line(&cmdline_str), @@ -1402,7 +1403,7 @@ async fn handle_tcp_connection( .severity(SeverityId::High) .status(StatusId::Failure) .dst_endpoint(Endpoint::from_domain(&host_lc, port)) - .src_endpoint_addr(peer_addr.ip(), peer_addr.port()) + .src_endpoint_addr(workload_addr.ip(), workload_addr.port()) .actor_process( Process::from_bypass(&binary_str, &pid_str, &ancestors_str) .with_cmd_line(&cmdline_str), @@ -1525,7 +1526,7 @@ async fn handle_tcp_connection( .severity(SeverityId::Medium) .status(StatusId::Failure) .dst_endpoint(Endpoint::from_domain(&host_lc, port)) - .src_endpoint_addr(peer_addr.ip(), peer_addr.port()) + .src_endpoint_addr(workload_addr.ip(), workload_addr.port()) .actor_process( Process::from_bypass(&binary_str, &pid_str, &ancestors_str) .with_cmd_line(&cmdline_str), @@ -1726,16 +1727,16 @@ fn collect_ancestor_identities(start_pid: u32, stop_pid: u32) -> Vec<(u32, PathB #[cfg(target_os = "linux")] fn resolve_process_identity( entrypoint_pid: u32, - peer_port: u16, + connection: crate::procfs::WorkloadProxyTcpConnection, identity_cache: &BinaryIdentityCache, ) -> std::result::Result { - let socket_owners = crate::procfs::resolve_tcp_peer_socket_owners(entrypoint_pid, peer_port) + let socket_owners = crate::procfs::resolve_tcp_peer_socket_owners(entrypoint_pid, connection) .map_err(|e| IdentityError { - reason: format!("failed to resolve peer binary: {e}"), - binary: None, - binary_pid: None, - ancestors: vec![], - })?; + reason: format!("failed to resolve peer binary: {e}"), + binary: None, + binary_pid: None, + ancestors: vec![], + })?; let mut identities = Vec::with_capacity(socket_owners.owners.len()); for owner in &socket_owners.owners { @@ -1794,7 +1795,7 @@ fn resolve_process_identity( /// Evaluate OPA policy for a TCP connection with identity binding via /proc/net/tcp. #[cfg(target_os = "linux")] fn evaluate_opa_tcp( - peer_addr: SocketAddr, + connection: crate::procfs::WorkloadProxyTcpConnection, engine: &OpaEngine, identity_cache: &BinaryIdentityCache, entrypoint_pid: &AtomicU32, @@ -1841,9 +1842,7 @@ fn evaluate_opa_tcp( }; let total_start = std::time::Instant::now(); - let peer_port = peer_addr.port(); - - let identity = match resolve_process_identity(proc_net_anchor_pid, peer_port, identity_cache) { + let identity = match resolve_process_identity(proc_net_anchor_pid, connection, identity_cache) { Ok(id) => id, Err(err) => { return deny( @@ -1946,7 +1945,7 @@ fn evaluate_endpoint_only_opa(engine: &OpaEngine, host: &str, port: u16) -> Conn /// Non-Linux stub: OPA identity binding requires /proc. #[cfg(not(target_os = "linux"))] fn evaluate_opa_tcp( - _peer_addr: SocketAddr, + _connection: crate::procfs::WorkloadProxyTcpConnection, engine: &OpaEngine, _identity_cache: &BinaryIdentityCache, _entrypoint_pid: &AtomicU32, @@ -3654,8 +3653,9 @@ async fn handle_forward_proxy( canonicalize_forward_host_header(&buf[..used], &canonical_authority)?; // 2. Evaluate OPA policy (same identity binding as CONNECT) - let peer_addr = client.peer_addr().into_diagnostic()?; - let _local_addr = client.local_addr().into_diagnostic()?; + let workload_addr = client.peer_addr().into_diagnostic()?; + let proxy_addr = client.local_addr().into_diagnostic()?; + let connection = crate::procfs::WorkloadProxyTcpConnection::new(workload_addr, proxy_addr); let opa_clone = opa_engine.clone(); let cache_clone = identity_cache.clone(); @@ -3663,7 +3663,7 @@ async fn handle_forward_proxy( let host_clone = host_lc.clone(); let decision = tokio::task::spawn_blocking(move || { evaluate_opa_tcp( - peer_addr, + connection, &opa_clone, &cache_clone, &pid_clone, @@ -3719,7 +3719,7 @@ async fn handle_forward_proxy( OcsfUrl::new("http", &host_lc, &path, port), )) .dst_endpoint(Endpoint::from_domain(&host_lc, port)) - .src_endpoint(Endpoint::from_ip(peer_addr.ip(), peer_addr.port())) + .src_endpoint(Endpoint::from_ip(workload_addr.ip(), workload_addr.port())) .actor_process( Process::from_bypass(&binary_str, &pid_str, &ancestors_str) .with_cmd_line(&cmdline_str), @@ -3981,7 +3981,7 @@ async fn handle_forward_proxy( OcsfUrl::new("http", &host_lc, &path, port), )) .dst_endpoint(Endpoint::from_domain(&host_lc, port)) - .src_endpoint(Endpoint::from_ip(peer_addr.ip(), peer_addr.port())) + .src_endpoint(Endpoint::from_ip(workload_addr.ip(), workload_addr.port())) .actor_process( Process::from_bypass(&binary_str, &pid_str, &ancestors_str) .with_cmd_line(&cmdline_str), @@ -4223,7 +4223,7 @@ async fn handle_forward_proxy( OcsfUrl::new("http", &host_lc, &path, port), )) .dst_endpoint(Endpoint::from_domain(&host_lc, port)) - .src_endpoint(Endpoint::from_ip(peer_addr.ip(), peer_addr.port())) + .src_endpoint(Endpoint::from_ip(workload_addr.ip(), workload_addr.port())) .actor_process( Process::from_bypass(&binary_str, &pid_str, &ancestors_str) .with_cmd_line(&cmdline_str), @@ -4304,7 +4304,7 @@ async fn handle_forward_proxy( OcsfUrl::new("http", &host_lc, &path, port), )) .dst_endpoint(Endpoint::from_domain(&host_lc, port)) - .src_endpoint(Endpoint::from_ip(peer_addr.ip(), peer_addr.port())) + .src_endpoint(Endpoint::from_ip(workload_addr.ip(), workload_addr.port())) .actor_process( Process::from_bypass(&binary_str, &pid_str, &ancestors_str) .with_cmd_line(&cmdline_str), @@ -4361,7 +4361,10 @@ async fn handle_forward_proxy( OcsfUrl::new("http", &host_lc, &path, port), )) .dst_endpoint(Endpoint::from_domain(&host_lc, port)) - .src_endpoint(Endpoint::from_ip(peer_addr.ip(), peer_addr.port())) + .src_endpoint(Endpoint::from_ip( + workload_addr.ip(), + workload_addr.port(), + )) .actor_process( Process::from_bypass(&binary_str, &pid_str, &ancestors_str) .with_cmd_line(&cmdline_str), @@ -4413,7 +4416,7 @@ async fn handle_forward_proxy( OcsfUrl::new("http", &host_lc, &path, port), )) .dst_endpoint(Endpoint::from_domain(&host_lc, port)) - .src_endpoint(Endpoint::from_ip(peer_addr.ip(), peer_addr.port())) + .src_endpoint(Endpoint::from_ip(workload_addr.ip(), workload_addr.port())) .actor_process( Process::from_bypass(&binary_str, &pid_str, &ancestors_str) .with_cmd_line(&cmdline_str), @@ -4470,7 +4473,7 @@ async fn handle_forward_proxy( OcsfUrl::new("http", &host_lc, &path, port), )) .dst_endpoint(Endpoint::from_domain(&host_lc, port)) - .src_endpoint(Endpoint::from_ip(peer_addr.ip(), peer_addr.port())) + .src_endpoint(Endpoint::from_ip(workload_addr.ip(), workload_addr.port())) .actor_process( Process::from_bypass(&binary_str, &pid_str, &ancestors_str) .with_cmd_line(&cmdline_str), @@ -4524,7 +4527,7 @@ async fn handle_forward_proxy( OcsfUrl::new("http", &host_lc, &path, port), )) .dst_endpoint(Endpoint::from_domain(&host_lc, port)) - .src_endpoint(Endpoint::from_ip(peer_addr.ip(), peer_addr.port())) + .src_endpoint(Endpoint::from_ip(workload_addr.ip(), workload_addr.port())) .actor_process( Process::from_bypass(&binary_str, &pid_str, &ancestors_str) .with_cmd_line(&cmdline_str), @@ -4599,7 +4602,7 @@ async fn handle_forward_proxy( OcsfUrl::new("http", &host_lc, &path, port), )) .dst_endpoint(Endpoint::from_domain(&host_lc, port)) - .src_endpoint(Endpoint::from_ip(peer_addr.ip(), peer_addr.port())) + .src_endpoint(Endpoint::from_ip(workload_addr.ip(), workload_addr.port())) .actor_process( Process::from_bypass(&binary_str, &pid_str, &ancestors_str) .with_cmd_line(&cmdline_str), @@ -4806,7 +4809,7 @@ async fn handle_forward_proxy( OcsfUrl::new("http", &host_lc, &path, port), )) .dst_endpoint(Endpoint::from_domain(&host_lc, port)) - .src_endpoint(Endpoint::from_ip(peer_addr.ip(), peer_addr.port())) + .src_endpoint(Endpoint::from_ip(workload_addr.ip(), workload_addr.port())) .actor_process( Process::from_bypass(&binary_str, &pid_str, &ancestors_str) .with_cmd_line(&cmdline_str), @@ -9629,9 +9632,9 @@ network_policies: /// 4. Spawn the temp bash as a child with a `/dev/tcp` one-liner that /// opens a real TCP connection to the listener and holds it open /// inside the bash process. - /// 5. Accept the connection on the listener side and capture the peer's - /// ephemeral port — that's what `resolve_process_identity` uses to - /// walk `/proc/net/tcp` back to the child PID. + /// 5. Accept the connection on the listener side and capture both socket + /// endpoints — that's what `resolve_process_identity` uses to walk + /// `/proc/net/tcp` back to the child PID. /// 6. Overwrite the temp bash on disk with different bytes to simulate /// a `docker cp` hot-swap. The running child is unaffected (it still /// executes from its in-memory image), but `/proc//exe` will @@ -9659,7 +9662,7 @@ network_policies: // 1. Start a listener on loopback. let listener = TcpListener::bind("127.0.0.1:0").expect("bind"); - let listener_port = listener.local_addr().unwrap().port(); + let proxy_addr = listener.local_addr().unwrap(); // 2. Copy /bin/bash to a temp path. let tmp = tempfile::TempDir::new().unwrap(); @@ -9679,8 +9682,10 @@ network_policies: // to keep it open. Do not use an external command like `sleep`: // it inherits the socket fd and intentionally trips the shared // socket ambiguity guard instead of exercising the hot-swap path. - let script = - format!("exec 3<>/dev/tcp/127.0.0.1/{listener_port}; read -r -t 30 _ <&3 || true"); + let script = format!( + "exec 3<>/dev/tcp/127.0.0.1/{}; read -r -t 30 _ <&3 || true", + proxy_addr.port() + ); let mut child = Command::new(&bash_v1) .arg("-c") .arg(&script) @@ -9690,9 +9695,9 @@ network_policies: .spawn() .expect("spawn hotswap-bash child"); - // 5. Accept on the listener side, capture the peer port. + // 5. Accept on the listener side and capture the peer endpoint. listener.set_nonblocking(false).expect("blocking listener"); - let (mut stream, peer_addr) = match listener.accept() { + let (mut stream, workload_addr) = match listener.accept() { Ok(pair) => pair, Err(e) => { let _ = child.kill(); @@ -9700,7 +9705,7 @@ network_policies: panic!("failed to accept child connection: {e}"); } }; - let peer_port = peer_addr.port(); + let connection = crate::procfs::WorkloadProxyTcpConnection::new(workload_addr, proxy_addr); // Drain any spurious data; we just need the socket open. stream .set_read_timeout(Some(Duration::from_millis(50))) @@ -9727,7 +9732,7 @@ network_policies: // contract: hash the live executable via /proc//exe while // returning a clean display path for policy/logging. let test_pid = std::process::id(); - let result = resolve_process_identity(test_pid, peer_port, &cache); + let result = resolve_process_identity(test_pid, connection, &cache); let child_pid = child.id(); // Always clean up the child before asserting so a failure doesn't @@ -9802,9 +9807,10 @@ network_policies: } let listener = TcpListener::bind("127.0.0.1:0").expect("bind listener"); - let listener_port = listener.local_addr().unwrap().port(); - let stream = TcpStream::connect(("127.0.0.1", listener_port)).expect("connect"); - let peer_port = stream.local_addr().unwrap().port(); + let proxy_addr = listener.local_addr().unwrap(); + let stream = TcpStream::connect(proxy_addr).expect("connect"); + let workload_addr = stream.local_addr().unwrap(); + let connection = crate::procfs::WorkloadProxyTcpConnection::new(workload_addr, proxy_addr); let (_accepted, _) = listener.accept().expect("accept"); let fd = stream.as_raw_fd(); @@ -9860,7 +9866,7 @@ network_policies: let cache = BinaryIdentityCache::new(); - let mut result = resolve_process_identity(entrypoint_pid, peer_port, &cache); + let mut result = resolve_process_identity(entrypoint_pid, connection, &cache); for _ in 0..10 { match &result { Err(err) @@ -9869,7 +9875,7 @@ network_policies: { // /proc//fd scan transiently failed; give procfs time to settle. std::thread::sleep(Duration::from_millis(50)); - result = resolve_process_identity(entrypoint_pid, peer_port, &cache); + result = resolve_process_identity(entrypoint_pid, connection, &cache); } Ok(_) => { // On arm64 under heavy CI load the /proc fd scan can transiently @@ -9877,7 +9883,7 @@ network_policies: // the child as owner and yielding a spurious Ok. Retry to give // both owners time to appear consistently in /proc//fd. std::thread::sleep(Duration::from_millis(50)); - result = resolve_process_identity(entrypoint_pid, peer_port, &cache); + result = resolve_process_identity(entrypoint_pid, connection, &cache); } _ => break, } From b422b6783a7af2ef3398aeb5461224aad39909aa Mon Sep 17 00:00:00 2001 From: Roland Huss Date: Fri, 24 Jul 2026 18:10:41 +0200 Subject: [PATCH 3/7] feat(cli): add --output json/yaml to sandbox get, status, and sandbox create (#1989) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat(cli): add --output json/yaml to sandbox get, status, and sandbox create Add structured output support (JSON and YAML) to sandbox lifecycle commands: sandbox get, status, and sandbox create. Introduce ProgressOutput enum to cleanly separate interactive, plain, and silent display modes during sandbox provisioning. Signed-off-by: Roland Huß * fix(cli): reject structured create output with side effects Signed-off-by: Evan Lezar * fix(cli): suppress upload ssh stdout Signed-off-by: Evan Lezar --------- Signed-off-by: Roland Huß Signed-off-by: Evan Lezar Co-authored-by: Evan Lezar --- crates/openshell-cli/src/main.rs | 73 ++- crates/openshell-cli/src/run.rs | 545 +++++++++++++++--- crates/openshell-cli/src/ssh.rs | 2 +- .../sandbox_create_lifecycle_integration.rs | 78 ++- .../sandbox_name_fallback_integration.rs | 41 +- docs/sandboxes/manage-gateways.mdx | 6 + docs/sandboxes/manage-sandboxes.mdx | 12 + 7 files changed, 648 insertions(+), 109 deletions(-) diff --git a/crates/openshell-cli/src/main.rs b/crates/openshell-cli/src/main.rs index a44b0eafa8..00942d79ec 100644 --- a/crates/openshell-cli/src/main.rs +++ b/crates/openshell-cli/src/main.rs @@ -582,7 +582,11 @@ enum Commands { /// Show gateway status and information. #[command(help_template = LEAF_HELP_TEMPLATE, next_help_heading = "FLAGS")] - Status, + Status { + /// Output format. + #[arg(short = 'o', long = "output", value_enum, default_value_t = OutputFormat::Table)] + output: OutputFormat, + }, /// Manage inference configuration. #[command(after_help = INFERENCE_EXAMPLES, help_template = SUBCOMMAND_HELP_TEMPLATE)] @@ -1434,6 +1438,10 @@ enum SandboxCommands { #[arg(long, value_parser = ["manual", "auto"], default_value = "manual")] approval_mode: String, + /// Output format. + #[arg(short = 'o', long = "output", value_enum, default_value_t = OutputFormat::Table, conflicts_with_all = ["editor", "command", "no_keep", "forward"])] + output: OutputFormat, + /// Command to run after "--" (defaults to an interactive shell). #[arg(last = true, allow_hyphen_values = true)] command: Vec, @@ -1447,8 +1455,12 @@ enum SandboxCommands { name: Option, /// Print only the active policy YAML (same policy as the default view; stdout only). - #[arg(long)] + #[arg(long, conflicts_with = "output")] policy_only: bool, + + /// Output format. + #[arg(short = 'o', long = "output", value_enum, default_value_t = OutputFormat::Table)] + output: OutputFormat, }, /// List sandboxes. @@ -2270,11 +2282,24 @@ async fn main() -> Result<()> { // ----------------------------------------------------------- // Top-level status // ----------------------------------------------------------- - Some(Commands::Status) => { + Some(Commands::Status { output }) => { if let Ok(ctx) = resolve_gateway(&cli.gateway, &cli.gateway_endpoint) { let mut tls = tls.with_gateway_name(&ctx.name); let auth_error = apply_auth_with_status(&mut tls, &ctx.name); - run::gateway_status(&ctx.name, &ctx.endpoint, &tls, auth_error.as_deref()).await?; + run::gateway_status( + &ctx.name, + &ctx.endpoint, + output.as_str(), + &tls, + auth_error.as_deref(), + ) + .await?; + } else if openshell_cli::output::print_output_single( + output.as_str(), + &(), + |()| serde_json::json!({"status": "not_configured"}), + )? { + // Structured output handled. } else { println!("{}", "Gateway Status".cyan().bold()); println!(); @@ -2885,6 +2910,7 @@ async fn main() -> Result<()> { labels, envs, approval_mode, + output, command, } => { // Resolve --tty / --no-tty into an Option override. @@ -2971,6 +2997,7 @@ async fn main() -> Result<()> { labels: labels_map, environment: env_map, approval_mode: &approval_mode, + output: output.as_str(), }, &cli.workspace, &tls, @@ -3030,10 +3057,21 @@ async fn main() -> Result<()> { | SandboxCommands::Download { .. } => { unreachable!() } - SandboxCommands::Get { name, policy_only } => { + SandboxCommands::Get { + name, + policy_only, + output, + } => { let name = resolve_sandbox_name(name, &ctx.name, &cli.workspace)?; - run::sandbox_get(endpoint, &name, policy_only, &cli.workspace, &tls) - .await?; + run::sandbox_get( + endpoint, + &name, + policy_only, + output.as_str(), + &cli.workspace, + &tls, + ) + .await?; } SandboxCommands::List { limit, @@ -3883,7 +3921,7 @@ mod tests { .expect("global gateway flag should parse with subcommands"); assert_eq!(cli.gateway.as_deref(), Some("demo")); - assert!(matches!(cli.command, Some(Commands::Status))); + assert!(matches!(cli.command, Some(Commands::Status { .. }))); } #[test] @@ -5025,6 +5063,25 @@ mod tests { ); } + #[test] + fn sandbox_create_output_conflicts_with_side_effect_args() { + for (label, extra_args) in [ + ("--editor", &["--editor", "code"][..]), + ("trailing command", &["--", "claude"][..]), + ("--no-keep", &["--no-keep"][..]), + ("--forward", &["--forward", "8080"][..]), + ] { + let args = ["openshell", "sandbox", "create", "--output", "json"] + .into_iter() + .chain(extra_args.iter().copied()); + let result = Cli::try_parse_from(args); + assert!( + result.is_err(), + "structured output should conflict with {label}" + ); + } + } + #[test] fn sandbox_create_resource_flags_parse() { let cli = Cli::try_parse_from([ diff --git a/crates/openshell-cli/src/run.rs b/crates/openshell-cli/src/run.rs index a2ad725a4c..9fddfcc7f5 100644 --- a/crates/openshell-cli/src/run.rs +++ b/crates/openshell-cli/src/run.rs @@ -51,18 +51,18 @@ use openshell_core::proto::{ ExposeServiceRequest, GetDraftHistoryRequest, GetDraftPolicyRequest, GetGatewayConfigRequest, GetGatewayInfoRequest, GetInferenceRouteRequest, GetProviderProfileRequest, GetProviderRefreshStatusRequest, GetProviderRequest, GetSandboxConfigRequest, - GetSandboxLogsRequest, GetSandboxPolicyStatusRequest, GetSandboxRequest, GetServiceRequest, - GpuResourceRequirements, HealthRequest, ImportProviderProfilesRequest, - LintProviderProfilesRequest, ListProviderProfilesRequest, ListProvidersRequest, - ListSandboxPoliciesRequest, ListSandboxProvidersRequest, ListSandboxesRequest, - ListServicesRequest, PolicySource, PolicyStatus, Provider, ProviderCredentialRefreshStatus, - ProviderCredentialRefreshStrategy, ProviderProfile, ProviderProfileDiagnostic, - ProviderProfileImportItem, RejectDraftChunkRequest, ResourceRequirements, - RevokeSshSessionRequest, RotateProviderCredentialRequest, Sandbox, SandboxPhase, SandboxPolicy, - SandboxSpec, SandboxTemplate, ServiceEndpointResponse, ServiceStatus, SetInferenceRouteRequest, - SettingScope, TcpForwardFrame, TcpForwardInit, TcpRelayTarget, UpdateConfigRequest, - UpdateProviderProfilesRequest, UpdateProviderRequest, WatchSandboxRequest, exec_sandbox_event, - setting_value, tcp_forward_init, + GetSandboxConfigResponse, GetSandboxLogsRequest, GetSandboxPolicyStatusRequest, + GetSandboxRequest, GetServiceRequest, GpuResourceRequirements, HealthRequest, + ImportProviderProfilesRequest, LintProviderProfilesRequest, ListProviderProfilesRequest, + ListProvidersRequest, ListSandboxPoliciesRequest, ListSandboxProvidersRequest, + ListSandboxesRequest, ListServicesRequest, PolicySource, PolicyStatus, Provider, + ProviderCredentialRefreshStatus, ProviderCredentialRefreshStrategy, ProviderProfile, + ProviderProfileDiagnostic, ProviderProfileImportItem, RejectDraftChunkRequest, + ResourceRequirements, RevokeSshSessionRequest, RotateProviderCredentialRequest, Sandbox, + SandboxPhase, SandboxPolicy, SandboxSpec, SandboxTemplate, ServiceEndpointResponse, + ServiceStatus, SetInferenceRouteRequest, SettingScope, TcpForwardFrame, TcpForwardInit, + TcpRelayTarget, UpdateConfigRequest, UpdateProviderProfilesRequest, UpdateProviderRequest, + WatchSandboxRequest, exec_sandbox_event, setting_value, tcp_forward_init, }; use openshell_core::settings; use openshell_core::{ObjectId, ObjectName, ObjectWorkspace}; @@ -122,27 +122,55 @@ struct ComputeDriverCapabilitiesView { driver_version: String, } +enum ProgressOutput { + Interactive(ProvisioningDisplay), + Plain, + Silent, +} + +impl ProgressOutput { + fn as_interactive_mut(&mut self) -> Option<&mut ProvisioningDisplay> { + match self { + Self::Interactive(d) => Some(d), + _ => None, + } + } + + fn as_interactive(&self) -> Option<&ProvisioningDisplay> { + match self { + Self::Interactive(d) => Some(d), + _ => None, + } + } + + fn is_plain(&self) -> bool { + matches!(self, Self::Plain) + } +} + /// Show gateway status. #[allow(clippy::branches_sharing_code)] pub async fn gateway_status( gateway_name: &str, server: &str, + output: &str, tls: &TlsOptions, auth_preparation_error: Option<&str>, ) -> Result<()> { - println!("{}", "Server Status".cyan().bold()); - println!(); - println!(" {} {}", "Gateway:".dimmed(), gateway_name); - println!(" {} {}", "Server:".dimmed(), server); - - // Try to connect and get health - match grpc_client(server, tls).await { + // Build status data before any output. + let is_bearer = tls.is_bearer_auth(); + let (status_str, version, error, http_status, authentication): ( + &str, + Option, + Option, + Option, + GatewayAuthenticationState, + ) = match grpc_client(server, tls).await { Ok(mut client) => match client.health(HealthRequest {}).await { Ok(response) => { let health = response.into_inner(); - println!(" {} {}", "Status:".dimmed(), "Connected".green()); - let authentication = match auth_preparation_error { - Some(error) => GatewayAuthenticationState::Failed(error.to_string()), + let auth = match auth_preparation_error { + Some(e) => GatewayAuthenticationState::Failed(e.to_string()), None => gateway_authentication_state( client .get_gateway_info(GetGatewayInfoRequest {}) @@ -152,52 +180,125 @@ pub async fn gateway_status( server, ), }; - print_gateway_authentication_state(&authentication); - println!(" {} {}", "Version:".dimmed(), health.version); + ("connected", Some(health.version), None, None, auth) } Err(e) => { - let authentication = auth_preparation_error.map_or_else( + let auth = auth_preparation_error.map_or_else( || { GatewayAuthenticationState::Unverified( "gRPC health check failed".to_string(), ) }, - |error| GatewayAuthenticationState::Failed(error.to_string()), + |err| GatewayAuthenticationState::Failed(err.to_string()), ); - if let Some(status) = http_health_check(server, tls).await? { - if status.is_success() { - println!(" {} {}", "Status:".dimmed(), "Connected (HTTP)".yellow()); - println!(" {} {}", "HTTP: ".dimmed(), status); - println!(" {} {}", "gRPC error:".dimmed(), e); - } else { - println!(" {} {}", "Status:".dimmed(), "Error".red()); - println!(" {} {}", "HTTP:".dimmed(), status); - println!(" {} {}", "gRPC error:".dimmed(), e); - } - } else { - println!(" {} {}", "Status:".dimmed(), "Error".red()); - println!(" {} {}", "Error:".dimmed(), e); - } - print_gateway_authentication_state(&authentication); + http_health_check(server, tls).await?.map_or_else( + || ("error", None, Some(e.to_string()), None, auth.clone()), + |http| { + let hs = Some(http.to_string()); + if http.is_success() { + ( + "connected_http", + None, + Some(e.to_string()), + hs, + auth.clone(), + ) + } else { + ("error", None, Some(e.to_string()), hs, auth.clone()) + } + }, + ) } }, Err(e) => { - let authentication = auth_preparation_error.map_or_else( + let auth = auth_preparation_error.map_or_else( || GatewayAuthenticationState::Unverified("gateway unreachable".to_string()), - |error| GatewayAuthenticationState::Failed(error.to_string()), + |err| GatewayAuthenticationState::Failed(err.to_string()), ); - if let Some(status) = http_health_check(server, tls).await? { - if status.is_success() { - println!(" {} {}", "Status:".dimmed(), "Connected (HTTP)".yellow()); - println!(" {} {}", "HTTP:".dimmed(), status); + http_health_check(server, tls).await?.map_or_else( + || { + ( + "disconnected", + None, + Some(e.to_string()), + None, + auth.clone(), + ) + }, + |http| { + let hs = Some(http.to_string()); + if http.is_success() { + ( + "connected_http", + None, + Some(e.to_string()), + hs, + auth.clone(), + ) + } else { + ("disconnected", None, Some(e.to_string()), hs, auth.clone()) + } + }, + ) + } + }; + + let json_data = status_to_json( + gateway_name, + server, + is_bearer, + status_str, + &version, + &error, + &http_status, + &authentication, + ); + if crate::output::print_output_single(output, &json_data, Clone::clone)? { + return Ok(()); + } + + // Human-readable output. + println!("{}", "Server Status".cyan().bold()); + println!(); + println!(" {} {}", "Gateway:".dimmed(), gateway_name); + println!(" {} {}", "Server:".dimmed(), server); + + match status_str { + "connected" => { + println!(" {} {}", "Status:".dimmed(), "Connected".green()); + print_gateway_authentication_state(&authentication); + if let Some(ref v) = version { + println!(" {} {}", "Version:".dimmed(), v); + } + } + "connected_http" => { + println!(" {} {}", "Status:".dimmed(), "Connected (HTTP)".yellow()); + if let Some(ref hs) = http_status { + println!(" {} {}", "HTTP: ".dimmed(), hs); + } + if let Some(ref e) = error { + println!(" {} {}", "gRPC error:".dimmed(), e); + } + print_gateway_authentication_state(&authentication); + } + "error" => { + println!(" {} {}", "Status:".dimmed(), "Error".red()); + if let Some(ref hs) = http_status { + println!(" {} {}", "HTTP:".dimmed(), hs); + if let Some(ref e) = error { println!(" {} {}", "gRPC error:".dimmed(), e); - } else { - println!(" {} {}", "Status:".dimmed(), "Disconnected".red()); - println!(" {} {}", "HTTP:".dimmed(), status); - println!(" {} {}", "Error:".dimmed(), e); } - } else { - println!(" {} {}", "Status:".dimmed(), "Disconnected".red()); + } else if let Some(ref e) = error { + println!(" {} {}", "Error:".dimmed(), e); + } + print_gateway_authentication_state(&authentication); + } + _ => { + println!(" {} {}", "Status:".dimmed(), "Disconnected".red()); + if let Some(ref hs) = http_status { + println!(" {} {}", "HTTP:".dimmed(), hs); + } + if let Some(ref e) = error { println!(" {} {}", "Error:".dimmed(), e); } print_gateway_authentication_state(&authentication); @@ -293,6 +394,60 @@ fn print_gateway_authentication_state(state: &GatewayAuthenticationState) { } } +fn authentication_state_to_json(state: &GatewayAuthenticationState) -> serde_json::Value { + match state { + GatewayAuthenticationState::Authenticated(provider) => serde_json::json!({ + "status": "authenticated", + "provider": provider, + }), + GatewayAuthenticationState::NotRequired(mode) => serde_json::json!({ + "status": "not_required", + "mode": mode, + }), + GatewayAuthenticationState::Failed(error) => serde_json::json!({ + "status": "failed", + "error": error, + }), + GatewayAuthenticationState::Unverified(reason) => serde_json::json!({ + "status": "unverified", + "reason": reason, + }), + } +} + +#[allow(clippy::too_many_arguments)] +fn status_to_json( + gateway_name: &str, + server: &str, + is_bearer: bool, + status: &str, + version: &Option, + error: &Option, + http_status: &Option, + authentication: &GatewayAuthenticationState, +) -> serde_json::Value { + let mut obj = serde_json::json!({ + "gateway": gateway_name, + "server": server, + "status": status, + "authentication": authentication_state_to_json(authentication), + }); + let map = obj.as_object_mut().expect("json! returns object"); + if is_bearer { + map.insert("auth".into(), serde_json::json!("edge_bearer")); + } + if let Some(v) = version { + map.insert("version".into(), serde_json::json!(v)); + } + if let Some(hs) = http_status { + map.insert("http_status".into(), serde_json::json!(hs)); + } + if let Some(e) = error { + map.insert("error".into(), serde_json::json!(e)); + } + obj +} + fn gateway_service_status_name(status: i32) -> &'static str { match ServiceStatus::try_from(status) { Ok(ServiceStatus::Healthy) => "healthy", @@ -1618,6 +1773,7 @@ pub struct SandboxCreateConfig<'a> { pub labels: HashMap, pub environment: HashMap, pub approval_mode: &'a str, + pub output: &'a str, } impl Default for SandboxCreateConfig<'_> { @@ -1641,6 +1797,7 @@ impl Default for SandboxCreateConfig<'_> { labels: HashMap::new(), environment: HashMap::new(), approval_mode: "manual", + output: "table", } } } @@ -1672,6 +1829,7 @@ pub async fn sandbox_create( labels, environment, approval_mode, + output, } = config; if editor.is_some() && !command.is_empty() { @@ -1821,23 +1979,36 @@ pub async fn sandbox_create( } } + let structured_output = output != "table"; + // Set up display — interactive terminals get a step-based checklist with - // spinners; non-interactive (pipes / CI) get timestamped lines. - let mut display = if interactive { - Some(ProvisioningDisplay::new()) + // spinners; non-interactive (pipes / CI) get timestamped lines; + // structured output suppresses all stdout progress. + let mut display = if structured_output { + ProgressOutput::Silent + } else if interactive { + ProgressOutput::Interactive(ProvisioningDisplay::new()) } else { - None + ProgressOutput::Plain }; - // Print header - print_sandbox_header(&sandbox, display.as_ref()); - - // Set initial active step on the spinner. - if let Some(d) = display.as_mut() { - d.set_active_step(ProvisioningStep::RequestingSandbox); + if structured_output { + eprintln!("Provisioning sandbox (structured output on stdout)..."); } else { - let ts = format_timestamp(Duration::ZERO); - println!(" {} Requesting compute...", ts.dimmed()); + // Print header + print_sandbox_header(&sandbox, display.as_interactive()); + + // Set initial active step on the spinner. + match &mut display { + ProgressOutput::Interactive(d) => { + d.set_active_step(ProvisioningStep::RequestingSandbox); + } + ProgressOutput::Plain => { + let ts = format_timestamp(Duration::ZERO); + println!(" {} Requesting compute...", ts.dimmed()); + } + ProgressOutput::Silent => {} + } } // Non-interactive mode: track start time for timestamps. @@ -1871,6 +2042,7 @@ pub async fn sandbox_create( .into_inner(); let mut last_phase = sandbox.phase(); + let mut last_sandbox = sandbox.clone(); let mut last_error_reason = String::new(); let mut last_condition_message = ready_false_condition_message(sandbox.status.as_ref()); // Track whether we have seen a non-Ready phase during the watch. @@ -1897,10 +2069,12 @@ pub async fn sandbox_create( resource_requirements.as_ref(), last_condition_message.as_deref(), ); - if let Some(d) = display.as_mut() { + if let Some(d) = display.as_interactive_mut() { d.finish_error(&timeout_message); } - println!(); + if display.is_plain() { + println!(); + } return Err(miette::miette!(timeout_message)); } @@ -1916,10 +2090,12 @@ pub async fn sandbox_create( resource_requirements.as_ref(), last_condition_message.as_deref(), ); - if let Some(d) = display.as_mut() { + if let Some(d) = display.as_interactive_mut() { d.finish_error(&timeout_message); } - println!(); + if display.is_plain() { + println!(); + } return Err(miette::miette!(timeout_message)); } }; @@ -1929,6 +2105,7 @@ pub async fn sandbox_create( Some(openshell_core::proto::sandbox_stream_event::Payload::Sandbox(s)) => { let phase = SandboxPhase::try_from(s.phase()).unwrap_or(SandboxPhase::Unknown); last_phase = s.phase(); + last_sandbox = s.clone(); if let Some(message) = ready_false_condition_message(s.status.as_ref()) { last_condition_message = Some(message); } @@ -1956,7 +2133,7 @@ pub async fn sandbox_create( // Only accept Ready as terminal after we've observed a // non-Ready phase, proving the controller has reconciled. if saw_non_ready && phase == SandboxPhase::Ready { - if let Some(d) = display.as_mut() { + if let Some(d) = display.as_interactive_mut() { d.clear(); } break; @@ -1970,7 +2147,24 @@ pub async fn sandbox_create( } Some(openshell_core::proto::sandbox_stream_event::Payload::Event(ev)) => { let extends_timeout = is_provisioning_progress_event(&ev); - if handle_platform_progress_event(&ev, &mut display, provision_start) { + // Silent mode suppresses all progress output; only update + // the deadline when applicable. + let handled = match &mut display { + ProgressOutput::Interactive(d) => { + let mut opt = Some(std::mem::replace(d, ProvisioningDisplay::new())); + let h = handle_platform_progress_event(&ev, &mut opt, provision_start); + if let Some(inner) = opt { + *d = inner; + } + h + } + ProgressOutput::Plain => { + let mut opt: Option = None; + handle_platform_progress_event(&ev, &mut opt, provision_start) + } + ProgressOutput::Silent => false, + }; + if handled { if extends_timeout { provisioning_idle_deadline = Instant::now() + provision_timeout; } @@ -1980,19 +2174,21 @@ pub async fn sandbox_create( provisioning_idle_deadline = Instant::now() + provision_timeout; } - if let Some(d) = display.as_mut() { - // Unknown events: show as detail on the current spinner. - if !ev.message.is_empty() { - d.set_active_detail(&ev.message); - } + if let Some(d) = display.as_interactive_mut() + && !ev.message.is_empty() + { + d.set_active_detail(&ev.message); } } Some(openshell_core::proto::sandbox_stream_event::Payload::Warning(w)) => { - if let Some(d) = display.as_mut() { - d.println(&format!(" {} {}", "!".yellow().bold(), w.message.yellow())); - } else { - let ts = format_timestamp(provision_start.elapsed()); - eprintln!(" {} {} {}", ts.dimmed(), "WARN".yellow(), w.message); + match &display { + ProgressOutput::Interactive(d) => { + d.println(&format!(" {} {}", "!".yellow().bold(), w.message.yellow())); + } + ProgressOutput::Plain | ProgressOutput::Silent => { + let ts = format_timestamp(provision_start.elapsed()); + eprintln!(" {} {} {}", ts.dimmed(), "WARN".yellow(), w.message); + } } } Some(openshell_core::proto::sandbox_stream_event::Payload::DraftPolicyUpdate(_)) @@ -2005,7 +2201,7 @@ pub async fn sandbox_create( // If we exited the loop without hitting the Ready break, finish the display. let final_phase = SandboxPhase::try_from(last_phase).unwrap_or(SandboxPhase::Unknown); if final_phase != SandboxPhase::Ready - && let Some(d) = display.as_mut() + && let Some(d) = display.as_interactive_mut() { if final_phase == SandboxPhase::Error { let msg = if last_error_reason.is_empty() { @@ -2115,6 +2311,11 @@ pub async fn sandbox_create( ); } + if structured_output { + crate::output::print_output_single(output, &last_sandbox, sandbox_to_json)?; + return Ok(()); + } + if let Some(editor) = editor { let ssh_gateway_name = effective_tls.gateway_name().unwrap_or(gateway_name); sandbox_connect_editor( @@ -2453,6 +2654,7 @@ pub async fn sandbox_get( server: &str, name: &str, policy_only: bool, + output: &str, workspace: &str, tls: &TlsOptions, ) -> Result<()> { @@ -2494,6 +2696,11 @@ pub async fn sandbox_get( return Ok(()); } + let detail_json = sandbox_detail_to_json(&sandbox, &config)?; + if crate::output::print_output_single(output, &detail_json, Clone::clone)? { + return Ok(()); + } + println!("{}", "Sandbox:".cyan().bold()); println!(); let id = if sandbox.object_id().is_empty() { @@ -3289,6 +3496,48 @@ fn sandbox_to_json(sandbox: &Sandbox) -> serde_json::Value { }) } +fn sandbox_detail_to_json( + sandbox: &Sandbox, + config: &GetSandboxConfigResponse, +) -> Result { + let mut value = sandbox_to_json(sandbox); + let obj = value + .as_object_mut() + .expect("sandbox_to_json returns object"); + + let policy_source = if config.policy_source == PolicySource::Global as i32 { + "global" + } else { + "sandbox" + }; + obj.insert("policy_source".into(), serde_json::json!(policy_source)); + + let policy_from_global = config.policy_source == PolicySource::Global as i32; + let revision = if policy_from_global { + if config.global_policy_version > 0 { + Some(config.global_policy_version) + } else if config.version > 0 { + Some(config.version) + } else { + None + } + } else if config.version > 0 { + Some(config.version) + } else { + None + }; + obj.insert("revision".into(), serde_json::json!(revision)); + + let policy_json = match config.policy.as_ref() { + Some(p) => openshell_policy::sandbox_policy_to_json_value(p) + .wrap_err("failed to convert policy to JSON")?, + None => serde_json::Value::Null, + }; + obj.insert("policy".into(), policy_json); + + Ok(value) +} + pub async fn sandbox_provider_list( server: &str, name: &str, @@ -6685,7 +6934,7 @@ pub async fn gateway_settings_get(server: &str, json: bool, tls: &TlsOptions) -> fn settings_to_json_sandbox( name: &str, workspace: &str, - response: &openshell_core::proto::GetSandboxConfigResponse, + response: &GetSandboxConfigResponse, ) -> serde_json::Value { let policy_source = if response.policy_source == PolicySource::Global as i32 { "global" @@ -8144,11 +8393,11 @@ mod tests { PROGRESS_STEP_STARTING_SANDBOX, }; use openshell_core::proto::{ - GpuResourceRequirements, PolicyStatus, Provider, ProviderCredentialRefresh, - ProviderCredentialRefreshStatus, ProviderCredentialRefreshStrategy, - ProviderCredentialTokenGrant, ProviderProfile, ProviderProfileCredential, - ResourceRequirements, SandboxCondition, SandboxPolicyRevision, SandboxStatus, - datamodel::v1::ObjectMeta, + GetSandboxConfigResponse, GpuResourceRequirements, PolicySource, PolicyStatus, Provider, + ProviderCredentialRefresh, ProviderCredentialRefreshStatus, + ProviderCredentialRefreshStrategy, ProviderCredentialTokenGrant, ProviderProfile, + ProviderProfileCredential, ResourceRequirements, Sandbox, SandboxCondition, SandboxPhase, + SandboxPolicyRevision, SandboxStatus, datamodel::v1::ObjectMeta, }; #[test] @@ -10248,4 +10497,124 @@ mod tests { "raw milliseconds field should not exist" ); } + + #[test] + fn sandbox_detail_to_json_includes_policy_fields() { + let mut sandbox = Sandbox { + metadata: Some(ObjectMeta { + id: "sb-123".to_string(), + name: "test-sb".to_string(), + resource_version: 5, + created_at_ms: 1_609_459_200_000, + ..Default::default() + }), + ..Default::default() + }; + sandbox.set_phase(SandboxPhase::Ready as i32); + sandbox.set_current_policy_version(2); + + let config = GetSandboxConfigResponse { + policy_source: PolicySource::Global as i32, + global_policy_version: 3, + ..Default::default() + }; + + let json = super::sandbox_detail_to_json(&sandbox, &config).unwrap(); + + assert_eq!(json["id"], "sb-123"); + assert_eq!(json["name"], "test-sb"); + assert_eq!(json["phase"], "Ready"); + assert_eq!(json["policy_source"], "global"); + assert_eq!(json["revision"], 3); + assert!(json["policy"].is_null()); + } + + #[test] + fn sandbox_detail_to_json_sandbox_source_without_policy() { + let sandbox = Sandbox { + metadata: Some(ObjectMeta { + id: "sb-456".to_string(), + name: "no-policy-sb".to_string(), + ..Default::default() + }), + ..Default::default() + }; + let config = GetSandboxConfigResponse { + policy_source: PolicySource::Sandbox as i32, + version: 0, + ..Default::default() + }; + + let json = super::sandbox_detail_to_json(&sandbox, &config).unwrap(); + + assert_eq!(json["policy_source"], "sandbox"); + assert!(json["revision"].is_null()); + assert!(json["policy"].is_null()); + } + + #[test] + fn status_to_json_connected() { + let auth = GatewayAuthenticationState::Authenticated("mTLS transport"); + let json = super::status_to_json( + "my-gw", + "http://127.0.0.1:8090", + false, + "connected", + &Some("1.2.3".to_string()), + &None, + &None, + &auth, + ); + + assert_eq!(json["gateway"], "my-gw"); + assert_eq!(json["server"], "http://127.0.0.1:8090"); + assert_eq!(json["status"], "connected"); + assert_eq!(json["version"], "1.2.3"); + assert_eq!(json["authentication"]["status"], "authenticated"); + assert!(json.get("auth").is_none()); + assert!(json.get("error").is_none()); + assert!(json.get("http_status").is_none()); + } + + #[test] + fn status_to_json_disconnected_with_error() { + let auth = GatewayAuthenticationState::Unverified("gateway unreachable".to_string()); + let json = super::status_to_json( + "broken-gw", + "http://10.0.0.1:8090", + false, + "disconnected", + &None, + &Some("connection refused".to_string()), + &None, + &auth, + ); + + assert_eq!(json["status"], "disconnected"); + assert_eq!(json["error"], "connection refused"); + assert_eq!(json["authentication"]["status"], "unverified"); + assert!(json.get("version").is_none()); + } + + #[test] + fn status_to_json_connected_http_with_bearer() { + let auth = GatewayAuthenticationState::Failed("token expired".to_string()); + let json = super::status_to_json( + "edge-gw", + "https://edge.example.com", + true, + "connected_http", + &None, + &Some("gRPC unavailable".to_string()), + &Some("200 OK".to_string()), + &auth, + ); + + assert_eq!(json["status"], "connected_http"); + assert_eq!(json["auth"], "edge_bearer"); + assert_eq!(json["error"], "gRPC unavailable"); + assert_eq!(json["http_status"], "200 OK"); + assert_eq!(json["authentication"]["status"], "failed"); + assert!(json.get("version").is_none()); + } } diff --git a/crates/openshell-cli/src/ssh.rs b/crates/openshell-cli/src/ssh.rs index d277804bf1..f8de99a692 100644 --- a/crates/openshell-cli/src/ssh.rs +++ b/crates/openshell-cli/src/ssh.rs @@ -802,7 +802,7 @@ async fn ssh_tar_upload( "mkdir -p {escaped_dest} && cat | tar xf - -C {escaped_dest}", )) .stdin(Stdio::piped()) - .stdout(Stdio::inherit()) + .stdout(Stdio::null()) .stderr(Stdio::inherit()); let mut child = ssh.spawn().into_diagnostic()?; diff --git a/crates/openshell-cli/tests/sandbox_create_lifecycle_integration.rs b/crates/openshell-cli/tests/sandbox_create_lifecycle_integration.rs index fda3d529f3..f42880d9f6 100644 --- a/crates/openshell-cli/tests/sandbox_create_lifecycle_integration.rs +++ b/crates/openshell-cli/tests/sandbox_create_lifecycle_integration.rs @@ -726,7 +726,7 @@ struct TestServer { endpoint: String, tls: TlsOptions, openshell: TestOpenShell, - _dir: TempDir, + dir: TempDir, } async fn run_server() -> TestServer { @@ -775,7 +775,7 @@ async fn run_server() -> TestServer { endpoint, tls, openshell, - _dir: dir, + dir, } } @@ -1908,3 +1908,77 @@ async fn sandbox_create_env_rejects_invalid_key_name() { "error should mention invalid key, got: {msg}" ); } + +async fn run_cli_sandbox_create( + server: &TestServer, + name: &str, + extra_args: &[&str], +) -> std::process::Output { + let xdg_dir = tempfile::tempdir().unwrap(); + let tls_dir = xdg_dir.path().join("openshell/gateways/openshell/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(); + } + + tokio::process::Command::new(env!("CARGO_BIN_EXE_openshell")) + .args([ + "--gateway", + "openshell", + "--gateway-endpoint", + &server.endpoint, + "sandbox", + "create", + "--name", + name, + "--no-tty", + "--no-auto-providers", + ]) + .args(extra_args) + .env("XDG_CONFIG_HOME", xdg_dir.path()) + .env("HOME", xdg_dir.path()) + .env("OPENSHELL_PROVISION_TIMEOUT", "5") + .output() + .await + .unwrap() +} + +#[tokio::test] +async fn sandbox_create_json_stdout_is_parseable_with_progress_events() { + let server = run_server().await; + server + .openshell + .state + .vm_slow_progress_before_ready + .store(true, Ordering::SeqCst); + + let result = run_cli_sandbox_create(&server, "json-progress", &["--output=json"]).await; + assert!( + result.status.success(), + "sandbox create failed:\n{}", + String::from_utf8_lossy(&result.stderr) + ); + let stdout = String::from_utf8(result.stdout).expect("stdout should be UTF-8"); + serde_json::from_str::(&stdout) + .unwrap_or_else(|err| panic!("stdout should contain only JSON: {err}\n{stdout}")); +} + +#[tokio::test] +async fn sandbox_create_yaml_stdout_is_parseable_with_progress_events() { + let server = run_server().await; + server + .openshell + .state + .vm_slow_progress_before_ready + .store(true, Ordering::SeqCst); + + let result = run_cli_sandbox_create(&server, "yaml-progress", &["--output=yaml"]).await; + assert!( + result.status.success(), + "sandbox create failed:\n{}", + String::from_utf8_lossy(&result.stderr) + ); + let stdout = String::from_utf8(result.stdout).expect("stdout should be UTF-8"); + serde_yml::from_str::(&stdout) + .unwrap_or_else(|err| panic!("stdout should contain only YAML: {err}\n{stdout}")); +} diff --git a/crates/openshell-cli/tests/sandbox_name_fallback_integration.rs b/crates/openshell-cli/tests/sandbox_name_fallback_integration.rs index 699749f0d1..5fa2c97029 100644 --- a/crates/openshell-cli/tests/sandbox_name_fallback_integration.rs +++ b/crates/openshell-cli/tests/sandbox_name_fallback_integration.rs @@ -687,9 +687,16 @@ async fn run_server() -> TestServer { async fn sandbox_get_sends_correct_name() { let ts = run_server().await; - run::sandbox_get(&ts.endpoint, "my-sandbox", false, "default", &ts.tls) - .await - .expect("sandbox_get should succeed"); + run::sandbox_get( + &ts.endpoint, + "my-sandbox", + false, + "table", + "default", + &ts.tls, + ) + .await + .expect("sandbox_get should succeed"); let recorded = ts.openshell.state.last_get_name.lock().await.clone(); assert_eq!( @@ -704,9 +711,16 @@ async fn sandbox_get_sends_correct_name() { async fn sandbox_get_policy_only_round_trip() { let ts = run_server().await; - run::sandbox_get(&ts.endpoint, "my-sandbox", true, "default", &ts.tls) - .await - .expect("sandbox_get with policy_only should succeed"); + run::sandbox_get( + &ts.endpoint, + "my-sandbox", + true, + "table", + "default", + &ts.tls, + ) + .await + .expect("sandbox_get with policy_only should succeed"); let recorded = ts.openshell.state.last_get_name.lock().await.clone(); assert_eq!(recorded.as_deref(), Some("my-sandbox")); @@ -730,7 +744,7 @@ async fn sandbox_get_with_persisted_last_sandbox() { assert_eq!(resolved, "persisted-sb"); // Call sandbox_get with the resolved name. - run::sandbox_get(&ts.endpoint, &resolved, false, "default", &ts.tls) + run::sandbox_get(&ts.endpoint, &resolved, false, "table", "default", &ts.tls) .await .expect("sandbox_get should succeed"); @@ -883,9 +897,16 @@ async fn explicit_name_takes_precedence_over_persisted() { // Persist one name, but supply a different one explicitly. save_last_sandbox("my-cluster", "default", "old-sandbox").expect("save should succeed"); - run::sandbox_get(&ts.endpoint, "explicit-sandbox", false, "default", &ts.tls) - .await - .expect("sandbox_get should succeed"); + run::sandbox_get( + &ts.endpoint, + "explicit-sandbox", + false, + "table", + "default", + &ts.tls, + ) + .await + .expect("sandbox_get should succeed"); let recorded = ts.openshell.state.last_get_name.lock().await.clone(); assert_eq!( diff --git a/docs/sandboxes/manage-gateways.mdx b/docs/sandboxes/manage-gateways.mdx index 91cfdfad28..ff1d0ccd3e 100644 --- a/docs/sandboxes/manage-gateways.mdx +++ b/docs/sandboxes/manage-gateways.mdx @@ -126,6 +126,12 @@ passed the gateway authentication layer. If authentication fails while status remains connected, run `openshell gateway login ` to refresh the stored credentials. +For automation or scripting, use `--output json` or `--output yaml` to get machine-readable output: + +```shell +openshell status --output json +``` + Use `openshell gateway info` when you need elevated runtime details such as initialized compute drivers and driver-reported capability versions: diff --git a/docs/sandboxes/manage-sandboxes.mdx b/docs/sandboxes/manage-sandboxes.mdx index 05418f8f7d..f3f36ecc9e 100644 --- a/docs/sandboxes/manage-sandboxes.mdx +++ b/docs/sandboxes/manage-sandboxes.mdx @@ -20,6 +20,12 @@ Create a sandbox with a single command. For example, to create a sandbox with Cl openshell sandbox create -- claude ``` +For automation, use `--output json` or `--output yaml` to get machine-readable sandbox metadata after creation: + +```shell +openshell sandbox create --output json +``` + Every sandbox requires a gateway. Register or select one before running sandbox commands: ```shell @@ -309,6 +315,12 @@ Get detailed information about a specific sandbox. The output lists **Policy sou openshell sandbox get my-sandbox ``` +For automation, use `--output json` or `--output yaml` to get machine-readable sandbox details: + +```shell +openshell sandbox get my-sandbox --output json +``` + Print only that policy YAML for scripting (same effective policy, no metadata): ```shell From 850bd42e8acb90a35f2abb1e1956ade4317ccffa Mon Sep 17 00:00:00 2001 From: Evan Lezar Date: Fri, 24 Jul 2026 18:28:42 +0200 Subject: [PATCH 4/7] refactor(tui): default create form state (#2458) Signed-off-by: Evan Lezar --- crates/openshell-tui/src/app.rs | 45 +++++++++------------------------ 1 file changed, 12 insertions(+), 33 deletions(-) diff --git a/crates/openshell-tui/src/app.rs b/crates/openshell-tui/src/app.rs index 9e3b8575b5..db7eef1d32 100644 --- a/crates/openshell-tui/src/app.rs +++ b/crates/openshell-tui/src/app.rs @@ -248,8 +248,9 @@ pub type CreateFormData = ( ); /// Which field is focused in the create sandbox modal. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] pub enum CreateFormField { + #[default] Name, Image, Command, @@ -291,9 +292,10 @@ pub struct ProviderEntry { } /// Tracks which phase the create sandbox modal is in. -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, Default, PartialEq, Eq)] pub enum CreatePhase { /// Filling out the form. + #[default] Form, /// Creating the sandbox (background task running). Creating, @@ -303,6 +305,7 @@ pub enum CreatePhase { pub const MIN_CREATING_DISPLAY: Duration = Duration::from_secs(4); /// State for the create sandbox modal form. +#[derive(Default)] pub struct CreateSandboxForm { pub focused_field: CreateFormField, pub name: String, @@ -327,9 +330,10 @@ pub struct CreateSandboxForm { // Create provider form // --------------------------------------------------------------------------- -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, Default, PartialEq, Eq)] pub enum CreateProviderPhase { /// Pick provider type from the known list. + #[default] SelectType, /// Choose: autodetect from env or enter key manually. ChooseMethod, @@ -340,8 +344,9 @@ pub enum CreateProviderPhase { } /// Which field is focused in the provider key entry form. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] pub enum ProviderKeyField { + #[default] Name, /// Focused credential row for known types (index via `cred_cursor`). Credential, @@ -358,6 +363,7 @@ pub enum ProviderKeyField { Submit, } +#[derive(Default)] pub struct CreateProviderForm { pub phase: CreateProviderPhase, /// Known provider type slugs. @@ -2214,17 +2220,8 @@ impl App { .collect(); self.create_form = Some(CreateSandboxForm { - focused_field: CreateFormField::Name, - name: String::new(), - image: String::new(), - command: String::new(), providers, - provider_cursor: 0, - ports: String::new(), - status: None, - phase: CreatePhase::Form, - anim_start: None, - create_result: None, + ..CreateSandboxForm::default() }); } @@ -2325,26 +2322,8 @@ impl App { let types: Vec = known.into_iter().map(String::from).collect(); self.create_provider_form = Some(CreateProviderForm { - phase: CreateProviderPhase::SelectType, types, - type_cursor: 0, - method_cursor: 0, - name: String::new(), - credentials: Vec::new(), - cred_cursor: 0, - config: IndexMap::new(), - config_cursor: 0, - config_key_input: String::new(), - config_value_input: String::new(), - generic_env_name: String::new(), - generic_value: String::new(), - key_field: ProviderKeyField::Name, - is_generic: false, - status: None, - warning: None, - anim_start: None, - create_result: None, - discovered_credentials: None, + ..CreateProviderForm::default() }); } From 77e5c322178c1fd4b469648e86866940514dfdfc Mon Sep 17 00:00:00 2001 From: Philippe Martin Date: Fri, 24 Jul 2026 18:51:52 +0200 Subject: [PATCH 5/7] feat(sandbox,gateway): route sandbox egress through corporate HTTP proxy (#2245) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat(sandbox,gateway): route sandbox egress through corporate HTTP proxy - Chain sandbox egress through a corporate HTTP proxy so outbound traffic from within the sandbox respects the host proxy settings - Forward sandbox proxy environment variables to the generated Podman config so the proxy is applied consistently to Podman-managed workloads Signed-off-by: Philippe Martin * fix(sandbox,podman): make corporate proxy routing operator-owned The operator-configured corporate egress proxy was injected under the conventional HTTPS_PROXY/HTTP_PROXY/NO_PROXY names as defaults beneath sandbox spec/template environment, so a sandbox creator could redirect egress at an arbitrary proxy or disable proxying with NO_PROXY=*. Route the boundary through reserved, supervisor-only variables (OPENSHELL_UPSTREAM_HTTPS_PROXY/HTTP_PROXY/NO_PROXY) written in the Podman driver's required-variable tier. Any sandbox-supplied value under a reserved name is stripped before the operator value is applied, so the supervisor never observes a reserved proxy variable the operator did not set. The supervisor now reads only the reserved names and ignores the conventional proxy variables the sandbox controls. Add the reserved proxy variables to the supervisor-only child-environment denylist so the corporate proxy URL and any embedded credentials are not inherited by the sandbox workload, which reaches egress through the local policy proxy and never needs them. Signed-off-by: Philippe Martin * feat(sandbox,podman): deliver corporate proxy credentials via secret file Proxy credentials were embedded inline in the proxy URL, so they were stored in gateway.toml and exposed in container metadata via 'podman inspect'. Reject inline 'user:pass@' credentials in https_proxy/http_proxy at startup (parsed with the url crate rather than hand-splitting), and add a proxy_auth_file option pointing at a 'user:pass' file. The driver stages that file as a per-sandbox root-only Podman secret, mounts it at a fixed path, and exports only the path in the reserved OPENSHELL_UPSTREAM_PROXY_AUTH_FILE variable, so the credential never appears in config, environment, or container metadata. Reading the file fails closed on a missing, empty, or control-character-bearing value. The supervisor reads the credential from the mounted file and builds the Proxy-Authorization: Basic header, rejecting control characters, and no longer derives credentials from URL userinfo. The auth-file path is added to the child-environment strip list, and the generated gateway.toml is written owner-only (mode 0600). Signed-off-by: Philippe Martin * fix(sandbox,podman): fail closed on invalid upstream proxy configuration The reserved OPENSHELL_UPSTREAM_* variables are an operator-owned egress boundary, but the supervisor treated present-but-invalid values as unset: an unsupported or malformed proxy URL was ignored with a warning, an unreadable auth file proceeded without credentials, and a malformed credential silently became unauthenticated. Any of these could quietly downgrade the corporate proxy boundary to direct dialing or unauthenticated proxy access. Make every configured-but-invalid proxy or auth setting fatal to supervisor proxy startup, emit an OCSF ConfigStateChange failure event before refusing, and share URL validation semantics between the Podman driver and the supervisor through a single validator in openshell-core (parse_upstream_proxy_url), so a value accepted at sandbox-create time can never be rejected in-container or vice versa. Inline user:pass@ URL credentials are now fatal in the supervisor too (previously warn-and-strip), matching the driver. Unset or empty variables still mean no proxy; only present-but-invalid values fail. Error paths never include credential content. Addresses the fail-closed review item on #2245. Signed-off-by: Philippe Martin * fix(sandbox,podman): finish the fail-closed upstream proxy credential contract The upstream proxy URL already had a single shared validator, but the credential did not: the Podman driver rejected only CR/LF/NUL while the supervisor rejected every control character, so a credential accepted at sandbox-create time (e.g. one containing a tab) could still be rejected in-container. Present-but-whitespace reserved OPENSHELL_UPSTREAM_* values were also silently treated as unset, quietly downgrading the operator's egress boundary to direct dialing. Add parse_upstream_proxy_credential to openshell-core as the single source of truth for the documented user:pass credential form (non-empty user, no control characters, trimmed) and use it in both the Podman driver's secret staging and the supervisor's Proxy-Authorization header construction. Error variants carry no payload so credential content can never leak into messages. Make a present-but-empty reserved variable fatal to supervisor proxy startup instead of meaning "unset"; only fully unset variables disable the proxy. The driver correspondingly rejects an empty no_proxy at config time so it can never inject a value the supervisor refuses. Addresses the remaining fail-closed credential/config review item on Signed-off-by: Philippe Martin #2245. * fix(sandbox,podman): close remaining fail-open upstream proxy config paths Two configuration paths could still silently run without the proxy boundary the operator believed was in effect. A no_proxy bypass list configured without any https_proxy/http_proxy was accepted by both the driver and the supervisor and simply meant "dial everything directly". Reject it on both sides, exactly like the existing proxy_auth_file-without-proxy rule: an operator who wrote a bypass list assumed proxying was active, so accepting it hides a fail-open state. The gateway.sh dev script guarded proxy settings with [[ -n "${VAR:-}" ]], which conflates unset with explicitly-empty and dropped the latter before the gateway's validation could see it. Use ${VAR+x} instead so a set-but-empty variable is written into gateway.toml and rejected at startup by validate_proxy_config rather than silently discarded. Addresses the remaining fail-open configuration review item on #2245. Signed-off-by: Philippe Martin * fix(sandbox,podman): reject upstream proxy URLs with path, query, or fragment parse_upstream_proxy_url accepted URLs like http://proxy.corp.com:8080/some/path and silently discarded everything after host:port, a lenience inherited from the original supervisor parser. A forward proxy is addressed by host:port only, so extra components indicate a misconfiguration (for example a pasted endpoint URL) and silently truncating them violates the present-but-invalid-is-fatal contract enforced everywhere else in this configuration surface. Reject a path, query, or fragment in the shared validator with a new UnexpectedComponent error. A bare trailing slash remains accepted because the url crate normalizes an absent http path to "/", making the two indistinguishable. Both the Podman driver (gateway startup) and the supervisor (sandbox startup) inherit the rule through the shared parser, keeping their semantics identical by construction. Addresses the proxy URL component review item on #2245. Signed-off-by: Philippe Martin * fix(sandbox,podman): remove plain-HTTP upstream proxy support The http_proxy path tunneled plain-HTTP requests through the corporate proxy with CONNECT to port 80 and then sent origin-form requests down the tunnel. Conventional enterprise forward proxies expect plain HTTP as absolute-form requests sent directly over the proxy connection, and commonly refuse CONNECT to port 80, so the setting looked supported but failed against typical deployments. Tunneling also blinds the proxy to the one protocol it could inspect. Narrow the feature to TLS (CONNECT) egress only, which is the conventional and already-correct case: plain-HTTP requests now always dial the destination directly, and only client CONNECT tunnels chain through the corporate proxy. Remove the http_proxy config field, the --sandbox-http-proxy / OPENSHELL_SANDBOX_HTTP_PROXY driver surface, the reserved OPENSHELL_UPSTREAM_HTTP_PROXY variable, and the UpstreamScheme plumbing. The feature never shipped, so this is a clean removal; a stray http_proxy key in gateway.toml still fails loudly through the config's deny_unknown_fields. Removing the plain-HTTP proxy branch also removes its host-gateway special case; the architecture doc now documents the real host-gateway behavior (add driver-injected host aliases to the reserved NO_PROXY list) instead of an invariant the HTTPS path never implemented. Plain-HTTP forwarding through a corporate proxy can return later as absolute-form forwarding behind its own design review. Addresses the plain-HTTP forwarding review item on #2245. Signed-off-by: Philippe Martin * fix(sandbox,podman): escape generated TOML and require explicit proxy URL form Escape backslashes, quotes, and control characters when gateway.sh writes proxy values into gateway.toml, so a hostile or unusual environment value cannot corrupt the config or inject extra keys. Restrict the upstream proxy URL grammar to the documented http://host:port form: a scheme-less value is no longer normalized to http:// and a missing port is no longer silently defaulted to 80. Docs, README, and CLI help now state the explicit-form requirement consistently. Also fix a test-only call of handle_tcp_connection that was missing the upstream_proxy argument added in an earlier commit. Signed-off-by: Philippe Martin * fix(sandbox,podman): preserve tunneled bytes read with the CONNECT response The CONNECT handshake reads the corporate proxy's response in chunks, so the read that completes the header block can also contain the first tunneled payload bytes. Those bytes were discarded, silently corrupting the start of the tunnel for server-speaks-first destinations or proxies that coalesce writes. connect_via now returns a PrefixedStream that replays any bytes received past the response terminator before reading from the socket again; writes pass through unchanged. Direct dials wrap the stream with an empty prefix so downstream relay and TLS paths keep a single stream type, and tls_connect_upstream is generalized to any AsyncRead + AsyncWrite stream. Adds regression coverage for a combined response/payload read and for prefix replay ordering. Signed-off-by: Philippe Martin * fix(sandbox,podman): gate cleartext proxy Basic auth behind an explicit opt-in Proxy-Authorization: Basic is base64 over the plain-TCP connection to the http:// corporate proxy, so anyone on the network path between the sandbox host and the proxy can recover the credential. Sending it is now an explicit operator decision instead of an implicit side effect of configuring proxy_auth_file. Add a proxy_auth_allow_insecure driver setting (CLI --sandbox-proxy-auth-allow-insecure, env OPENSHELL_SANDBOX_PROXY_AUTH_ALLOW_INSECURE), delivered to the supervisor as the reserved OPENSHELL_UPSTREAM_PROXY_AUTH_ALLOW_INSECURE variable. Fail-closed pairing on both sides: an auth file without the acknowledgement is rejected at gateway startup and at supervisor startup, as is the acknowledgement without an auth file or any value other than 'true'. gateway.sh writes the key only as a TOML boolean; a non-boolean value is emitted as a quoted string so the gateway rejects it at startup instead of risking injection. Documents the exposure prominently in the gateway config reference, the driver README, and the sandbox architecture doc. Signed-off-by: Philippe Martin * fix(sandbox,podman): honor port qualifiers and resolved addresses in NO_PROXY Two divergences from the documented NO_PROXY contract: - A port-qualified entry (internal.corp:8443) was silently stripped to its hostname and bypassed the proxy for every port, excluding traffic the operator never listed. Entries now keep the optional :port qualifier (also on IP and CIDR entries) and only apply to that destination port; a trailing qualifier that is not a valid port stays part of the pattern instead of widening the entry. - IP and CIDR entries only matched IP-literal hosts, so a bypass like 10.0.0.0/8 never applied to hostnames resolving into that range. NO_PROXY evaluation now sees the validated resolved addresses: an IP/CIDR entry matching through resolution authorizes a direct dial of only the addresses it contains, so a bypass scoped to an internal range cannot widen into a direct dial of addresses outside it. Hostname-level matches (loopback, wildcard, domain entries, IP-literal hosts) keep authorizing all validated addresses. proxy_for is replaced by decision(host, port, resolved) returning either the proxy endpoint or the permitted direct-dial subset, and dial_upstream restricts the direct connect to that subset. Adds regression coverage for port-scoped bypasses on domain, IP, and CIDR entries, invalid port qualifiers, resolved-address matching, and split-resolution subset dialing. Signed-off-by: Philippe Martin * fix(sandbox,podman): bind proxied CONNECT tunnels to validated addresses The CONNECT request sent to the corporate proxy carried the destination hostname, so the proxy resolved the name itself and the addresses that had passed SSRF and allowed_ips validation were discarded. Split-horizon DNS or rebinding at the proxy could then reach internal or otherwise unapproved destinations through a tunnel the supervisor logged as validated, and IP-range policy could not be enforced at all on proxied dials. CONNECT now targets a validated resolved address by default: the proxy performs no DNS resolution and the tunnel stays bound to the answer the supervisor checked. The hostname still travels inside the tunnel (TLS SNI, application Host), so destination servers behave normally. In split-horizon networks, operators point the gateway host at the corporate resolver so internal names validate to their internal addresses. For proxies whose ACLs filter on hostnames and reject IP CONNECT targets, a new proxy_connect_by_hostname opt-in (CLI --sandbox-proxy-connect-by-hostname, env OPENSHELL_SANDBOX_PROXY_CONNECT_BY_HOSTNAME, reserved OPENSHELL_UPSTREAM_PROXY_CONNECT_BY_HOSTNAME) restores hostname CONNECT, documented as re-opening proxy-side resolution and making the proxy's ACLs the effective egress control. Fail-closed pairing on both sides: the opt-in without a proxy, or any value other than 'true', is fatal. Adds regression coverage for the IP CONNECT request line (including IPv6 bracketing and hostname non-leakage), the hostname opt-in, and the config pairing rules in driver and supervisor. Signed-off-by: Philippe Martin * fix(sandbox,podman): reject empty port after bracketed IPv6 proxy host http://[fd00::1]: passed the explicit-port check because the bracketed branch only tested for a colon after the bracket, then fell back to port 80 — violating the fail-closed http://host:port contract and potentially sending configured Basic credentials to an unintended service. Require a non-empty suffix after ]:, matching the unbracketed branch, and cover the case in the shared parser tests. Signed-off-by: Philippe Martin * fix(sandbox,podman): fall back across validated addresses in proxied CONNECT The direct path hands TcpStream::connect the whole validated address list and it falls back across them, but the validated-IP CONNECT path attempted only the first address, so a dual-stack destination could fail through the corporate proxy even when a later validated address was reachable. connect_via_validated tries each validated address in order under one aggregate CONNECT_HANDSHAKE_TIMEOUT budget, returning the first success; when every attempt fails the error names the attempt count and carries the last failure. An empty address list is rejected up front. Adds regressions for first-fails/second-succeeds fallback (asserting both CONNECT request lines), the aggregate all-addresses failure message, and the empty-list rejection. Signed-off-by: Philippe Martin * fix(sandbox,podman): strip new reserved proxy vars and complete docs/tests Follow-ups from review: - Add OPENSHELL_UPSTREAM_PROXY_AUTH_ALLOW_INSECURE and OPENSHELL_UPSTREAM_PROXY_CONNECT_BY_HOSTNAME to the supervisor-only strip list so workload child processes never inherit them, matching the documented contract for the other reserved proxy variables, and cover both in the supervisor-only variable test. - Document all five OPENSHELL_SANDBOX_* proxy variables in the mise run gateway help text, marked Podman-only and stating the auth-file/acknowledgement pairing, and complete the gateway-key list in the Podman README. - Add NO_PROXY composition coverage for bracketed IPv6 entries with port qualifiers, bare IPv6 entries, and IPv6 CIDR matching against an IPv6-literal host and against a hostname's resolved addresses, including the port-qualified CIDR form. Signed-off-by: Philippe Martin * fix(sandbox,podman): cap each proxied CONNECT attempt within the shared budget A proxy that accepted the first CONNECT request but never responded consumed the entire aggregate handshake timeout, so later validated addresses were never tried and the hang defeated the multi-address fallback. Each attempt is now time-boxed to its fair share of the time remaining before the shared deadline (remaining / attempts_left): a hanging attempt is cut off with enough budget left for every remaining address, while time a fast failure does not use rolls over to later attempts and the total never exceeds CONNECT_HANDSHAKE_TIMEOUT. A timed-out attempt is recorded like any other failure, and the aggregate error distinguishes all-attempted from budget-exhausted runs. Adds a first-hangs/second-succeeds regression driven through a test-visible budget parameter so it runs in about a second instead of a real 30s window. Signed-off-by: Philippe Martin * fix(sandbox,podman): deliver corporate proxy config on the supervisor argv The proxy settings were injected as reserved OPENSHELL_UPSTREAM_* container environment variables. The driver only wrote names the operator configured, but container runtimes layer the spec environment over ENV values baked into the sandbox image, so an image could supply NO_PROXY=*, enable hostname CONNECT, or point an unconfigured deployment at an attacker-controlled proxy whenever the operator left a field unset. The settings now travel as supervisor command-line arguments (--upstream-proxy, --upstream-no-proxy, --upstream-proxy-auth-file, --upstream-proxy-auth-allow-insecure, --upstream-proxy-connect-by-hostname) built by the driver from operator config. The driver sets the container entrypoint and command explicitly, so neither sandbox spec/template environment nor image ENV can influence argv, and an omitted flag genuinely means unconfigured — in every supervisor topology, since the supervisor no longer consults its environment for these settings at all. Credentials stay on the root-only secret mount; only the mount path appears on argv. The reserved environment names, their strip-list entries, and the env-based validation surface are removed. UpstreamProxyConfig::from_args replaces from_env, reusing the same shared fail-closed validation and pairing rules keyed by the CLI flag names. Driver tests now assert the argv contract, including that sandbox-supplied environment cannot add, remove, or redirect proxy flags; supervisor tests cover from_args mapping and its pairing rules. Signed-off-by: Philippe Martin * docs(sandbox): align proxy comments with the argv transport The argv migration left comments describing the configuration as reserved environment variables ("reserved value", "present-but-empty variable", "reserved upstream proxy variables"). Rephrase them as driver-supplied arguments and operator settings so the documented trust boundary matches the implementation. Comment-only change. Signed-off-by: Philippe Martin * fix(sandbox): parse bracketed IPv6 authorities in client CONNECT targets parse_target split the CONNECT authority at the first colon, so an IPv6-literal target like [2001:db8::1]:443 always failed port parsing and IPv6-literal clients could never reach policy evaluation; a regression test even locked in that failure. Parse the RFC 3986 bracketed form and return the host bracket-free, matching what DNS resolution, SSRF validation, NO_PROXY matching, and the upstream CONNECT builder expect. Unclosed brackets, a missing or empty port after the bracket, and non-numeric ports are rejected; unbracketed behavior is unchanged. Replaces the failure-locking test with success coverage for bracketed targets and adds malformed-bracket rejection cases. Signed-off-by: Philippe Martin * test(podman): cover proxy-auth secret cleanup across lifecycle failures The per-sandbox proxy-auth credential secret is staged before the container is created and removed on cleanup, but no test proved the cleanup paths actually issue the secret removal. Add Podman-stub tests that drive create_sandbox to a container-create failure and to a start failure, and delete_sandbox for an out-of-band deletion, asserting each path issues the DELETE for the per-sandbox proxy-auth secret so a credential can never outlive the sandbox that owned it. Signed-off-by: Philippe Martin * docs: list corporate proxy keys in the Podman compute-driver overview The Fern Podman driver section enumerated its gateway.toml keys but omitted the corporate egress proxy settings. Add https_proxy, no_proxy, proxy_auth_file, proxy_auth_allow_insecure, and proxy_connect_by_hostname with a pointer to the gateway configuration reference for the full contract. No navigation change: the reference folder already includes the gateway configuration page. Signed-off-by: Philippe Martin * test(sandbox): cover the SSRF-to-TLS composition across the proxy tunnel Existing tests exercised validated-IP CONNECT and the upstream-TLS helper independently, but not the full boundary. Add an end-to-end regression that stands up a fake corporate proxy tunneling to a fake TLS server and drives the real path: connect_via_validated CONNECTs to the validated address, the proxy splices the tunnel, and tls_connect_upstream verifies the upstream certificate against the original hostname carried in SNI. It asserts the CONNECT authority is the validated IP and never the hostname, that verification succeeds for the matching hostname, and that a mismatched hostname is rejected — proving a rebinding or split-horizon substitution behind the proxy cannot pass certificate verification. Signed-off-by: Philippe Martin * fix(sandbox,podman): bound proxy-auth reads, reject port 0, fix stale comment Three review findings: - CWE-400: the proxy-auth credential file was read with an unbounded read_to_string on both the driver (sandbox-create) and supervisor (startup) paths, so a huge file or a special file such as /dev/zero could exhaust memory. Add a shared bounded reader in openshell-core that rejects non-regular files, caps the size at 4 KiB, and reads at most that many bytes; the driver runs it via spawn_blocking. Covers oversized, special-file, and missing-path cases on both sides. - Reject an upstream proxy URL with port 0: it passed the explicit-port check and startup validation but is not a connectable TCP port, so every proxied dial would fail later. Add a typed ZeroPort error with shared-validator and Podman-config tests. - Reword a driver-config comment that still described a 'reserved variable' to match the argv transport. Signed-off-by: Philippe Martin * fix(sandbox): open proxy-auth file non-blocking to reject FIFOs promptly read_upstream_proxy_credential_file opened the path with a blocking File::open before the regular-file check, so a configured FIFO with no writer would block open() indefinitely — hanging sandbox creation on the driver and supervisor startup. Open with O_NONBLOCK on Unix so the open returns immediately, then reject the non-regular file as before; O_NONBLOCK has no effect on the later read of a regular file. Adds a mkfifo regression asserting the reader returns promptly with a non-regular-file error instead of hanging. Signed-off-by: Philippe Martin * test(podman): cover corporate proxy egress across driver and supervisor The existing corporate-proxy tests construct config structs or call CONNECT helpers directly, so none of them detect a break in the wiring between layers: gateway TOML deserialization, the Podman argv and secret-mount semantics, supervisor CLI parsing, or policy denial before proxy contact. Add a Podman e2e that drives the whole chain against a fake authenticated forward proxy and asserts that an approved TLS request traverses it with a validated-IP CONNECT, a policy-denied destination is refused with 403 without ever reaching the proxy, credentials arrive through the mounted per-sandbox secret, and deleting the sandbox removes that secret. SupportContainer is a new harness fixture. Unlike ContainerHttpServer it probes readiness with a TCP connect rather than an HTTP GET, so it can host a forward proxy and TLS servers, and it exposes container logs and network IP for assertions. Signed-off-by: Philippe Martin * test(podman): restart the gateway on the proxy-config panic path The panic cleanup for the temporary corporate proxy configuration restored the gateway TOML but left the gateway process running with the temporary configuration still loaded, which could poison later test binaries in the same run. Nothing restarted it: the only ManagedGateway is the short-lived one inside restart_gateway, and its Drop only calls start, which does not reload config for an already-running gateway. Restore and synchronously stop/start the gateway in Drop, and set restored only after the normal restore and restart both succeed so a failed restart no longer suppresses the fallback. Signed-off-by: Philippe Martin * fix(supervisor-network): derive the loopback proxy bypass from resolved IPs The automatic bypass treated the host string "localhost" as proof that the destination was loopback and returned every resolved address. A sandbox controls its own /etc/hosts and resolve_socket_addrs consults it before DNS, so a workload could map localhost to any policy-allowed address and dial it directly, escaping the operator proxy and the inspection and audit boundary it exists to provide. Check the resolved addresses instead: the name bypasses only when the resolution is non-empty and every address is loopback. A mixed answer is not partially honored, and an IP literal is still authoritative for itself. A spoofed localhost falls through to the entries below, so an explicit operator NO_PROXY entry is still honored. This matches the trust model detect_trusted_host_gateway already applies to the same hosts file, which validates the mapped address rather than the alias. Signed-off-by: Philippe Martin * fix(podman): clean up proxy-auth secret when container already deleted The delete_sandbox early-return path cleaned up the token secret but skipped the proxy-auth secret, leaking it on disk. Also update tests for recent API changes (Optional socket_path, workspace field, list-based container lookup). Signed-off-by: Philippe Martin Signed-off-by: Philippe Martin --------- Signed-off-by: Philippe Martin Signed-off-by: Philippe Martin --- Cargo.lock | 1 + architecture/sandbox.md | 64 + crates/openshell-core/Cargo.toml | 3 + crates/openshell-core/src/driver_utils.rs | 510 +++++ crates/openshell-core/src/sandbox_env.rs | 5 + crates/openshell-driver-podman/README.md | 32 + crates/openshell-driver-podman/src/config.rs | 354 ++++ .../openshell-driver-podman/src/container.rs | 307 ++- crates/openshell-driver-podman/src/driver.rs | 262 ++- crates/openshell-driver-podman/src/main.rs | 35 + crates/openshell-sandbox/src/lib.rs | 2 + crates/openshell-sandbox/src/main.rs | 38 + .../src/l7/tls.rs | 2 +- .../openshell-supervisor-network/src/lib.rs | 1 + .../openshell-supervisor-network/src/proxy.rs | 168 +- .../openshell-supervisor-network/src/run.rs | 2 + .../src/upstream_proxy.rs | 1877 +++++++++++++++++ docs/reference/gateway-config.mdx | 60 + docs/reference/sandbox-compute-drivers.mdx | 2 + e2e/rust/Cargo.toml | 5 + e2e/rust/src/harness/container.rs | 143 ++ e2e/rust/tests/podman_corporate_proxy.rs | 594 ++++++ tasks/scripts/gateway.sh | 75 + 23 files changed, 4499 insertions(+), 43 deletions(-) create mode 100644 crates/openshell-supervisor-network/src/upstream_proxy.rs create mode 100644 e2e/rust/tests/podman_corporate_proxy.rs diff --git a/Cargo.lock b/Cargo.lock index 21c81cc945..04fae9937d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3890,6 +3890,7 @@ dependencies = [ "glob", "ipnet", "miette", + "nix", "prost", "prost-types", "protobuf-src", diff --git a/architecture/sandbox.md b/architecture/sandbox.md index bfb1c14741..4f95e1ef69 100644 --- a/architecture/sandbox.md +++ b/architecture/sandbox.md @@ -106,6 +106,70 @@ handled by the inference interception path: External inference endpoints that do not use `inference.local` are treated like ordinary network traffic and must be allowed by policy. +In proxy-required networks, the supervisor chains upstream TLS tunnels through +a corporate forward proxy with HTTP CONNECT instead of connecting directly, +once policy and SSRF checks pass. Only TLS (CONNECT) egress is chained: +plain-HTTP requests always dial the destination directly, because forwarding +plain HTTP through a proxy requires absolute-form request forwarding rather +than CONNECT tunneling and is out of scope. The proxy configuration is an +operator-owned boundary delivered on the supervisor's command line +(`--upstream-proxy` and friends) by the compute driver; sandbox and template +environment — and `ENV` values baked into the sandbox image — cannot +influence it, since none of these can alter the argv the driver sets. The +conventional `HTTPS_PROXY`/`HTTP_PROXY`/`NO_PROXY` variables a sandbox +controls are ignored on this path. Operator `NO_PROXY` destinations and +loopback always dial directly; add driver-injected host aliases (e.g. +`host.containers.internal`) to the operator `NO_PROXY` list when the corporate +proxy cannot reach the container host. `NO_PROXY` matching is port-aware and +resolution-aware: an entry with a `:port` qualifier only bypasses that port, +and IP/CIDR entries also match hostnames through their validated resolved +addresses, with the direct dial limited to the addresses the entry contains. Only `http://` proxy URLs in explicit +`http://host:port` form are supported — the scheme and port are both +required, and a path, query, or fragment is rejected. Local DNS resolution +and SSRF validation still run before the proxied dial, and the CONNECT +target sent to the corporate proxy is a validated resolved address, so the +proxy performs no DNS resolution of its own and the tunnel stays bound to +the answer that passed SSRF and `allowed_ips` validation. The hostname still +travels inside the tunnel (TLS SNI, application `Host`). In split-horizon +networks, point the gateway host at the corporate resolver so internal names +validate to their internal addresses; the `proxy_connect_by_hostname` +opt-in exists as a +last resort for proxies whose ACLs filter on hostnames and reject IP CONNECT +targets — with it, the proxy resolves the name itself and its ACLs become +the effective egress control for proxied TLS. (Resolving through the proxy's +own DNS view, e.g. DoH tunneled via CONNECT, is a possible future +enhancement and out of scope.) The workload child's proxy variables are +unaffected — they are always rewritten to point at the local policy proxy. + +The configuration is fail-closed: a setting that is present but invalid — an +empty value, an unsupported or malformed proxy URL, an unreadable auth file, +a malformed credential, or an auth file or `NO_PROXY` list set while no proxy +URL is configured — is fatal to supervisor startup instead of being treated +as unset, so a misconfiguration can never silently degrade to direct dialing +or unauthenticated proxy access. Only an omitted argument means "no proxy". +The driver validates the same rules at sandbox-create time through +validators shared with the supervisor +(`openshell_core::driver_utils::parse_upstream_proxy_url` and +`parse_upstream_proxy_credential`). + +Proxy credentials are never embedded in the URL: an inline `user:pass@` is +rejected because it would be stored in `gateway.toml` and exposed in container +metadata. Operators supply credentials via `proxy_auth_file`; the driver +stages them as a root-only secret mounted at a fixed path and passes only +that path on the supervisor's command line. The supervisor reads the +file and builds the `Proxy-Authorization: Basic` header; a credential that is +empty, contains control characters, or is not in `user:pass` form is fatal on +both sides. + +The Basic header travels over the plain-TCP connection to the `http://` proxy, +so it is readable on the network path between sandbox host and proxy. +Configuring `proxy_auth_file` therefore requires the explicit opt-in +`proxy_auth_allow_insecure = true`. Both the +driver (at sandbox-create time) and the supervisor (at startup) reject an +auth file without the acknowledgement, and the acknowledgement without an +auth file, so credentials are never sent in cleartext without an explicit +operator decision. + ## Credentials Provider credentials are stored at the gateway and fetched by the supervisor at diff --git a/crates/openshell-core/Cargo.toml b/crates/openshell-core/Cargo.toml index 495d069b68..35a3732cf9 100644 --- a/crates/openshell-core/Cargo.toml +++ b/crates/openshell-core/Cargo.toml @@ -28,6 +28,9 @@ base64 = { workspace = true } chrono = { version = "0.4", default-features = false, features = ["clock", "std"], optional = true } reqwest = { workspace = true, features = ["blocking", "rustls-tls-webpki-roots"], optional = true } +[target.'cfg(unix)'.dependencies] +nix = { workspace = true } + [features] default = ["telemetry"] ## Compile in anonymous telemetry emission support. On by default; disable with diff --git a/crates/openshell-core/src/driver_utils.rs b/crates/openshell-core/src/driver_utils.rs index 8a7d177ba3..a5bcc55ad3 100644 --- a/crates/openshell-core/src/driver_utils.rs +++ b/crates/openshell-core/src/driver_utils.rs @@ -82,6 +82,293 @@ pub const TLS_KEY_MOUNT_PATH: &str = "/etc/openshell/tls/client/tls.key"; /// Container-side mount path for the per-sandbox JWT token. pub const SANDBOX_TOKEN_MOUNT_PATH: &str = "/etc/openshell/auth/sandbox.jwt"; +/// Container-side mount path for the corporate upstream-proxy credentials. +/// +/// The file holds the `user:pass` userinfo used to build the +/// `Proxy-Authorization` header. It is delivered through a root-only secret +/// mount so the credential never appears in container environment/metadata. +pub const UPSTREAM_PROXY_AUTH_MOUNT_PATH: &str = "/etc/openshell/auth/upstream-proxy"; + +/// A validated corporate upstream-proxy address. +/// +/// Produced by [`parse_upstream_proxy_url`], which is the single source of +/// truth for what counts as a valid upstream proxy URL. Compute drivers use +/// it to reject bad operator config at sandbox-create time, and the +/// in-container supervisor applies the same rules to its driver-supplied +/// arguments so a value one side accepts is never rejected (or silently +/// ignored) by the other. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct UpstreamProxyAddr { + /// Proxy hostname, IPv4, or IPv6 address (IPv6 without brackets). + pub host: String, + /// Proxy TCP port (always explicit in the accepted URL grammar). + pub port: u16, +} + +/// Why an upstream proxy URL was rejected by [`parse_upstream_proxy_url`]. +/// +/// Kept as a typed error so each consumer (driver config validation, +/// supervisor startup) can phrase the message for its own surface while +/// enforcing identical semantics. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum UpstreamProxyUrlError { + /// The value is empty or whitespace-only. + #[error("proxy URL is empty")] + Empty, + /// The value does not parse as a URL. + #[error("not a valid proxy URL: {0}")] + Invalid(url::ParseError), + /// The value has no `scheme://` prefix. Bare `host[:port]` forms are + /// rejected so the accepted grammar matches the documented + /// `http://host:port` contract exactly. + #[error("proxy URL must include an explicit scheme, e.g. http://proxy.corp.com:3128")] + MissingScheme, + /// The URL uses a scheme other than `http` (TLS and SOCKS proxies are + /// not supported by the sandbox supervisor). + #[error( + "unsupported proxy scheme '{0}': only http:// forward proxies are \ + supported by the sandbox supervisor" + )] + UnsupportedScheme(String), + /// The URL has no explicit port. Corporate proxies rarely listen on the + /// scheme default (80), so a forgotten port is rejected instead of + /// silently dialing port 80. + #[error("proxy URL must include an explicit proxy port, e.g. http://proxy.corp.com:3128")] + MissingPort, + /// The URL specifies port `0`, which is not a connectable TCP port. It + /// would pass startup validation but fail every proxied dial, so it is + /// rejected up front. + #[error("proxy URL port must not be 0")] + ZeroPort, + /// The URL embeds `user:pass@` credentials, which would leak into config + /// and container metadata. Credentials must come from the proxy auth file. + #[error("proxy URL must not embed credentials; supply them via the proxy auth file")] + InlineCredentials, + /// The URL has no host component. + #[error("proxy URL is missing a proxy host")] + MissingHost, + /// The URL carries a path, query, or fragment. A forward proxy is + /// addressed by `host:port` only, so extra components indicate a + /// misconfiguration (e.g. a pasted endpoint URL) and are rejected instead + /// of being silently discarded. + #[error("proxy URL must not contain a {0}; use scheme://host:port only")] + UnexpectedComponent(&'static str), +} + +/// Parse and validate a corporate upstream-proxy URL. +/// +/// The accepted grammar is exactly `http://host:port`: the scheme and the +/// port must both be explicit, only `http://` proxies are accepted, and +/// inline userinfo is rejected. The URL must address the proxy only: a path +/// (other than a bare trailing `/`), query, or fragment is rejected rather +/// than silently discarded. +/// +/// # Errors +/// +/// Returns an [`UpstreamProxyUrlError`] describing the first rule the value +/// violates. +pub fn parse_upstream_proxy_url(raw: &str) -> Result { + let trimmed = raw.trim(); + if trimmed.is_empty() { + return Err(UpstreamProxyUrlError::Empty); + } + if !trimmed.contains("://") { + return Err(UpstreamProxyUrlError::MissingScheme); + } + let parsed = url::Url::parse(trimmed).map_err(UpstreamProxyUrlError::Invalid)?; + + if !parsed.scheme().eq_ignore_ascii_case("http") { + return Err(UpstreamProxyUrlError::UnsupportedScheme( + parsed.scheme().to_string(), + )); + } + if !parsed.username().is_empty() || parsed.password().is_some() { + return Err(UpstreamProxyUrlError::InlineCredentials); + } + let host = match parsed.host() { + // `Host::Ipv6` renders without brackets, which is what socket + // connect APIs expect. + Some(url::Host::Ipv6(ip)) => ip.to_string(), + Some(host) => host.to_string(), + None => return Err(UpstreamProxyUrlError::MissingHost), + }; + if host.is_empty() { + return Err(UpstreamProxyUrlError::MissingHost); + } + // The `url` crate normalizes an absent path to "/" for http URLs, so a + // bare trailing slash is indistinguishable from no path and is accepted. + if !matches!(parsed.path(), "" | "/") { + return Err(UpstreamProxyUrlError::UnexpectedComponent("path")); + } + if parsed.query().is_some() { + return Err(UpstreamProxyUrlError::UnexpectedComponent("query")); + } + if parsed.fragment().is_some() { + return Err(UpstreamProxyUrlError::UnexpectedComponent("fragment")); + } + if !authority_has_explicit_port(trimmed) { + return Err(UpstreamProxyUrlError::MissingPort); + } + // Explicit-port presence was verified above; `port()` is `None` only + // when the URL spells out the scheme default (`:80`), which the url crate + // normalizes away. + let port = parsed.port().unwrap_or(80); + if port == 0 { + return Err(UpstreamProxyUrlError::ZeroPort); + } + Ok(UpstreamProxyAddr { host, port }) +} + +/// Return `true` when the raw URL's authority carries an explicit `:port`. +/// +/// The `url` crate normalizes a scheme-default port (`:80` for http) to +/// `None`, making it indistinguishable from an absent port in the parsed +/// form, so the raw authority must be inspected instead. +fn authority_has_explicit_port(raw: &str) -> bool { + let after_scheme = raw.split_once("://").map_or(raw, |(_, rest)| rest); + let authority_end = after_scheme + .find(['/', '?', '#']) + .unwrap_or(after_scheme.len()); + let authority = &after_scheme[..authority_end]; + // Userinfo is rejected by the caller, but strip it anyway so this check + // never misreads a `user:pass@` colon as a port. + let host_port = authority.rsplit_once('@').map_or(authority, |(_, hp)| hp); + host_port.rfind(']').map_or_else( + || { + host_port + .rsplit_once(':') + .is_some_and(|(_, port)| !port.is_empty()) + }, + // Bracketed IPv6 literal: a port can only follow the bracket, and a + // bare trailing `]:` is no more explicit than no port at all. + |end| { + host_port[end + 1..] + .strip_prefix(':') + .is_some_and(|port| !port.is_empty()) + }, + ) +} + +/// Why an upstream proxy credential was rejected by +/// [`parse_upstream_proxy_credential`]. +/// +/// Variants carry no payload so an error can never leak credential content +/// into logs or user-facing messages. +#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)] +pub enum UpstreamProxyCredentialError { + /// The credential is empty or whitespace-only. + #[error("credential is empty")] + Empty, + /// The credential contains control characters (CR, LF, NUL, tab, ...) + /// that could inject additional HTTP headers. + #[error("credential contains control characters")] + ControlCharacters, + /// The credential has no `:` separating user from password. + #[error("credential must use the user:pass form (missing ':')")] + MissingSeparator, + /// The credential has an empty user before the `:` separator. + #[error("credential must use the user:pass form (empty user)")] + EmptyUser, +} + +/// Validate a corporate upstream-proxy credential read from the proxy auth +/// file, returning the trimmed `user:pass` value. +/// +/// Single source of truth for what counts as a valid proxy credential: the +/// compute driver applies it at sandbox-create time (before staging the +/// secret) and the in-container supervisor applies it again before building +/// the `Proxy-Authorization: Basic` header, so a credential one side accepts +/// is never rejected by the other. +/// +/// Surrounding whitespace (including the conventional trailing newline) is +/// trimmed. The user part must be non-empty; the password may be empty and +/// may itself contain `:` (per RFC 7617 the first `:` is the separator). +/// +/// # Errors +/// +/// Returns an [`UpstreamProxyCredentialError`] describing the first rule the +/// value violates. Errors never contain the credential itself. +pub fn parse_upstream_proxy_credential(raw: &str) -> Result<&str, UpstreamProxyCredentialError> { + let credential = raw.trim(); + if credential.is_empty() { + return Err(UpstreamProxyCredentialError::Empty); + } + if credential.contains(|c: char| c.is_control()) { + return Err(UpstreamProxyCredentialError::ControlCharacters); + } + match credential.split_once(':') { + None => Err(UpstreamProxyCredentialError::MissingSeparator), + Some(("", _)) => Err(UpstreamProxyCredentialError::EmptyUser), + Some(_) => Ok(credential), + } +} + +/// Hard upper bound on the size of a proxy-auth credential file. +/// +/// A `user:pass` credential is tiny; this cap only exists to stop a hostile +/// or misconfigured path (a huge file, or a special file such as +/// `/dev/zero`) from exhausting memory during a bounded read. +pub const MAX_UPSTREAM_PROXY_CREDENTIAL_BYTES: u64 = 4096; + +/// Read a proxy-auth credential file with a hard size bound. +/// +/// Rejects non-regular files (e.g. `/dev/zero`, directories, FIFOs) and +/// files larger than [`MAX_UPSTREAM_PROXY_CREDENTIAL_BYTES`], and reads at +/// most that many bytes, so a hostile or misconfigured path cannot exhaust +/// gateway or supervisor memory. Returns the raw contents; callers pass the +/// result to [`parse_upstream_proxy_credential`]. +/// +/// Shared by the compute driver (at sandbox-create time) and the in-container +/// supervisor so both enforce the same bound. This is a blocking read; async +/// callers should wrap it (e.g. `tokio::task::spawn_blocking`). +/// +/// # Errors +/// +/// Returns a descriptive error (never containing file contents) when the path +/// cannot be opened or stat'd, is not a regular file, or exceeds the size +/// bound. +pub fn read_upstream_proxy_credential_file(path: &str) -> Result { + use std::io::Read as _; + + // On Unix, open non-blocking so a FIFO with no writer does not hang the + // open() call indefinitely; the regular-file check below then rejects it. + // O_NONBLOCK has no effect on the subsequent read of a regular file. + #[cfg(unix)] + let open_result = { + use std::os::unix::fs::OpenOptionsExt as _; + std::fs::OpenOptions::new() + .read(true) + .custom_flags(nix::libc::O_NONBLOCK) + .open(path) + }; + #[cfg(not(unix))] + let open_result = std::fs::File::open(path); + + let file = open_result.map_err(|e| format!("failed to open proxy auth file '{path}': {e}"))?; + let metadata = file + .metadata() + .map_err(|e| format!("failed to stat proxy auth file '{path}': {e}"))?; + if !metadata.is_file() { + return Err(format!("proxy auth file '{path}' is not a regular file")); + } + if metadata.len() > MAX_UPSTREAM_PROXY_CREDENTIAL_BYTES { + return Err(format!( + "proxy auth file '{path}' exceeds the {MAX_UPSTREAM_PROXY_CREDENTIAL_BYTES}-byte limit" + )); + } + // Bound the read even if the file grows between stat and read. + let mut buf = String::new(); + file.take(MAX_UPSTREAM_PROXY_CREDENTIAL_BYTES + 1) + .read_to_string(&mut buf) + .map_err(|e| format!("failed to read proxy auth file '{path}': {e}"))?; + if buf.len() as u64 > MAX_UPSTREAM_PROXY_CREDENTIAL_BYTES { + return Err(format!( + "proxy auth file '{path}' exceeds the {MAX_UPSTREAM_PROXY_CREDENTIAL_BYTES}-byte limit" + )); + } + Ok(buf) +} + /// Return the XDG state path for a driver's sandbox JWT token file. /// /// The resulting path is `$XDG_STATE_HOME/openshell/[/]//sandbox.jwt`. @@ -170,3 +457,226 @@ pub fn supervisor_image_tag(image: &str) -> Option<&str> { pub fn supervisor_image_should_refresh(image: &str) -> bool { matches!(supervisor_image_tag(image), Some("dev" | "latest")) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn upstream_proxy_url_accepts_http_with_port() { + let addr = parse_upstream_proxy_url("http://proxy.corp.com:8080").unwrap(); + assert_eq!(addr.host, "proxy.corp.com"); + assert_eq!(addr.port, 8080); + } + + #[test] + fn upstream_proxy_url_rejects_missing_scheme() { + for url in [ + "proxy.corp.com", + "proxy.corp.com:3128", + "user:pass@proxy.corp.com:8080", + ] { + assert_eq!( + parse_upstream_proxy_url(url), + Err(UpstreamProxyUrlError::MissingScheme), + "{url}" + ); + } + } + + #[test] + fn upstream_proxy_url_rejects_missing_port() { + for url in [ + "http://proxy.corp.com", + "http://proxy.corp.com/", + "http://proxy.corp.com:", + "http://[fd00::1]", + "http://[fd00::1]:", + ] { + assert_eq!( + parse_upstream_proxy_url(url), + Err(UpstreamProxyUrlError::MissingPort), + "{url}" + ); + } + // An explicit scheme-default port is accepted even though the url + // crate normalizes it away in the parsed form. + let addr = parse_upstream_proxy_url("http://proxy.corp.com:80").unwrap(); + assert_eq!(addr.port, 80); + } + + #[test] + fn upstream_proxy_url_rejects_zero_port() { + // Port 0 parses as an explicit port but is not connectable; reject it + // up front instead of failing every proxied dial later. + for url in ["http://proxy.corp.com:0", "http://[fd00::1]:0"] { + assert_eq!( + parse_upstream_proxy_url(url), + Err(UpstreamProxyUrlError::ZeroPort), + "{url}" + ); + } + } + + #[test] + fn upstream_proxy_url_ipv6_host_is_bracket_free() { + let addr = parse_upstream_proxy_url("http://[fd00::1]:8080").unwrap(); + assert_eq!(addr.host, "fd00::1"); + assert_eq!(addr.port, 8080); + } + + #[test] + fn upstream_proxy_url_rejects_tls_and_socks_schemes() { + for url in ["https://proxy:443", "socks5://proxy:1080"] { + assert!(matches!( + parse_upstream_proxy_url(url), + Err(UpstreamProxyUrlError::UnsupportedScheme(_)) + )); + } + } + + #[test] + fn upstream_proxy_url_rejects_inline_credentials() { + for url in ["http://user:pass@proxy:8080", "http://user@proxy:8080"] { + assert_eq!( + parse_upstream_proxy_url(url), + Err(UpstreamProxyUrlError::InlineCredentials) + ); + } + } + + #[test] + fn upstream_proxy_url_rejects_empty_and_invalid() { + assert_eq!( + parse_upstream_proxy_url(" "), + Err(UpstreamProxyUrlError::Empty) + ); + assert!(matches!( + parse_upstream_proxy_url("http://proxy:notaport"), + Err(UpstreamProxyUrlError::Invalid(_)) + )); + assert!(parse_upstream_proxy_url("http://").is_err()); + } + + #[test] + fn upstream_proxy_url_rejects_path_query_and_fragment() { + for (url, component) in [ + ("http://proxy.corp.com:8080/some/path", "path"), + ("http://proxy.corp.com:8080?x=1", "query"), + ("http://proxy.corp.com:8080/?x=1", "query"), + ("http://proxy.corp.com:8080#frag", "fragment"), + ] { + assert_eq!( + parse_upstream_proxy_url(url), + Err(UpstreamProxyUrlError::UnexpectedComponent(component)), + "{url}" + ); + } + // A bare trailing slash is URL normalization, not a real path. + let addr = parse_upstream_proxy_url("http://proxy.corp.com:8080/").unwrap(); + assert_eq!(addr.host, "proxy.corp.com"); + assert_eq!(addr.port, 8080); + } + + #[test] + fn upstream_proxy_credential_accepts_user_pass_and_trims() { + assert_eq!( + parse_upstream_proxy_credential("user:pass\n"), + Ok("user:pass") + ); + // The password may be empty and may contain further colons. + assert_eq!(parse_upstream_proxy_credential("user:"), Ok("user:")); + assert_eq!( + parse_upstream_proxy_credential("user:p@:ss"), + Ok("user:p@:ss") + ); + } + + #[test] + fn upstream_proxy_credential_rejects_empty() { + for raw in ["", " ", "\n"] { + assert_eq!( + parse_upstream_proxy_credential(raw), + Err(UpstreamProxyCredentialError::Empty) + ); + } + } + + #[test] + fn upstream_proxy_credential_rejects_control_characters() { + for raw in ["user:pa\r\nss", "user:pa\0ss", "user:pa\tss"] { + assert_eq!( + parse_upstream_proxy_credential(raw), + Err(UpstreamProxyCredentialError::ControlCharacters) + ); + } + } + + #[test] + fn upstream_proxy_credential_rejects_malformed_user_pass_form() { + assert_eq!( + parse_upstream_proxy_credential("userpass"), + Err(UpstreamProxyCredentialError::MissingSeparator) + ); + assert_eq!( + parse_upstream_proxy_credential(":pass"), + Err(UpstreamProxyCredentialError::EmptyUser) + ); + } + + #[test] + fn credential_file_reads_within_the_size_bound() { + let file = tempfile::NamedTempFile::new().unwrap(); + std::fs::write(file.path(), "user:pass\n").unwrap(); + let raw = read_upstream_proxy_credential_file(file.path().to_str().unwrap()).unwrap(); + assert_eq!(parse_upstream_proxy_credential(&raw), Ok("user:pass")); + } + + #[test] + fn credential_file_rejects_oversized_files() { + let file = tempfile::NamedTempFile::new().unwrap(); + let huge = vec![b'a'; usize::try_from(MAX_UPSTREAM_PROXY_CREDENTIAL_BYTES + 1).unwrap()]; + std::fs::write(file.path(), &huge).unwrap(); + let err = read_upstream_proxy_credential_file(file.path().to_str().unwrap()).unwrap_err(); + assert!(err.contains("limit"), "{err}"); + } + + #[test] + fn credential_file_rejects_non_regular_files() { + // A directory is a non-regular path; /dev/zero would be rejected the + // same way (not a regular file) without risking an unbounded read. + let dir = tempfile::tempdir().unwrap(); + let err = read_upstream_proxy_credential_file(dir.path().to_str().unwrap()).unwrap_err(); + assert!(err.contains("regular file"), "{err}"); + + if std::path::Path::new("/dev/zero").exists() { + let err = read_upstream_proxy_credential_file("/dev/zero").unwrap_err(); + assert!(err.contains("regular file"), "{err}"); + } + } + + #[test] + fn credential_file_missing_path_is_an_error() { + let err = read_upstream_proxy_credential_file("/nonexistent/proxy-auth").unwrap_err(); + assert!(err.contains("open proxy auth file"), "{err}"); + } + + #[cfg(unix)] + #[test] + fn credential_file_rejects_fifo_without_hanging() { + // A FIFO with no writer would block a blocking open() forever. The + // reader opens non-blocking and rejects the non-regular file, so it + // must return promptly even though nothing ever opens the write end. + let dir = tempfile::tempdir().unwrap(); + let fifo = dir.path().join("proxy-auth-fifo"); + nix::unistd::mkfifo(&fifo, nix::sys::stat::Mode::S_IRUSR).unwrap(); + + let start = std::time::Instant::now(); + let err = read_upstream_proxy_credential_file(fifo.to_str().unwrap()).unwrap_err(); + assert!(err.contains("regular file"), "{err}"); + assert!( + start.elapsed() < std::time::Duration::from_secs(5), + "reading a FIFO must not block" + ); + } +} diff --git a/crates/openshell-core/src/sandbox_env.rs b/crates/openshell-core/src/sandbox_env.rs index f066580636..f15ce34bb1 100644 --- a/crates/openshell-core/src/sandbox_env.rs +++ b/crates/openshell-core/src/sandbox_env.rs @@ -114,3 +114,8 @@ pub const SANDBOX_UID: &str = "OPENSHELL_SANDBOX_UID"; /// Used alongside UID for PVC init container `chown` operations and when the /// supervisor drops privileges to a group other than the UID's primary group. pub const SANDBOX_GID: &str = "OPENSHELL_SANDBOX_GID"; + +// The corporate upstream-proxy configuration deliberately has no reserved +// environment variables: it travels on the supervisor's argv +// (`--upstream-proxy` and friends), which a sandbox image cannot forge the +// way it could bake `ENV` values. diff --git a/crates/openshell-driver-podman/README.md b/crates/openshell-driver-podman/README.md index 6a58cdcd23..d068dfbc8f 100644 --- a/crates/openshell-driver-podman/README.md +++ b/crates/openshell-driver-podman/README.md @@ -345,6 +345,38 @@ Podman resources after out-of-band container removal or label drift. | `OPENSHELL_PODMAN_TLS_CA` | `--podman-tls-ca` | unset | Host path to the CA certificate mounted for sandbox mTLS. | | `OPENSHELL_PODMAN_TLS_CERT` | `--podman-tls-cert` | unset | Host path to the client certificate mounted for sandbox mTLS. | | `OPENSHELL_PODMAN_TLS_KEY` | `--podman-tls-key` | unset | Host path to the client private key mounted for sandbox mTLS. | +| `OPENSHELL_SANDBOX_HTTPS_PROXY` | `--sandbox-https-proxy` | unset | Corporate forward proxy URL for the supervisor's upstream TLS dials, chained with HTTP CONNECT. Only credential-free `http://host:port` URLs are supported (scheme and port required). Plain-HTTP requests always dial directly. | +| `OPENSHELL_SANDBOX_NO_PROXY` | `--sandbox-no-proxy` | unset | Comma-separated `NO_PROXY` list (hostnames, domain suffixes, IPs, CIDRs, each with an optional `:port` qualifier) dialed directly instead of through the corporate proxy. IP/CIDR entries also match hostnames through their validated DNS resolution. | +| `OPENSHELL_SANDBOX_PROXY_AUTH_FILE` | `--sandbox-proxy-auth-file` | unset | Path to a file containing the proxy credentials as `user:pass`. Staged as a root-only Podman secret so credentials never appear in config or container metadata. Requires the insecure-auth acknowledgement below. | +| `OPENSHELL_SANDBOX_PROXY_AUTH_ALLOW_INSECURE` | `--sandbox-proxy-auth-allow-insecure` | unset | Explicit acknowledgement (`true`) that the credential is sent as cleartext Basic auth over the plain-TCP connection to the `http://` proxy. Required when the auth file is set; rejected when it is not. | +| `OPENSHELL_SANDBOX_PROXY_CONNECT_BY_HOSTNAME` | `--sandbox-proxy-connect-by-hostname` | unset | Send the destination hostname in CONNECT requests instead of a validated IP. Last resort for proxies whose ACLs filter on hostnames: the proxy then resolves the name itself, so sandbox SSRF/`allowed_ips` validation no longer binds the connection. | + +Through the gateway, the same settings are the `https_proxy`, `no_proxy`, +`proxy_auth_file`, `proxy_auth_allow_insecure`, and +`proxy_connect_by_hostname` keys under `[openshell.drivers.podman]`; see +`docs/reference/gateway-config.mdx`. + +This is an operator-owned egress boundary: the driver passes the settings on +the supervisor's command line, so sandbox and template environment — and any +`ENV` baked into the sandbox image — cannot override them, and the +conventional `HTTPS_PROXY`/`HTTP_PROXY`/`NO_PROXY` variables a sandbox +controls do not steer it. Credentials must be supplied through +`proxy_auth_file`; an inline `user:pass@` in the URL is rejected at startup. + +Basic auth over an `http://` proxy is cleartext on the wire: anyone on the +network path between the sandbox host and the proxy can recover the +credential. Setting `proxy_auth_file` therefore requires +`proxy_auth_allow_insecure = true`; both the driver and the in-container +supervisor reject credentials without that explicit acknowledgement. + +CONNECT requests target a validated resolved IP by default, so the proxy +performs no DNS resolution and the tunnel stays bound to the address that +passed the sandbox's SSRF and `allowed_ips` checks; the hostname still +travels inside the tunnel (TLS SNI, application `Host`). In split-horizon +networks, point the gateway host at the corporate resolver. Set +`proxy_connect_by_hostname = true` only when the proxy's ACLs filter on +hostnames and reject IP CONNECT targets — it re-opens proxy-side DNS +resolution, making the proxy's ACLs the effective egress control. ## Rootless-Specific Adaptations diff --git a/crates/openshell-driver-podman/src/config.rs b/crates/openshell-driver-podman/src/config.rs index e9bd8619dc..ba193e8e1c 100644 --- a/crates/openshell-driver-podman/src/config.rs +++ b/crates/openshell-driver-podman/src/config.rs @@ -133,6 +133,57 @@ pub struct PodmanComputeConfig { /// Set to `0` to disable health checks entirely. /// Defaults to [`DEFAULT_HEALTH_CHECK_INTERVAL_SECS`] (10 seconds). pub health_check_interval_secs: u64, + /// Corporate forward proxy URL passed to the in-container supervisor + /// (e.g. `http://proxy.corp.com:8080`). + /// + /// The supervisor chains policy-approved TLS tunnels through this proxy + /// with HTTP CONNECT instead of dialing upstream destinations directly. + /// Only `http://` proxy URLs in explicit `http://host:port` form (scheme + /// and port required) are supported. This is an operator-owned egress + /// boundary delivered on the supervisor's command line, so + /// sandbox/template environment cannot override it, and the conventional + /// `HTTPS_PROXY` variables are not used. + pub https_proxy: Option, + /// Comma-separated `NO_PROXY` list passed alongside the proxy URL (e.g. + /// `*.svc.cluster.local,10.0.0.0/8`). Destinations matching an entry are + /// dialed directly instead of through the corporate proxy. Entries take + /// an optional `:port` qualifier that limits them to that destination + /// port, and IP/CIDR entries also match hostnames through their + /// validated DNS resolution. + pub no_proxy: Option, + /// Path (on the gateway host) to a file containing the corporate proxy + /// credentials as `user:pass`. + /// + /// Credentials must be supplied through this file, never embedded in the + /// proxy URL: an inline `user:pass@` in `https_proxy` is + /// rejected at startup because it would leak into `gateway.toml` and + /// container metadata. The gateway reads this file at sandbox-create time + /// and delivers it to the supervisor through a root-only secret mount. + pub proxy_auth_file: Option, + /// Explicit acknowledgement that proxy credentials are sent in cleartext. + /// + /// `Proxy-Authorization: Basic` is base64, not encryption, and the + /// connection to an `http://` corporate proxy is plain TCP, so anyone on + /// the network path between the sandbox host and the proxy can recover + /// the credential. Setting `proxy_auth_file` therefore requires + /// `proxy_auth_allow_insecure = true`; without it the configuration is + /// rejected at startup. Set it only when the path to the proxy is a + /// trusted network segment. + pub proxy_auth_allow_insecure: Option, + /// Send the destination *hostname* in CONNECT requests to the corporate + /// proxy instead of a validated IP. + /// + /// By default the supervisor CONNECTs to an address that already passed + /// SSRF and `allowed_ips` validation, so the proxy performs no DNS + /// resolution and the tunnel stays bound to the validated answer. Set + /// this to `true` only when the proxy's ACLs filter on hostnames and + /// reject IP CONNECT targets: the proxy then resolves the name itself, + /// so a name that resolves differently at the proxy (split-horizon DNS, + /// rebinding) can reach destinations the sandbox policy never approved, + /// and the proxy's own ACLs become the effective egress control. Prefer + /// pointing the gateway host at the corporate resolver so validated-IP + /// CONNECT works in split-horizon networks. + pub proxy_connect_by_hostname: Option, } pub const DEFAULT_HEALTH_CHECK_INTERVAL_SECS: u64 = 10; @@ -188,6 +239,94 @@ impl PodmanComputeConfig { Ok(()) } + /// Validate optional corporate proxy configuration. + /// + /// Shares validation semantics with the in-container supervisor through + /// [`openshell_core::driver_utils::parse_upstream_proxy_url`], so a value + /// accepted here can never be rejected by the supervisor at sandbox + /// startup (or vice versa). The supervisor only supports `http://` + /// forward proxies, so other schemes are rejected at config time instead + /// of failing inside every sandbox. Credentials must be supplied through + /// `proxy_auth_file`; an inline `user:pass@` in the URL is rejected + /// because it would otherwise be stored in `gateway.toml` and exposed in + /// container metadata. + pub fn validate_proxy_config(&self) -> Result<(), crate::client::PodmanApiError> { + use openshell_core::driver_utils::{UpstreamProxyUrlError, parse_upstream_proxy_url}; + if let Some(url) = &self.https_proxy { + parse_upstream_proxy_url(url).map_err(|err| { + crate::client::PodmanApiError::InvalidInput(match err { + UpstreamProxyUrlError::Empty => { + "https_proxy must not be empty when set".to_string() + } + UpstreamProxyUrlError::InlineCredentials => { + "https_proxy must not embed credentials in the URL; supply them via \ + proxy_auth_file so they are not stored in config or container metadata" + .to_string() + } + err => format!("https_proxy {err}"), + }) + })?; + } + + // The supervisor treats a present-but-empty driver-supplied argument + // as a fatal misconfiguration, so never accept (and later pass) one. + if let Some(list) = self.no_proxy.as_deref() { + if list.trim().is_empty() { + return Err(crate::client::PodmanApiError::InvalidInput( + "no_proxy must not be empty when set; omit it instead".to_string(), + )); + } + // A bypass list only makes sense relative to a proxy boundary. An + // operator who set one believed proxying was in effect, so accepting + // it while all egress dials directly would hide a fail-open state. + if self.https_proxy.is_none() { + return Err(crate::client::PodmanApiError::InvalidInput( + "no_proxy is set but no https_proxy is configured".to_string(), + )); + } + } + + if let Some(path) = self.proxy_auth_file.as_deref() { + if path.trim().is_empty() { + return Err(crate::client::PodmanApiError::InvalidInput( + "proxy_auth_file must not be empty when set".to_string(), + )); + } + if self.https_proxy.is_none() { + return Err(crate::client::PodmanApiError::InvalidInput( + "proxy_auth_file is set but no https_proxy is configured".to_string(), + )); + } + // Basic auth over the plain-TCP proxy connection is readable by + // anyone on the network path; sending it requires an explicit + // operator acknowledgement rather than being an implicit side + // effect of configuring credentials. + if self.proxy_auth_allow_insecure != Some(true) { + return Err(crate::client::PodmanApiError::InvalidInput( + "proxy_auth_file sends the credential as cleartext Basic auth over the \ + plain-TCP connection to the http:// proxy; set proxy_auth_allow_insecure \ + = true to accept that exposure, or remove proxy_auth_file" + .to_string(), + )); + } + } else if self.proxy_auth_allow_insecure.is_some() { + // The acknowledgement without credentials means the operator + // believed an auth file was configured; surface the mismatch. + return Err(crate::client::PodmanApiError::InvalidInput( + "proxy_auth_allow_insecure is set but no proxy_auth_file is configured".to_string(), + )); + } + + // The CONNECT-target mode only means something relative to a proxy + // boundary the operator believed was in effect. + if self.proxy_connect_by_hostname.is_some() && self.https_proxy.is_none() { + return Err(crate::client::PodmanApiError::InvalidInput( + "proxy_connect_by_hostname is set but no https_proxy is configured".to_string(), + )); + } + Ok(()) + } + /// Validate optional host gateway override. pub fn validate_host_gateway_ip(&self) -> Result<(), crate::client::PodmanApiError> { let trimmed = self.host_gateway_ip.trim(); @@ -235,6 +374,11 @@ impl Default for PodmanComputeConfig { sandbox_pids_limit: DEFAULT_SANDBOX_PIDS_LIMIT, enable_bind_mounts: false, health_check_interval_secs: DEFAULT_HEALTH_CHECK_INTERVAL_SECS, + https_proxy: None, + no_proxy: None, + proxy_auth_file: None, + proxy_auth_allow_insecure: None, + proxy_connect_by_hostname: None, } } } @@ -261,6 +405,12 @@ impl std::fmt::Debug for PodmanComputeConfig { "health_check_interval_secs", &self.health_check_interval_secs, ) + // Proxy URLs may embed credentials in userinfo; log presence only. + .field("https_proxy", &self.https_proxy.is_some()) + .field("no_proxy", &self.no_proxy) + .field("proxy_auth_file", &self.proxy_auth_file.is_some()) + .field("proxy_auth_allow_insecure", &self.proxy_auth_allow_insecure) + .field("proxy_connect_by_hostname", &self.proxy_connect_by_hostname) .finish() } } @@ -322,6 +472,210 @@ mod tests { assert!(err.to_string().contains("sandbox_pids_limit")); } + // ── Proxy config validation ─────────────────────────────────────── + + #[test] + fn validate_proxy_config_accepts_unset_and_http() { + assert!( + PodmanComputeConfig::default() + .validate_proxy_config() + .is_ok() + ); + let cfg = PodmanComputeConfig { + https_proxy: Some("http://proxy.corp.com:8080".to_string()), + no_proxy: Some("*.svc.cluster.local".to_string()), + ..PodmanComputeConfig::default() + }; + assert!(cfg.validate_proxy_config().is_ok()); + } + + #[test] + fn validate_proxy_config_rejects_non_http_schemes() { + for url in ["https://proxy:443", "socks5://proxy:1080"] { + let cfg = PodmanComputeConfig { + https_proxy: Some(url.to_string()), + ..PodmanComputeConfig::default() + }; + let err = cfg.validate_proxy_config().unwrap_err(); + assert!( + err.to_string().contains("unsupported proxy scheme"), + "{url}: {err}" + ); + } + } + + #[test] + fn validate_proxy_config_rejects_url_components() { + for url in [ + "http://proxy.corp.com:8080/path", + "http://proxy.corp.com:8080?x=1", + "http://proxy.corp.com:8080#frag", + ] { + let cfg = PodmanComputeConfig { + https_proxy: Some(url.to_string()), + ..PodmanComputeConfig::default() + }; + let err = cfg.validate_proxy_config().unwrap_err(); + assert!( + err.to_string().contains("scheme://host:port"), + "{url}: {err}" + ); + } + } + + #[test] + fn validate_proxy_config_rejects_zero_port() { + let cfg = PodmanComputeConfig { + https_proxy: Some("http://proxy.corp.com:0".to_string()), + ..PodmanComputeConfig::default() + }; + let err = cfg.validate_proxy_config().unwrap_err(); + assert!(err.to_string().contains("port must not be 0"), "{err}"); + } + + #[test] + fn validate_proxy_config_rejects_missing_scheme_or_port() { + // A scheme-less value (previously normalized to http://) and a + // port-less value (previously defaulted to 80) are both rejected so + // gateway.toml matches the documented http://host:port grammar. + for url in ["proxy.corp.com:8080", "http://proxy.corp.com"] { + let cfg = PodmanComputeConfig { + https_proxy: Some(url.to_string()), + ..PodmanComputeConfig::default() + }; + let err = cfg.validate_proxy_config().unwrap_err(); + assert!(err.to_string().contains("explicit"), "{url}: {err}"); + } + } + + #[test] + fn validate_proxy_config_rejects_empty_value() { + let cfg = PodmanComputeConfig { + https_proxy: Some(" ".to_string()), + ..PodmanComputeConfig::default() + }; + let err = cfg.validate_proxy_config().unwrap_err(); + assert!(err.to_string().contains("https_proxy"), "{err}"); + } + + #[test] + fn validate_proxy_config_rejects_empty_no_proxy() { + let cfg = PodmanComputeConfig { + https_proxy: Some("http://proxy.corp.com:8080".to_string()), + no_proxy: Some(" ".to_string()), + ..PodmanComputeConfig::default() + }; + let err = cfg.validate_proxy_config().unwrap_err(); + assert!(err.to_string().contains("no_proxy"), "{err}"); + } + + #[test] + fn validate_proxy_config_rejects_no_proxy_without_proxy() { + let cfg = PodmanComputeConfig { + no_proxy: Some("*.svc.cluster.local".to_string()), + ..PodmanComputeConfig::default() + }; + let err = cfg.validate_proxy_config().unwrap_err(); + assert!(err.to_string().contains("no_proxy"), "{err}"); + } + + #[test] + fn validate_proxy_config_rejects_inline_credentials() { + for url in [ + "http://user:pass@proxy.corp.com:8080", + "http://user@proxy.corp.com:8080", + ] { + let cfg = PodmanComputeConfig { + https_proxy: Some(url.to_string()), + ..PodmanComputeConfig::default() + }; + let err = cfg.validate_proxy_config().unwrap_err(); + assert!( + err.to_string().contains("proxy_auth_file"), + "{url} should be rejected and point at proxy_auth_file: {err}" + ); + } + } + + #[test] + fn validate_proxy_config_accepts_auth_file_with_proxy_and_acknowledgement() { + let cfg = PodmanComputeConfig { + https_proxy: Some("http://proxy.corp.com:8080".to_string()), + proxy_auth_file: Some("/etc/openshell/secrets/proxy-auth".to_string()), + proxy_auth_allow_insecure: Some(true), + ..PodmanComputeConfig::default() + }; + assert!(cfg.validate_proxy_config().is_ok()); + } + + #[test] + fn validate_proxy_config_rejects_auth_file_without_insecure_acknowledgement() { + // Basic auth over the plain-TCP proxy connection is readable on the + // network path; sending it must be an explicit operator decision. + for allow in [None, Some(false)] { + let cfg = PodmanComputeConfig { + https_proxy: Some("http://proxy.corp.com:8080".to_string()), + proxy_auth_file: Some("/etc/openshell/secrets/proxy-auth".to_string()), + proxy_auth_allow_insecure: allow, + ..PodmanComputeConfig::default() + }; + let err = cfg.validate_proxy_config().unwrap_err(); + assert!( + err.to_string().contains("proxy_auth_allow_insecure"), + "{allow:?}: {err}" + ); + assert!(err.to_string().contains("cleartext"), "{allow:?}: {err}"); + } + } + + #[test] + fn validate_proxy_config_accepts_connect_by_hostname_with_proxy() { + for by_hostname in [Some(true), Some(false)] { + let cfg = PodmanComputeConfig { + https_proxy: Some("http://proxy.corp.com:8080".to_string()), + proxy_connect_by_hostname: by_hostname, + ..PodmanComputeConfig::default() + }; + assert!(cfg.validate_proxy_config().is_ok(), "{by_hostname:?}"); + } + } + + #[test] + fn validate_proxy_config_rejects_connect_by_hostname_without_proxy() { + let cfg = PodmanComputeConfig { + proxy_connect_by_hostname: Some(true), + ..PodmanComputeConfig::default() + }; + let err = cfg.validate_proxy_config().unwrap_err(); + assert!(err.to_string().contains("no https_proxy"), "{err}"); + } + + #[test] + fn validate_proxy_config_rejects_acknowledgement_without_auth_file() { + for allow in [Some(true), Some(false)] { + let cfg = PodmanComputeConfig { + https_proxy: Some("http://proxy.corp.com:8080".to_string()), + proxy_auth_allow_insecure: allow, + ..PodmanComputeConfig::default() + }; + let err = cfg.validate_proxy_config().unwrap_err(); + assert!( + err.to_string().contains("no proxy_auth_file"), + "{allow:?}: {err}" + ); + } + } + + #[test] + fn validate_proxy_config_rejects_auth_file_without_proxy() { + let cfg = PodmanComputeConfig { + proxy_auth_file: Some("/etc/openshell/secrets/proxy-auth".to_string()), + ..PodmanComputeConfig::default() + }; + let err = cfg.validate_proxy_config().unwrap_err(); + assert!(err.to_string().contains("proxy_auth_file"), "{err}"); + } + // ── TLS config validation ───────────────────────────────────────── #[test] diff --git a/crates/openshell-driver-podman/src/container.rs b/crates/openshell-driver-podman/src/container.rs index 4ca2575d82..e417358c6e 100644 --- a/crates/openshell-driver-podman/src/container.rs +++ b/crates/openshell-driver-podman/src/container.rs @@ -53,12 +53,15 @@ const VOLUME_PREFIX: &str = "openshell-sandbox-"; /// Secret name prefix for per-sandbox gateway JWTs. const TOKEN_SECRET_PREFIX: &str = "openshell-token-"; +const PROXY_AUTH_SECRET_PREFIX: &str = "openshell-proxy-auth-"; /// Container-side mount paths for client TLS materials and the sandbox token. const TLS_CA_MOUNT_PATH: &str = openshell_core::driver_utils::TLS_CA_MOUNT_PATH; const TLS_CERT_MOUNT_PATH: &str = openshell_core::driver_utils::TLS_CERT_MOUNT_PATH; const TLS_KEY_MOUNT_PATH: &str = openshell_core::driver_utils::TLS_KEY_MOUNT_PATH; const SANDBOX_TOKEN_MOUNT_PATH: &str = openshell_core::driver_utils::SANDBOX_TOKEN_MOUNT_PATH; +const UPSTREAM_PROXY_AUTH_MOUNT_PATH: &str = + openshell_core::driver_utils::UPSTREAM_PROXY_AUTH_MOUNT_PATH; /// Directory inside sandbox containers where the supervisor binary is mounted. const SUPERVISOR_MOUNT_DIR: &str = openshell_core::driver_utils::SUPERVISOR_CONTAINER_DIR; @@ -162,6 +165,12 @@ pub fn token_secret_name(sandbox_id: &str) -> String { format!("{TOKEN_SECRET_PREFIX}{sandbox_id}") } +/// Build the per-sandbox Podman secret name for the corporate proxy credentials. +#[must_use] +pub fn proxy_auth_secret_name(sandbox_id: &str) -> String { + format!("{PROXY_AUTH_SECRET_PREFIX}{sandbox_id}") +} + /// Truncate a container ID to 12 characters (standard short form). #[must_use] pub fn short_id(id: &str) -> String { @@ -349,6 +358,41 @@ pub fn resolve_image<'a>(sandbox: &'a DriverSandbox, config: &'a PodmanComputeCo /// User-supplied vars are inserted first so that the required driver /// vars always win -- preventing spec/template overrides of security- /// critical values like `OPENSHELL_ENDPOINT` or `OPENSHELL_SANDBOX_ID`. +/// Build the corporate upstream-proxy command-line arguments passed to the +/// supervisor. +/// +/// This operator-owned egress boundary travels on argv, which sandbox +/// spec/template environment and image `ENV` cannot influence. Credentials +/// are never on argv — only the root-only mount path is passed; the +/// supervisor reads the secret from the mount. +fn upstream_proxy_cli_args(config: &PodmanComputeConfig) -> Vec { + let mut args = Vec::new(); + if let Some(url) = &config.https_proxy { + args.push("--upstream-proxy".to_string()); + args.push(url.clone()); + } + if let Some(list) = &config.no_proxy { + args.push("--upstream-no-proxy".to_string()); + args.push(list.clone()); + } + if config.proxy_auth_file.is_some() { + args.push("--upstream-proxy-auth-file".to_string()); + args.push(UPSTREAM_PROXY_AUTH_MOUNT_PATH.to_string()); + } + // Config validation guarantees the acknowledgement is `true` whenever an + // auth file is configured; the supervisor independently refuses + // credentials without it. + if config.proxy_auth_allow_insecure == Some(true) { + args.push("--upstream-proxy-auth-allow-insecure".to_string()); + } + // Absent means the default validated-IP CONNECT binding; only the + // explicit hostname opt-in is passed through. + if config.proxy_connect_by_hostname == Some(true) { + args.push("--upstream-proxy-connect-by-hostname".to_string()); + } + args +} + fn build_env( sandbox: &DriverSandbox, config: &PodmanComputeConfig, @@ -386,6 +430,12 @@ fn build_env( } // 2. Required driver vars (highest priority -- always overwrite). + + // The operator's corporate egress proxy settings are not environment + // variables: they travel on the supervisor's argv (see + // `upstream_proxy_cli_args`), which sandbox spec/template environment + // and image ENV cannot influence. + env.insert( openshell_core::sandbox_env::SANDBOX.into(), sandbox.name.clone(), @@ -900,7 +950,10 @@ pub fn build_container_spec_with_token_and_gpu_devices( // Without this, the container would run the entrypoint binary with // the supervisor path as an argument instead of executing it directly. entrypoint: vec![SUPERVISOR_BINARY_PATH.into()], - command: vec![], + // Operator-owned corporate proxy flags. The workload command is not + // part of argv (the supervisor takes it from the reserved command + // env var), so these flags are the whole command list. + command: upstream_proxy_cli_args(config), // Force the supervisor to run as root (UID 0). Sandbox images may // set a non-root USER directive (e.g. `USER sandbox`), but the // supervisor needs root to create network namespaces, set up the @@ -994,15 +1047,32 @@ pub fn build_container_spec_with_token_and_gpu_devices( }, resource_limits, secret_env: BTreeMap::new(), - secrets: token_secret_name.map_or_else(Vec::new, |source| { - vec![SecretMount { - source: source.to_string(), - target: SANDBOX_TOKEN_MOUNT_PATH.into(), - uid: 0, - gid: 0, - mode: 0o400, - }] - }), + secrets: { + let mut secrets = Vec::new(); + if let Some(source) = token_secret_name { + secrets.push(SecretMount { + source: source.to_string(), + target: SANDBOX_TOKEN_MOUNT_PATH.into(), + uid: 0, + gid: 0, + mode: 0o400, + }); + } + // Corporate proxy credentials, when configured, are mounted as a + // root-only secret. The driver creates a matching Podman secret + // (see `create_sandbox_proxy_auth_secret`) named deterministically + // from the sandbox id, so no name needs threading through here. + if config.proxy_auth_file.is_some() { + secrets.push(SecretMount { + source: proxy_auth_secret_name(&sandbox.id), + target: UPSTREAM_PROXY_AUTH_MOUNT_PATH.into(), + uid: 0, + gid: 0, + mode: 0o400, + }); + } + secrets + }, stop_timeout: config.stop_timeout_secs, // Inject stable host aliases into /etc/hosts so sandbox containers can // reach services on the host. `host.openshell.internal` is the driver- @@ -1650,6 +1720,125 @@ mod tests { ); } + /// Extract the container spec's supervisor argv (`command`) as strings. + fn spec_command(spec: &Value) -> Vec { + spec["command"] + .as_array() + .expect("command should be an array") + .iter() + .map(|v| { + v.as_str() + .expect("command arg should be a string") + .to_string() + }) + .collect() + } + + #[test] + fn container_spec_passes_operator_proxy_on_supervisor_argv() { + let sandbox = test_sandbox("test-id", "test-name"); + let mut config = test_config(); + config.https_proxy = Some("http://proxy.corp.com:8080".to_string()); + config.no_proxy = Some("*.svc.cluster.local,10.0.0.0/8".to_string()); + + let spec = build_container_spec(&sandbox, &config); + let command = spec_command(&spec); + + // Config travels on argv (the image cannot forge process arguments), + // as flag/value pairs. + let idx = command + .iter() + .position(|a| a == "--upstream-proxy") + .expect("proxy URL flag present"); + assert_eq!( + command.get(idx + 1).map(String::as_str), + Some("http://proxy.corp.com:8080") + ); + let idx = command + .iter() + .position(|a| a == "--upstream-no-proxy") + .expect("no_proxy flag present"); + assert_eq!( + command.get(idx + 1).map(String::as_str), + Some("*.svc.cluster.local,10.0.0.0/8") + ); + + // The proxy settings are argv-only; nothing about them lands in the + // environment, and the conventional proxy variables (which belong to + // the sandbox creator) are not touched by operator config. + let env_map = spec["env"].as_object().expect("env should be an object"); + for key in ["HTTPS_PROXY", "https_proxy", "HTTP_PROXY", "http_proxy"] { + assert!( + !env_map.contains_key(key), + "{key} must not be populated from operator proxy config" + ); + } + } + + #[test] + fn container_spec_omits_proxy_argv_when_unconfigured() { + let sandbox = test_sandbox("test-id", "test-name"); + let spec = build_container_spec(&sandbox, &test_config()); + let command = spec_command(&spec); + + assert!( + !command.iter().any(|a| a.starts_with("--upstream-proxy")), + "no proxy flags without operator proxy config: {command:?}" + ); + } + + #[test] + fn container_spec_sandbox_env_cannot_influence_proxy_argv() { + use openshell_core::proto::compute::v1::{DriverSandboxSpec, DriverSandboxTemplate}; + + // A sandbox creator tries to steer the egress boundary through spec + // and template environment (image-baked ENV behaves the same at the + // runtime layer). The supervisor takes proxy config only from the + // argv the driver builds out of operator config, so none of it has + // any effect. + let mut sandbox = test_sandbox("test-id", "test-name"); + sandbox.spec = Some(DriverSandboxSpec { + environment: std::collections::HashMap::from([ + ( + "HTTPS_PROXY".to_string(), + "http://attacker:9999".to_string(), + ), + ("NO_PROXY".to_string(), "*".to_string()), + ]), + template: Some(DriverSandboxTemplate { + environment: std::collections::HashMap::from([( + "NO_PROXY".to_string(), + "*".to_string(), + )]), + ..Default::default() + }), + ..Default::default() + }); + let mut config = test_config(); + config.https_proxy = Some("http://proxy.corp.com:8080".to_string()); + + let spec = build_container_spec(&sandbox, &config); + let command = spec_command(&spec); + + // Only the operator's proxy is delivered, and only on argv. + let idx = command + .iter() + .position(|a| a == "--upstream-proxy") + .expect("operator proxy flag present"); + assert_eq!( + command.get(idx + 1).map(String::as_str), + Some("http://proxy.corp.com:8080") + ); + assert!( + !command.iter().any(|a| a == "--upstream-no-proxy"), + "sandbox environment must not add a NO_PROXY bypass: {command:?}" + ); + assert!( + !command.iter().any(|a| a.contains("attacker")), + "attacker proxy must not reach argv: {command:?}" + ); + } + #[test] fn container_spec_required_labels_cannot_be_overridden() { use openshell_core::proto::compute::v1::{DriverSandboxSpec, DriverSandboxTemplate}; @@ -2390,6 +2579,104 @@ mod tests { ); } + #[test] + fn container_spec_proxy_auth_file_mounts_secret_and_sets_path_only() { + let sandbox = test_sandbox("proxy-id", "proxy-name"); + let mut config = test_config(); + config.https_proxy = Some("http://proxy.corp.com:8080".to_string()); + config.proxy_auth_file = Some("/etc/openshell/secrets/proxy-auth".to_string()); + config.proxy_auth_allow_insecure = Some(true); + + let spec = build_container_spec(&sandbox, &config); + let command = spec_command(&spec); + + // The supervisor gets only the mount *path* on argv, never the + // credential itself. + let idx = command + .iter() + .position(|a| a == "--upstream-proxy-auth-file") + .expect("auth-file flag present"); + assert_eq!( + command.get(idx + 1).map(String::as_str), + Some(UPSTREAM_PROXY_AUTH_MOUNT_PATH) + ); + // The cleartext-credential acknowledgement travels with the auth + // file so the supervisor's fail-closed pairing check passes. + assert!( + command + .iter() + .any(|a| a == "--upstream-proxy-auth-allow-insecure"), + "acknowledgement flag present: {command:?}" + ); + // The raw credential path from config never appears anywhere in the + // spec (only the fixed mount path does). + assert!( + !command + .iter() + .any(|a| a == "/etc/openshell/secrets/proxy-auth"), + "host-side credential path must not reach the container: {command:?}" + ); + + let secrets = spec["secrets"] + .as_array() + .expect("secrets should be an array"); + assert!( + secrets.iter().any(|secret| { + secret["source"].as_str() == Some(proxy_auth_secret_name(&sandbox.id).as_str()) + && secret["target"].as_str() == Some(UPSTREAM_PROXY_AUTH_MOUNT_PATH) + && secret["mode"].as_u64() == Some(0o400) + }), + "proxy credentials must be delivered through a root-only secret mount" + ); + } + + #[test] + fn container_spec_omits_proxy_auth_mount_when_unconfigured() { + let sandbox = test_sandbox("proxy-id", "proxy-name"); + let mut config = test_config(); + config.https_proxy = Some("http://proxy.corp.com:8080".to_string()); + + let spec = build_container_spec(&sandbox, &config); + let command = spec_command(&spec); + assert!( + !command.iter().any(|a| a == "--upstream-proxy-auth-file"), + "auth-file flag must be absent when no proxy_auth_file is configured: {command:?}" + ); + assert!( + !command + .iter() + .any(|a| a == "--upstream-proxy-auth-allow-insecure"), + "acknowledgement flag must be absent when no proxy_auth_file is configured: {command:?}" + ); + } + + #[test] + fn container_spec_connect_by_hostname_passed_only_on_opt_in() { + let sandbox = test_sandbox("proxy-id", "proxy-name"); + let mut config = test_config(); + config.https_proxy = Some("http://proxy.corp.com:8080".to_string()); + + // Default: no flag, the supervisor uses validated-IP CONNECT binding. + let spec = build_container_spec(&sandbox, &config); + let command = spec_command(&spec); + assert!( + !command + .iter() + .any(|a| a == "--upstream-proxy-connect-by-hostname"), + "hostname CONNECT must be absent without the operator opt-in: {command:?}" + ); + + config.proxy_connect_by_hostname = Some(true); + let spec = build_container_spec(&sandbox, &config); + let command = spec_command(&spec); + assert!( + command + .iter() + .any(|a| a == "--upstream-proxy-connect-by-hostname"), + "hostname CONNECT flag present on opt-in: {command:?}" + ); + } + #[test] fn container_spec_omits_tls_without_config() { let sandbox = test_sandbox("notls-id", "notls-name"); diff --git a/crates/openshell-driver-podman/src/driver.rs b/crates/openshell-driver-podman/src/driver.rs index c4d205c414..3878f59836 100644 --- a/crates/openshell-driver-podman/src/driver.rs +++ b/crates/openshell-driver-podman/src/driver.rs @@ -114,6 +114,57 @@ async fn cleanup_sandbox_token_secret(client: &PodmanClient, secret_name: &str) } } +/// Read the operator's proxy credentials file and stage it as a per-sandbox +/// Podman secret, so the credentials reach the supervisor through a root-only +/// mount rather than the container environment. +/// +/// Fails closed: when `proxy_auth_file` is configured but cannot be read or +/// does not hold a valid `user:pass` credential, the sandbox is not created. +/// Credential validation is shared with the in-container supervisor through +/// [`openshell_core::driver_utils::parse_upstream_proxy_credential`], so a +/// credential staged here can never be rejected at supervisor startup. +async fn create_sandbox_proxy_auth_secret( + client: &PodmanClient, + config: &PodmanComputeConfig, + sandbox: &DriverSandbox, +) -> Result, ComputeDriverError> { + let Some(path) = config.proxy_auth_file.as_deref() else { + return Ok(None); + }; + + // Bounded, blocking read shared with the supervisor: rejects non-regular + // files (e.g. /dev/zero) and caps the size so a hostile path cannot + // exhaust gateway memory. + let path_owned = path.to_string(); + let raw = tokio::task::spawn_blocking(move || { + openshell_core::driver_utils::read_upstream_proxy_credential_file(&path_owned) + }) + .await + .map_err(|e| ComputeDriverError::Message(format!("proxy_auth_file read task failed: {e}")))? + .map_err(ComputeDriverError::Message)?; + let credential = + openshell_core::driver_utils::parse_upstream_proxy_credential(&raw).map_err(|err| { + ComputeDriverError::InvalidArgument(format!("proxy_auth_file '{path}': {err}")) + })?; + + let secret_name = container::proxy_auth_secret_name(&sandbox.id); + client + .create_secret(&secret_name, format!("{credential}\n").as_bytes()) + .await + .map_err(ComputeDriverError::from)?; + Ok(Some(secret_name)) +} + +async fn cleanup_sandbox_proxy_auth_secret(client: &PodmanClient, secret_name: &str) { + if let Err(err) = client.remove_secret(secret_name).await { + warn!( + secret = %secret_name, + error = %err, + "Failed to remove Podman sandbox proxy-auth secret" + ); + } +} + fn local_podman_cdi_gpu_inventory_from(dev_root: &Path) -> CdiGpuInventory { let mut device_ids = std::fs::read_dir(dev_root) .ok() @@ -211,6 +262,7 @@ impl PodmanComputeDriver { config.validate_tls_config()?; config.validate_runtime_limits()?; config.validate_host_gateway_ip()?; + config.validate_proxy_config()?; let client = PodmanClient::new(socket_path); @@ -542,6 +594,29 @@ impl PodmanComputeDriver { return Err(e); } }; + let proxy_auth_secret_name = + match create_sandbox_proxy_auth_secret(&self.client, &self.config, sandbox).await { + Ok(name) => name, + Err(e) => { + let _ = self.client.remove_volume(&vol_name).await; + if let Some(secret) = token_secret_name.as_deref() { + cleanup_sandbox_token_secret(&self.client, secret).await; + } + return Err(e); + } + }; + + // Clean up the volume and both per-sandbox secrets on any failure past + // this point. + let cleanup_created = || async { + let _ = self.client.remove_volume(&vol_name).await; + if let Some(secret) = token_secret_name.as_deref() { + cleanup_sandbox_token_secret(&self.client, secret).await; + } + if let Some(secret) = proxy_auth_secret_name.as_deref() { + cleanup_sandbox_proxy_auth_secret(&self.client, secret).await; + } + }; // 3. Create container. let gpu_devices = match self.resolve_gpu_cdi_devices( @@ -551,10 +626,7 @@ impl PodmanComputeDriver { ) { Ok(devices) => devices, Err(e) => { - let _ = self.client.remove_volume(&vol_name).await; - if let Some(secret) = token_secret_name.as_deref() { - cleanup_sandbox_token_secret(&self.client, secret).await; - } + cleanup_created().await; return Err(e); } }; @@ -566,10 +638,7 @@ impl PodmanComputeDriver { ) { Ok(spec) => spec, Err(e) => { - let _ = self.client.remove_volume(&vol_name).await; - if let Some(secret) = token_secret_name.as_deref() { - cleanup_sandbox_token_secret(&self.client, secret).await; - } + cleanup_created().await; return Err(e); } }; @@ -580,17 +649,11 @@ impl PodmanComputeDriver { // sandbox's ID, not the conflicting container's ID (which // has the same name but a different ID), so it would be // orphaned otherwise. - let _ = self.client.remove_volume(&vol_name).await; - if let Some(secret) = token_secret_name.as_deref() { - cleanup_sandbox_token_secret(&self.client, secret).await; - } + cleanup_created().await; return Err(ComputeDriverError::AlreadyExists); } Err(e) => { - let _ = self.client.remove_volume(&vol_name).await; - if let Some(secret) = token_secret_name.as_deref() { - cleanup_sandbox_token_secret(&self.client, secret).await; - } + cleanup_created().await; return Err(ComputeDriverError::from(e)); } } @@ -603,10 +666,7 @@ impl PodmanComputeDriver { "Failed to start container; cleaning up" ); let _ = self.client.remove_container(&name).await; - let _ = self.client.remove_volume(&vol_name).await; - if let Some(secret) = token_secret_name.as_deref() { - cleanup_sandbox_token_secret(&self.client, secret).await; - } + cleanup_created().await; return Err(ComputeDriverError::from(e)); } @@ -662,6 +722,11 @@ impl PodmanComputeDriver { } cleanup_sandbox_token_secret(&self.client, &container::token_secret_name(sandbox_id)) .await; + cleanup_sandbox_proxy_auth_secret( + &self.client, + &container::proxy_auth_secret_name(sandbox_id), + ) + .await; return Ok(false); }; info!(sandbox_id = %sandbox_id, container = %container_id, "Deleting sandbox container"); @@ -689,6 +754,11 @@ impl PodmanComputeDriver { ); } cleanup_sandbox_token_secret(&self.client, &container::token_secret_name(sandbox_id)).await; + cleanup_sandbox_proxy_auth_secret( + &self.client, + &container::proxy_auth_secret_name(sandbox_id), + ) + .await; Ok(container_existed) } @@ -873,7 +943,7 @@ mod tests { }; use std::collections::HashMap; use std::fs; - use std::path::PathBuf; + use std::path::{Path, PathBuf}; // ── socket resolution ─────────────────────────────────────────────── // @@ -1533,6 +1603,156 @@ mod tests { let _ = fs::remove_file(socket_path); } + /// Write a valid `user:pass` credential to a unique path for proxy-auth + /// secret tests. Caller removes it. + fn write_proxy_auth_file(test_name: &str) -> PathBuf { + let path = crate::test_utils::unique_socket_path(test_name).with_extension("auth"); + fs::write(&path, "user:pass\n").expect("write proxy auth file"); + path + } + + fn proxy_auth_config(socket_path: PathBuf, auth_file: &Path) -> PodmanComputeConfig { + PodmanComputeConfig { + socket_path: Some(socket_path), + stop_timeout_secs: 10, + proxy_auth_file: Some(auth_file.to_string_lossy().into_owned()), + proxy_auth_allow_insecure: Some(true), + ..PodmanComputeConfig::default() + } + } + + fn plain_sandbox(id: &str, name: &str) -> DriverSandbox { + DriverSandbox { + id: id.to_string(), + name: name.to_string(), + namespace: String::new(), + workspace: String::new(), + spec: None, + status: None, + } + } + + fn secret_delete_request(sandbox_id: &str) -> String { + format!( + "DELETE {}", + api_path(&format!( + "/libpod/secrets/{}", + container::proxy_auth_secret_name(sandbox_id) + )) + ) + } + + #[tokio::test] + async fn create_sandbox_removes_proxy_auth_secret_on_container_create_failure() { + // A credential secret is staged before the container is created, so a + // container-create failure must remove it — no credential residue. + let sandbox_id = "sandbox-cc"; + let auth_file = write_proxy_auth_file("create-fail"); + let (socket_path, request_log, handle) = spawn_podman_stub( + "create-container-fail", + vec![ + StubResponse::new(StatusCode::OK, "{}"), // pull supervisor image + StubResponse::new(StatusCode::OK, "{}"), // pull sandbox image + StubResponse::new(StatusCode::CREATED, "{}"), // create volume + StubResponse::new(StatusCode::CREATED, "{}"), // create proxy-auth secret + StubResponse::new(StatusCode::INTERNAL_SERVER_ERROR, r#"{"message":"boom"}"#), // create container + StubResponse::new(StatusCode::NO_CONTENT, ""), // cleanup: remove volume + StubResponse::new(StatusCode::NO_CONTENT, ""), // cleanup: remove proxy-auth secret + ], + ); + let driver = test_driver_with_config(proxy_auth_config(socket_path.clone(), &auth_file)); + + driver + .create_sandbox(&plain_sandbox(sandbox_id, "demo")) + .await + .expect_err("container create should fail"); + + handle.await.expect("stub task should finish"); + let requests = request_log + .lock() + .expect("request log lock should not be poisoned") + .clone(); + assert!( + requests.contains(&secret_delete_request(sandbox_id)), + "proxy-auth secret must be removed on container-create failure: {requests:?}" + ); + let _ = fs::remove_file(&auth_file); + let _ = fs::remove_file(socket_path); + } + + #[tokio::test] + async fn create_sandbox_removes_proxy_auth_secret_on_start_failure() { + // The container is created but fails to start; the staged credential + // secret must still be removed. + let sandbox_id = "sandbox-sf"; + let auth_file = write_proxy_auth_file("start-fail"); + let (socket_path, request_log, handle) = spawn_podman_stub( + "create-start-fail", + vec![ + StubResponse::new(StatusCode::OK, "{}"), // pull supervisor image + StubResponse::new(StatusCode::OK, "{}"), // pull sandbox image + StubResponse::new(StatusCode::CREATED, "{}"), // create volume + StubResponse::new(StatusCode::CREATED, "{}"), // create proxy-auth secret + StubResponse::new(StatusCode::CREATED, "{}"), // create container + StubResponse::new(StatusCode::INTERNAL_SERVER_ERROR, r#"{"message":"boom"}"#), // start container + StubResponse::new(StatusCode::NO_CONTENT, ""), // cleanup: remove container + StubResponse::new(StatusCode::NO_CONTENT, ""), // cleanup: remove volume + StubResponse::new(StatusCode::NO_CONTENT, ""), // cleanup: remove proxy-auth secret + ], + ); + let driver = test_driver_with_config(proxy_auth_config(socket_path.clone(), &auth_file)); + + driver + .create_sandbox(&plain_sandbox(sandbox_id, "demo")) + .await + .expect_err("container start should fail"); + + handle.await.expect("stub task should finish"); + let requests = request_log + .lock() + .expect("request log lock should not be poisoned") + .clone(); + assert!( + requests.contains(&secret_delete_request(sandbox_id)), + "proxy-auth secret must be removed on start failure: {requests:?}" + ); + let _ = fs::remove_file(&auth_file); + let _ = fs::remove_file(socket_path); + } + + #[tokio::test] + async fn delete_sandbox_removes_proxy_auth_secret() { + // Deleting a sandbox (here already gone out of band) must remove the + // per-sandbox proxy-auth secret so credentials never outlive it. + let sandbox_id = "sandbox-del"; + let (socket_path, request_log, handle) = spawn_podman_stub( + "delete-proxy-auth", + vec![ + StubResponse::new(StatusCode::OK, "[]"), // list_containers (not found) + StubResponse::new(StatusCode::NO_CONTENT, ""), // remove volume + StubResponse::new(StatusCode::NO_CONTENT, ""), // remove token secret + StubResponse::new(StatusCode::NO_CONTENT, ""), // remove proxy-auth secret + ], + ); + let driver = test_driver(socket_path.clone()); + + driver + .delete_sandbox(sandbox_id) + .await + .expect("delete should succeed"); + + handle.await.expect("stub task should finish"); + let requests = request_log + .lock() + .expect("request log lock should not be poisoned") + .clone(); + assert!( + requests.contains(&secret_delete_request(sandbox_id)), + "proxy-auth secret must be removed on delete: {requests:?}" + ); + let _ = fs::remove_file(socket_path); + } + #[tokio::test] async fn delete_sandbox_finds_container_by_label_and_removes() { let sandbox_id = "sandbox-request-id"; diff --git a/crates/openshell-driver-podman/src/main.rs b/crates/openshell-driver-podman/src/main.rs index 831d338a30..35191e4cda 100644 --- a/crates/openshell-driver-podman/src/main.rs +++ b/crates/openshell-driver-podman/src/main.rs @@ -103,6 +103,36 @@ struct Args { /// Host path to the client private key for sandbox mTLS. #[arg(long, env = "OPENSHELL_PODMAN_TLS_KEY")] podman_tls_key: Option, + + /// Corporate forward proxy URL for the supervisor's upstream TLS dials, + /// in explicit `http://host:port` form (scheme and port required). + /// Credentials must not be embedded in the URL; use + /// `--sandbox-proxy-auth-file` instead. + #[arg(long, env = "OPENSHELL_SANDBOX_HTTPS_PROXY")] + sandbox_https_proxy: Option, + + /// Comma-separated `NO_PROXY` list injected alongside the proxy URL. + #[arg(long, env = "OPENSHELL_SANDBOX_NO_PROXY")] + sandbox_no_proxy: Option, + + /// Path to a file containing the corporate proxy credentials as + /// `user:pass`. Delivered to the supervisor through a root-only secret + /// mount so the credentials never appear in config or container metadata. + #[arg(long, env = "OPENSHELL_SANDBOX_PROXY_AUTH_FILE")] + sandbox_proxy_auth_file: Option, + + /// Explicit acknowledgement (`true`) that the proxy credential is sent + /// as cleartext Basic auth over the plain-TCP connection to the http:// + /// proxy. Required when `--sandbox-proxy-auth-file` is set. + #[arg(long, env = "OPENSHELL_SANDBOX_PROXY_AUTH_ALLOW_INSECURE")] + sandbox_proxy_auth_allow_insecure: Option, + + /// Send the destination hostname in CONNECT requests to the corporate + /// proxy instead of a validated IP. Only for proxies whose ACLs filter + /// on hostnames: the proxy then resolves the name itself, so sandbox + /// SSRF/`allowed_ips` validation no longer binds the connection. + #[arg(long, env = "OPENSHELL_SANDBOX_PROXY_CONNECT_BY_HOSTNAME")] + sandbox_proxy_connect_by_hostname: Option, } #[tokio::main] @@ -133,6 +163,11 @@ async fn main() -> Result<()> { guest_tls_cert: args.podman_tls_cert, guest_tls_key: args.podman_tls_key, sandbox_pids_limit: args.sandbox_pids_limit, + https_proxy: args.sandbox_https_proxy, + no_proxy: args.sandbox_no_proxy, + proxy_auth_file: args.sandbox_proxy_auth_file, + proxy_auth_allow_insecure: args.sandbox_proxy_auth_allow_insecure, + proxy_connect_by_hostname: args.sandbox_proxy_connect_by_hostname, ..PodmanComputeConfig::default() }) .await diff --git a/crates/openshell-sandbox/src/lib.rs b/crates/openshell-sandbox/src/lib.rs index 271f82710c..3a5c7b70ae 100644 --- a/crates/openshell-sandbox/src/lib.rs +++ b/crates/openshell-sandbox/src/lib.rs @@ -98,6 +98,7 @@ pub async fn run_sandbox( ocsf_enabled: Arc, network_enabled: bool, process_enabled: bool, + upstream_proxy_args: openshell_supervisor_network::upstream_proxy::UpstreamProxyArgs, ) -> Result { let (program, args) = command .split_first() @@ -388,6 +389,7 @@ pub async fn run_sandbox( activity_tx, agent_proposals.clone(), workspace_rx.clone(), + &upstream_proxy_args, ) .await?, ) diff --git a/crates/openshell-sandbox/src/main.rs b/crates/openshell-sandbox/src/main.rs index 71f881f68a..62ae37b5a1 100644 --- a/crates/openshell-sandbox/src/main.rs +++ b/crates/openshell-sandbox/src/main.rs @@ -101,6 +101,9 @@ impl std::str::FromStr for Mode { } /// `OpenShell` Sandbox - process isolation and monitoring. +// CLI flags are naturally boolean switches; grouping them into structs would +// only obscure the clap definition. +#[allow(clippy::struct_excessive_bools)] #[derive(Parser, Debug)] #[command(name = "openshell-sandbox")] #[command(version = openshell_core::VERSION)] @@ -200,6 +203,32 @@ struct Args { /// Shared TLS work directory between the network init container and sidecar. #[arg(long, env = "OPENSHELL_PROXY_TLS_DIR", default_value = SIDECAR_TLS_DIR)] sidecar_tls_dir: String, + + // Corporate upstream proxy. Operator-owned egress boundary: accepted + // only as command-line arguments (no `env =`), because the driver + // controls the supervisor's argv while a sandbox image could bake + // matching `ENV` values. + /// Corporate forward proxy URL (`http://host:port`) for upstream TLS egress. + #[arg(long)] + upstream_proxy: Option, + + /// Comma-separated `NO_PROXY` list for the corporate proxy. + #[arg(long)] + upstream_no_proxy: Option, + + /// Path to the root-only file holding corporate proxy credentials (`user:pass`). + #[arg(long)] + upstream_proxy_auth_file: Option, + + /// Acknowledge that proxy credentials travel as cleartext Basic auth over + /// the plain-TCP connection to the `http://` proxy. + #[arg(long)] + upstream_proxy_auth_allow_insecure: bool, + + /// Send the destination hostname in CONNECT instead of a validated IP + /// (for proxies whose ACLs filter on hostnames). + #[arg(long)] + upstream_proxy_connect_by_hostname: bool, } /// Copy the running executable to `dest`, creating parent directories as @@ -581,6 +610,14 @@ fn main() -> Result<()> { // is not yet initialized at this point (run_sandbox hasn't been called). // The shorthand layer will render it in fallback format. + let upstream_proxy_args = openshell_supervisor_network::upstream_proxy::UpstreamProxyArgs { + https_proxy: args.upstream_proxy, + no_proxy: args.upstream_no_proxy, + proxy_auth_file: args.upstream_proxy_auth_file, + proxy_auth_allow_insecure: args.upstream_proxy_auth_allow_insecure, + proxy_connect_by_hostname: args.upstream_proxy_connect_by_hostname, + }; + run_sandbox( command, args.workdir, @@ -598,6 +635,7 @@ fn main() -> Result<()> { ocsf_enabled, args.mode.network, args.mode.process, + upstream_proxy_args, ) .await })?; diff --git a/crates/openshell-supervisor-network/src/l7/tls.rs b/crates/openshell-supervisor-network/src/l7/tls.rs index 70e198f420..f7c923c690 100644 --- a/crates/openshell-supervisor-network/src/l7/tls.rs +++ b/crates/openshell-supervisor-network/src/l7/tls.rs @@ -184,7 +184,7 @@ pub async fn tls_terminate_client( /// /// Returns a TLS stream for re-encrypted upstream communication. pub async fn tls_connect_upstream( - upstream: TcpStream, + upstream: impl AsyncRead + AsyncWrite + Unpin + Send, hostname: &str, client_config: &Arc, ) -> Result { diff --git a/crates/openshell-supervisor-network/src/lib.rs b/crates/openshell-supervisor-network/src/lib.rs index c6c1af5aed..ac0cb120a2 100644 --- a/crates/openshell-supervisor-network/src/lib.rs +++ b/crates/openshell-supervisor-network/src/lib.rs @@ -19,3 +19,4 @@ pub mod run; pub mod sigv4; mod spiffe_endpoint; mod token_grant; +pub mod upstream_proxy; diff --git a/crates/openshell-supervisor-network/src/proxy.rs b/crates/openshell-supervisor-network/src/proxy.rs index 7a842af977..69245e11e1 100644 --- a/crates/openshell-supervisor-network/src/proxy.rs +++ b/crates/openshell-supervisor-network/src/proxy.rs @@ -7,6 +7,7 @@ use crate::identity::BinaryIdentityCache; use crate::l7::tls::ProxyTlsState; use crate::opa::{NetworkAction, OpaEngine, PolicyGenerationGuard}; use crate::policy_local::{POLICY_LOCAL_HOST, PolicyLocalContext}; +use crate::upstream_proxy::{self, UpstreamProxyConfig}; use miette::{IntoDiagnostic, Result}; use openshell_core::activity::{ActivitySender, try_record_activity}; use openshell_core::denial::DenialEvent; @@ -200,6 +201,7 @@ impl ProxyHandle { denial_tx: Option>, activity_tx: Option, engine_ready: tokio::sync::watch::Receiver, + upstream_proxy_args: &upstream_proxy::UpstreamProxyArgs, ) -> Result { // Use override bind_addr, fall back to policy http_addr, then default // to loopback:3128. The default allows the proxy to function when no @@ -243,6 +245,45 @@ impl ProxyHandle { .as_ref() .map_or_else(Default::default, |ctx| ctx.agent_proposals()); + // Corporate egress proxy configured by the operator and delivered on + // the supervisor's command line by the compute driver; the + // conventional HTTPS_PROXY/NO_PROXY variables the sandbox controls + // are ignored here. + // + // This is an operator-owned security boundary, so a present-but-invalid + // value (bad proxy URL, unreadable auth file, malformed credential) is + // fatal to proxy startup: failing closed prevents a misconfiguration + // from silently degrading to direct dialing or unauthenticated proxy + // access. + let upstream_proxy: Arc> = Arc::new( + UpstreamProxyConfig::from_args(upstream_proxy_args).map_err(|err| { + let event = + openshell_ocsf::ConfigStateChangeBuilder::new(openshell_ocsf::ctx::ctx()) + .severity(SeverityId::High) + .status(StatusId::Failure) + .state(openshell_ocsf::StateId::Disabled, "invalid") + .message(format!( + "Upstream corporate proxy configuration invalid; \ + refusing to start: {err}" + )) + .build(); + ocsf_emit!(event); + miette::miette!("invalid upstream corporate proxy configuration: {err}") + })?, + ); + if let Some(cfg) = upstream_proxy.as_ref() { + let event = openshell_ocsf::ConfigStateChangeBuilder::new(openshell_ocsf::ctx::ctx()) + .severity(SeverityId::Informational) + .status(StatusId::Success) + .state(openshell_ocsf::StateId::Enabled, "enabled") + .message(format!( + "Upstream corporate proxy enabled: {}", + cfg.summary() + )) + .build(); + ocsf_emit!(event); + } + let join = tokio::spawn(async move { // Wait for the OPA engine's symlink resolution reload to complete // before accepting connections. This prevents requests from @@ -279,6 +320,7 @@ impl ProxyHandle { let policy_local = policy_local_ctx.clone(); let proposals = agent_proposals.clone(); let gw = trusted_host_gateway.clone(); + let up_proxy = upstream_proxy.clone(); let resolver = provider_credentials .as_ref() .and_then(ProviderCredentialState::resolver); @@ -301,6 +343,7 @@ impl ProxyHandle { policy_local, proposals, gw, + up_proxy, resolver, dynamic_credentials, dtx, @@ -633,6 +676,7 @@ async fn handle_tcp_connection( policy_local_ctx: Option>, agent_proposals: openshell_core::proposals::AgentProposals, trusted_host_gateway: Arc>, + upstream_proxy: Arc>, secret_resolver: Option>, dynamic_credentials: Option< Arc< @@ -1178,7 +1222,7 @@ async fn handle_tcp_connection( return Ok(()); } - let mut upstream = TcpStream::connect(validated_addrs.as_slice()) + let mut upstream = dial_upstream(&upstream_proxy, &host_lc, port, &validated_addrs) .await .into_diagnostic()?; @@ -2911,6 +2955,67 @@ fn validate_declared_endpoint_resolved_addrs( Ok(()) } +/// Dial a validated upstream destination for a TLS (CONNECT) tunnel. +/// +/// Connects directly to the SSRF-checked resolved addresses, or chains +/// through the corporate proxy (HTTP CONNECT) when one is configured for +/// this destination via the driver-supplied upstream proxy arguments +/// and not excluded by the operator `NO_PROXY` list. Policy evaluation and +/// SSRF validation must have already succeeded; only the final TCP dial +/// changes. Plain-HTTP requests never take this path: they always dial the +/// destination directly. +/// +/// `NO_PROXY` evaluation is port-aware and sees the validated resolved +/// addresses: an entry with a `:port` qualifier only bypasses that port, +/// and an IP/CIDR entry that matches through resolution limits the direct +/// dial to the addresses it contains. +/// +/// The CONNECT target sent to the corporate proxy is a validated resolved +/// address, so the proxy performs no DNS resolution of its own and the +/// tunnel stays bound to the answer that passed SSRF and `allowed_ips` +/// validation; the hostname still travels inside the tunnel (TLS SNI, +/// application `Host`). The operator opt-in `proxy_connect_by_hostname` +/// sends the client-requested hostname instead, for proxies whose ACLs +/// filter on hostnames, at the cost of re-opening proxy-side resolution. +/// +/// Both paths return a [`upstream_proxy::PrefixedStream`]: for proxied +/// dials it replays any tunneled bytes that arrived in the same read as the +/// CONNECT response; for direct dials it is a plain passthrough. +async fn dial_upstream( + upstream_proxy: &Option, + host_lc: &str, + port: u16, + addrs: &[SocketAddr], +) -> std::io::Result { + if let Some(cfg) = upstream_proxy.as_ref() { + return match cfg.decision(host_lc, port, addrs) { + upstream_proxy::ProxyDecision::Proxy(endpoint) => { + if cfg.connect_by_hostname() { + upstream_proxy::connect_via( + endpoint, + host_lc, + port, + upstream_proxy::ConnectTarget::Hostname, + ) + .await + } else { + // Try every validated address in order, matching the + // fallback the direct path's `TcpStream::connect` does. + upstream_proxy::connect_via_validated(endpoint, host_lc, port, addrs).await + } + } + upstream_proxy::ProxyDecision::Direct(direct_addrs) => { + Ok(upstream_proxy::PrefixedStream::without_prefix( + TcpStream::connect(&direct_addrs[..]).await?, + )) + } + }; + } + Ok(upstream_proxy::PrefixedStream::without_prefix( + TcpStream::connect(addrs).await?, + )) +} + /// Resolve a host:port using sandbox `/etc/hosts` first (when available), then /// reject if any resolved address is internal. /// @@ -4589,8 +4694,12 @@ async fn handle_forward_proxy( return Ok(()); } - // 6. Connect upstream - let mut upstream = match TcpStream::connect(addrs.as_slice()).await { + // 6. Connect upstream. Plain-HTTP requests always dial the destination + // directly: only TLS (CONNECT) tunnels chain through the corporate + // proxy, since plain-HTTP forwarding would need absolute-form requests + // rather than a CONNECT tunnel. + let dial_result = TcpStream::connect(addrs.as_slice()).await; + let mut upstream = match dial_result { Ok(s) => s, Err(e) => { let event = HttpActivityBuilder::new(openshell_ocsf::ctx::ctx()) @@ -4859,10 +4968,26 @@ async fn handle_forward_proxy( Ok(()) } +/// Parse a CONNECT authority into `(host, port)`. +/// +/// IPv6 literals use the RFC 3986 bracketed form (`[::1]:443`); the returned +/// host is bracket-free, matching what DNS resolution, SSRF validation, and +/// `NO_PROXY` matching expect. Host content is otherwise passed through +/// unvalidated — policy and resolution decide what it means. fn parse_target(target: &str) -> Result<(String, u16)> { - let (host, port_str) = target - .split_once(':') - .ok_or_else(|| miette::miette!("CONNECT target missing port: {target}"))?; + let (host, port_str) = if let Some(rest) = target.strip_prefix('[') { + let (host, after) = rest + .split_once(']') + .ok_or_else(|| miette::miette!("CONNECT target has unclosed '[': {target}"))?; + let port_str = after + .strip_prefix(':') + .ok_or_else(|| miette::miette!("CONNECT target missing port: {target}"))?; + (host, port_str) + } else { + target + .split_once(':') + .ok_or_else(|| miette::miette!("CONNECT target missing port: {target}"))? + }; let port: u16 = port_str .parse() .map_err(|_| miette::miette!("Invalid port in CONNECT target: {target}"))?; @@ -5087,6 +5212,7 @@ network_policies: {} None, AgentProposals::default(), Arc::new(None), + Arc::new(None), None, None, None, @@ -8311,11 +8437,30 @@ network_policies: } #[test] - fn test_parse_target_ipv6_bracket_notation_fails() { - assert!( - parse_target("[::1]:443").is_err(), - "split_once splits at first colon inside brackets — port parse fails" - ); + fn test_parse_target_ipv6_bracket_notation() { + let (host, port) = parse_target("[::1]:443").unwrap(); + assert_eq!(host, "::1", "brackets are stripped from the parsed host"); + assert_eq!(port, 443); + + let (host, port) = parse_target("[2001:db8::1]:8443").unwrap(); + assert_eq!(host, "2001:db8::1"); + assert_eq!(port, 8443); + } + + #[test] + fn test_parse_target_rejects_malformed_ipv6_brackets() { + for target in [ + // Unclosed bracket. + "[::1:443", + // No port after the bracket. + "[::1]", + "[::1]443", + // Empty or non-numeric port. + "[::1]:", + "[::1]:notaport", + ] { + assert!(parse_target(target).is_err(), "{target} should be rejected"); + } } // -- parse_proxy_uri: hostname parser regression tests -- @@ -9406,6 +9551,7 @@ network_policies: None, // policy_local_ctx AgentProposals::default(), // agent_proposals Arc::new(None), // trusted_host_gateway + Arc::new(None), // upstream_proxy None, // secret_resolver None, // dynamic_credentials Some(denial_tx), // denial_tx — positive allow/deny signal diff --git a/crates/openshell-supervisor-network/src/run.rs b/crates/openshell-supervisor-network/src/run.rs index f8f38a440b..5047ad7bdb 100644 --- a/crates/openshell-supervisor-network/src/run.rs +++ b/crates/openshell-supervisor-network/src/run.rs @@ -89,6 +89,7 @@ pub async fn run_networking( activity_tx: Option, agent_proposals: AgentProposals, workspace_rx: tokio::sync::watch::Receiver, + upstream_proxy_args: &crate::upstream_proxy::UpstreamProxyArgs, ) -> Result { // Build the policy-local route context. The orchestrator's policy poll // loop also holds an `Arc` clone (via `Networking::policy_local_ctx`) so @@ -314,6 +315,7 @@ pub async fn run_networking( denial_tx, activity_tx, engine_ready_rx, + upstream_proxy_args, ) .await?; Some(proxy_handle) diff --git a/crates/openshell-supervisor-network/src/upstream_proxy.rs b/crates/openshell-supervisor-network/src/upstream_proxy.rs new file mode 100644 index 0000000000..85e57c14c5 --- /dev/null +++ b/crates/openshell-supervisor-network/src/upstream_proxy.rs @@ -0,0 +1,1877 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Upstream corporate proxy chaining for the sandbox egress proxy. +//! +//! In proxy-required enterprise networks (issue #1792) the supervisor cannot +//! dial policy-approved destinations directly: all outbound traffic must go +//! through a corporate forward proxy. The operator-owned proxy configuration +//! reaches the supervisor as command-line arguments ([`UpstreamProxyArgs`]) +//! that the compute driver sets when it launches the supervisor — never +//! through the environment, which sandbox images could bake `ENV` values +//! into — and this module chains approved TLS tunnels through the corporate +//! proxy with HTTP CONNECT. +//! +//! Only TLS (CONNECT) egress is chained: plain-HTTP requests always dial the +//! destination directly. Forwarding plain HTTP through a corporate proxy +//! requires absolute-form request forwarding rather than CONNECT tunneling +//! and is out of scope for this feature. +//! +//! The conventional `HTTPS_PROXY` / `HTTP_PROXY` / `ALL_PROXY` / `NO_PROXY` +//! variables are intentionally ignored: those are controlled by the sandbox +//! creator and are rewritten separately to point the workload child at the +//! local policy proxy, so honoring them would let a sandbox pick an arbitrary +//! upstream proxy or disable proxying with `NO_PROXY=*`. +//! +//! Scope and invariants: +//! - Only `http://` proxy URLs are supported. Configuration is fail-closed: +//! any present-but-invalid driver-supplied setting — an empty argument +//! value, an unsupported (`https://`, SOCKS) or malformed proxy URL, an +//! unreadable auth file, a malformed credential, or an auth file without the explicit +//! cleartext-credential acknowledgement — is a fatal startup error rather +//! than being silently ignored, so a typo can never quietly downgrade the +//! operator's egress boundary to direct dialing or unauthenticated proxy +//! access. Validation semantics are shared with the compute driver via +//! [`openshell_core::driver_utils::parse_upstream_proxy_url`] and +//! [`openshell_core::driver_utils::parse_upstream_proxy_credential`]. +//! - Policy evaluation, DNS resolution, and SSRF checks run exactly as in the +//! direct-dial path; the corporate proxy only replaces the final TCP dial. +//! - CONNECT requests target a validated resolved address by default, so the +//! proxy performs no DNS resolution and the tunnel stays bound to the +//! answer that passed SSRF/`allowed_ips` validation. The +//! `--upstream-proxy-connect-by-hostname` opt-in sends the hostname +//! instead, for proxies whose ACLs filter on hostnames. +//! - The operator `NO_PROXY` list decides which destinations bypass the +//! corporate proxy and keep dialing directly (cluster-internal services, +//! host gateway, etc.). Loopback destinations always bypass the proxy. + +use std::io::{Error as IoError, ErrorKind}; +use std::net::{IpAddr, SocketAddr}; +use std::pin::Pin; +use std::task::{Context, Poll}; +use std::time::Duration; + +use base64::Engine as _; +use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, ReadBuf}; +use tokio::net::TcpStream; +use tracing::debug; + +/// Upper bound on the corporate proxy's CONNECT response header block. +const MAX_CONNECT_RESPONSE_BYTES: usize = 8 * 1024; + +/// End-to-end budget for dialing the corporate proxy and completing the +/// CONNECT handshake. +const CONNECT_HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(30); + +/// A parsed corporate proxy endpoint. +#[derive(Clone)] +pub struct ProxyEndpoint { + host: String, + port: u16, + /// Pre-computed `Basic ` header value from the proxy auth file. + /// Never logged. + proxy_authorization: Option, +} + +impl ProxyEndpoint { + /// `host:port` label for logs. Excludes credentials. + #[must_use] + pub fn display_addr(&self) -> String { + format!("{}:{}", self.host, self.port) + } +} + +impl std::fmt::Debug for ProxyEndpoint { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("ProxyEndpoint") + .field("host", &self.host) + .field("port", &self.port) + .field("proxy_authorization", &self.proxy_authorization.is_some()) + .finish() + } +} + +/// The pattern half of one parsed `NO_PROXY` entry. +#[derive(Debug, Clone)] +enum NoProxyPattern { + /// `*` — bypass the proxy for every destination. + Wildcard, + /// Domain suffix match: `corp.com` matches `corp.com` and `x.corp.com`. + Domain(String), + /// Exact IP match, against an IP-literal host or its resolved addresses. + Ip(IpAddr), + /// CIDR match, against an IP-literal host or its resolved addresses. + Cidr(ipnet::IpNet), +} + +/// One parsed `NO_PROXY` entry. +#[derive(Debug, Clone)] +struct NoProxyEntry { + pattern: NoProxyPattern, + /// When set (`internal.corp:8443`), the entry only applies to this + /// destination port instead of every port. + port: Option, +} + +/// Parsed `NO_PROXY` list. +#[derive(Debug, Clone, Default)] +struct NoProxy { + entries: Vec, +} + +impl NoProxy { + fn parse(raw: &str) -> Self { + let mut entries = Vec::new(); + for item in raw.split(',') { + let item = item.trim(); + if item.is_empty() { + continue; + } + if item == "*" { + entries.push(NoProxyEntry { + pattern: NoProxyPattern::Wildcard, + port: None, + }); + continue; + } + // Whole-item IP/CIDR forms first: a bare IPv6 literal contains + // colons that must never be misread as a port qualifier. + if let Ok(net) = item.parse::() { + entries.push(NoProxyEntry { + pattern: NoProxyPattern::Cidr(net), + port: None, + }); + continue; + } + if let Ok(ip) = item.trim_matches(['[', ']']).parse::() { + entries.push(NoProxyEntry { + pattern: NoProxyPattern::Ip(ip), + port: None, + }); + continue; + } + // Optional `:port` qualifier: only a valid trailing u16 counts; + // anything else stays part of the pattern. + let (head, port) = item + .rsplit_once(':') + .map_or((item, None), |(head, port_str)| { + port_str + .parse::() + .map_or((item, None), |port| (head, Some(port))) + }); + let pattern = if let Ok(net) = head.parse::() { + NoProxyPattern::Cidr(net) + } else if let Ok(ip) = head.trim_matches(['[', ']']).parse::() { + NoProxyPattern::Ip(ip) + } else { + // Domain entry. Strip any leading `*.` or `.` so + // `.corp.com`, `*.corp.com`, and `corp.com` all behave + // identically. + let name = head + .strip_prefix("*.") + .or_else(|| head.strip_prefix('.')) + .unwrap_or(head) + .to_ascii_lowercase(); + if name.is_empty() { + continue; + } + NoProxyPattern::Domain(name) + }; + entries.push(NoProxyEntry { pattern, port }); + } + Self { entries } + } + + /// The validated addresses that may be dialed directly for + /// `(host, port)`, or `None` when no entry matches and the corporate + /// proxy must be used. + /// + /// Hostname-level matches — `*`, a domain entry, or an IP/CIDR entry + /// matching an IP-literal host — authorize every validated address. + /// IP/CIDR entries match hostnames through their *resolved* addresses and + /// authorize only the addresses they contain, so a bypass scoped to an + /// internal range can never widen into a direct dial of an address + /// outside that range. + /// + /// The automatic loopback bypass is derived from resolved addresses, never + /// from the host string: `resolved` may come from the sandbox's own + /// `/etc/hosts` (see `resolve_socket_addrs`), which the workload controls, + /// so treating the name `localhost` as proof of loopback would let a + /// spoofed mapping dial a policy-allowed public address while escaping the + /// operator proxy. A spoofed `localhost` falls through to the entries below + /// and is proxied unless an explicit `NO_PROXY` entry matches. + fn direct_addrs( + &self, + host: &str, + port: u16, + resolved: &[SocketAddr], + ) -> Option> { + let host_ip = host.trim_matches(['[', ']']).parse::().ok(); + if let Some(ip) = host_ip { + // An IP literal is its own destination, so the host string is + // authoritative here. + if ip.is_loopback() { + return Some(resolved.to_vec()); + } + } else if host == "localhost" + && !resolved.is_empty() + && resolved.iter().all(|addr| addr.ip().is_loopback()) + { + return Some(resolved.to_vec()); + } + let mut subset: Vec = Vec::new(); + for entry in &self.entries { + if entry.port.is_some_and(|entry_port| entry_port != port) { + continue; + } + match &entry.pattern { + NoProxyPattern::Wildcard => return Some(resolved.to_vec()), + NoProxyPattern::Domain(suffix) => { + if host == suffix + || host + .strip_suffix(suffix) + .is_some_and(|prefix| prefix.ends_with('.')) + { + return Some(resolved.to_vec()); + } + } + NoProxyPattern::Ip(ip) => { + if host_ip == Some(*ip) { + return Some(resolved.to_vec()); + } + for addr in resolved { + if addr.ip() == *ip && !subset.contains(addr) { + subset.push(*addr); + } + } + } + NoProxyPattern::Cidr(net) => { + if host_ip.is_some_and(|ip| net.contains(&ip)) { + return Some(resolved.to_vec()); + } + for addr in resolved { + if net.contains(&addr.ip()) && !subset.contains(addr) { + subset.push(*addr); + } + } + } + } + } + if subset.is_empty() { + None + } else { + Some(subset) + } + } +} + +/// How a validated destination must be dialed, per the operator `NO_PROXY` +/// contract. Produced by [`UpstreamProxyConfig::decision`]. +#[derive(Debug)] +pub enum ProxyDecision<'a> { + /// Chain through the corporate proxy with HTTP CONNECT. + Proxy(&'a ProxyEndpoint), + /// Dial directly, restricted to this subset of the validated addresses: + /// all of them for hostname-level matches (loopback, `*`, domain + /// entries, IP-literal hosts), only the addresses contained in the + /// matching IP/CIDR entries otherwise. + Direct(Vec), +} + +/// What the supervisor puts in the CONNECT request line sent to the +/// corporate proxy. +#[derive(Debug, Clone, Copy)] +pub enum ConnectTarget { + /// CONNECT to this validated address; the proxy performs no DNS + /// resolution, so the tunnel is bound to the answer that already passed + /// SSRF and `allowed_ips` validation. The destination hostname still + /// travels inside the tunnel (TLS SNI, application `Host`). + Ip(IpAddr), + /// CONNECT by hostname; the proxy resolves the name itself. Operator + /// opt-in for hostname-filtering proxy ACLs + /// (`--upstream-proxy-connect-by-hostname`). + Hostname, +} + +/// Corporate proxy configuration built from the driver-supplied +/// command-line arguments ([`UpstreamProxyArgs`]). +#[derive(Debug, Clone)] +pub struct UpstreamProxyConfig { + https: ProxyEndpoint, + no_proxy: NoProxy, + connect_by_hostname: bool, +} + +/// Operator-owned corporate proxy settings passed to the supervisor as +/// command-line arguments by the compute driver. +/// +/// Argv is set by the driver when it creates the container/VM and cannot be +/// influenced by sandbox environment or image `ENV`, so a field left `None` +/// / `false` genuinely means "not configured by the operator". +#[derive(Debug, Clone, Default)] +pub struct UpstreamProxyArgs { + /// `http://host:port` corporate proxy URL, or `None` for direct egress. + pub https_proxy: Option, + /// Comma-separated `NO_PROXY` list. + pub no_proxy: Option, + /// Path to the root-only credential mount (`user:pass`). + pub proxy_auth_file: Option, + /// Operator acknowledgement that credentials travel as cleartext Basic + /// auth over the plain-TCP proxy connection. + pub proxy_auth_allow_insecure: bool, + /// Send the destination hostname in CONNECT instead of a validated IP. + pub proxy_connect_by_hostname: bool, +} + +// Supervisor CLI flag names for the corporate-proxy settings, used as the +// dispatch keys in `from_lookup` and in operator-facing error messages. +const ARG_HTTPS_PROXY: &str = "--upstream-proxy"; +const ARG_NO_PROXY: &str = "--upstream-no-proxy"; +const ARG_PROXY_AUTH_FILE: &str = "--upstream-proxy-auth-file"; +const ARG_PROXY_AUTH_ALLOW_INSECURE: &str = "--upstream-proxy-auth-allow-insecure"; +const ARG_PROXY_CONNECT_BY_HOSTNAME: &str = "--upstream-proxy-connect-by-hostname"; + +impl UpstreamProxyConfig { + /// Build the corporate proxy configuration from the driver-supplied + /// command-line [`UpstreamProxyArgs`]. Returns `Ok(None)` when no proxy + /// is configured. + /// + /// The conventional `HTTPS_PROXY` / `HTTP_PROXY` / `ALL_PROXY` / + /// `NO_PROXY` environment variables are intentionally never consulted: + /// they are controlled by the sandbox creator (and rewritten to point + /// workload children at the local policy proxy), so honoring them would + /// let a sandbox choose an arbitrary upstream proxy or disable proxying + /// entirely. + /// + /// # Errors + /// + /// This is an operator-owned security boundary, so a present-but-invalid + /// value is fatal instead of being treated as unset: an empty (or + /// whitespace-only) argument, an invalid or unsupported proxy URL, an + /// auth file that is set but unreadable or holds a malformed credential, + /// an auth file without the cleartext-credential acknowledgement, or an + /// auth file / `NO_PROXY` list / acknowledgement / connect-by-hostname + /// flag with no proxy configured. Failing closed prevents a + /// misconfiguration from silently degrading to direct dialing or + /// unauthenticated proxy access. + pub fn from_args(args: &UpstreamProxyArgs) -> Result, String> { + // Present the typed argv fields under their canonical identifiers so + // the shared validation runs once. Booleans map to Some("true") / + // None, so every pairing rule (auth file needs the acknowledgement, + // no auxiliary setting without a proxy) applies unchanged. + Self::from_lookup(|name| { + if name == ARG_HTTPS_PROXY { + args.https_proxy.clone() + } else if name == ARG_NO_PROXY { + args.no_proxy.clone() + } else if name == ARG_PROXY_AUTH_FILE { + args.proxy_auth_file.clone() + } else if name == ARG_PROXY_AUTH_ALLOW_INSECURE { + args.proxy_auth_allow_insecure.then(|| "true".to_string()) + } else if name == ARG_PROXY_CONNECT_BY_HOSTNAME { + args.proxy_connect_by_hostname.then(|| "true".to_string()) + } else { + None + } + }) + } + + fn from_lookup(lookup: impl Fn(&str) -> Option) -> Result, String> { + // A missing setting means "not configured". A present-but-empty value + // is a misconfiguration (the driver never emits one), so it is fatal + // rather than silently downgrading the boundary to direct dialing or + // unauthenticated proxy access. + let var = |name: &str| -> Result, String> { + match lookup(name) { + None => Ok(None), + Some(value) if value.trim().is_empty() => { + Err(format!("{name} must not be empty when set")) + } + Some(value) => Ok(Some(value)), + } + }; + let https = var(ARG_HTTPS_PROXY)? + .map(|url| parse_proxy_url(&url, ARG_HTTPS_PROXY)) + .transpose()?; + let auth_file = var(ARG_PROXY_AUTH_FILE)?; + let auth_allow_insecure = var(ARG_PROXY_AUTH_ALLOW_INSECURE)?; + let connect_by_hostname_raw = var(ARG_PROXY_CONNECT_BY_HOSTNAME)?; + let no_proxy_list = var(ARG_NO_PROXY)?; + let Some(mut https) = https else { + // Auxiliary proxy settings without a proxy mean the operator + // believed a proxy boundary was in effect; refuse rather than + // silently running with direct egress. + for (name, value) in [ + (ARG_PROXY_AUTH_FILE, &auth_file), + (ARG_PROXY_AUTH_ALLOW_INSECURE, &auth_allow_insecure), + (ARG_PROXY_CONNECT_BY_HOSTNAME, &connect_by_hostname_raw), + (ARG_NO_PROXY, &no_proxy_list), + ] { + if value.is_some() { + return Err(format!("{name} is set but no upstream proxy is configured")); + } + } + return Ok(None); + }; + + // CONNECT-target mode. The default binds the tunnel to a validated + // address; hostname CONNECT re-opens proxy-side DNS resolution and + // is only honored as the exact opt-in value the driver writes. + let connect_by_hostname = match connect_by_hostname_raw.as_deref().map(str::trim) { + None => false, + Some("true") => true, + Some(_) => { + return Err(format!( + "{ARG_PROXY_CONNECT_BY_HOSTNAME} must be 'true' when set" + )); + } + }; + + // Cleartext-credential acknowledgement. `Proxy-Authorization: Basic` + // travels over plain TCP to the http:// proxy, so credentials are + // only sent when the operator explicitly opted in. The compute driver + // enforces the same pairing at sandbox-create time; enforcing it here + // as well keeps the supervisor fail-closed against a bypassed or + // foreign driver. + let allow_insecure = match auth_allow_insecure.as_deref().map(str::trim) { + None => false, + Some("true") => true, + Some(_) => { + return Err(format!( + "{ARG_PROXY_AUTH_ALLOW_INSECURE} must be 'true' when set" + )); + } + }; + if auth_file.is_none() && auth_allow_insecure.is_some() { + return Err(format!( + "{ARG_PROXY_AUTH_ALLOW_INSECURE} is set but no {ARG_PROXY_AUTH_FILE} is configured" + )); + } + if auth_file.is_some() && !allow_insecure { + return Err(format!( + "{ARG_PROXY_AUTH_FILE} sends the credential as cleartext Basic auth \ + over the plain-TCP proxy connection; refusing without \ + {ARG_PROXY_AUTH_ALLOW_INSECURE}" + )); + } + + // Load proxy credentials from the configured auth file, if any. + // The file is delivered through a root-only secret mount so the + // credentials never appear in the environment or container metadata. + if let Some(path) = auth_file { + let credential = + openshell_core::driver_utils::read_upstream_proxy_credential_file(&path)?; + let header = basic_auth_header(&credential).map_err(|err| { + format!("invalid credential in upstream proxy auth file '{path}': {err}") + })?; + https.proxy_authorization = Some(header); + } + + Ok(Some(Self { + https, + no_proxy: NoProxy::parse(&no_proxy_list.unwrap_or_default()), + connect_by_hostname, + })) + } + + /// Whether CONNECT requests carry the destination hostname instead of a + /// validated IP (operator opt-in for hostname-filtering proxy ACLs). + #[must_use] + pub fn connect_by_hostname(&self) -> bool { + self.connect_by_hostname + } + + /// How to dial the validated destination `(host, port, resolved)`, + /// honoring the operator `NO_PROXY` list. + /// + /// Entries may carry a `:port` qualifier that limits them to that + /// destination port. IP/CIDR entries also match a hostname through its + /// already-validated resolved addresses; such a match authorizes a + /// direct dial of only the addresses inside the entry (see + /// [`ProxyDecision::Direct`]). + #[must_use] + pub fn decision<'a>( + &'a self, + host: &str, + port: u16, + resolved: &[SocketAddr], + ) -> ProxyDecision<'a> { + self.no_proxy + .direct_addrs(host, port, resolved) + .map_or(ProxyDecision::Proxy(&self.https), ProxyDecision::Direct) + } + + /// Credential-free summary for startup logging. + #[must_use] + pub fn summary(&self) -> String { + format!( + "https_proxy={} no_proxy_entries={} connect_target={}", + self.https.display_addr(), + self.no_proxy.entries.len(), + if self.connect_by_hostname { + "hostname" + } else { + "validated-ip" + } + ) + } +} + +/// Parse an `http://host:port` proxy URL with the same validation rules the +/// compute driver applies at sandbox-create time +/// ([`parse_upstream_proxy_url`](openshell_core::driver_utils::parse_upstream_proxy_url)). +/// +/// Credentials are never taken from the URL: they are delivered out of band +/// through the root-only auth-file mount (`--upstream-proxy-auth-file`) so +/// they never appear in config or container metadata. +/// +/// # Errors +/// +/// Rejects unsupported schemes (TLS or SOCKS proxies), inline `user:pass@` +/// credentials, and malformed addresses. The error names `var_name` so the +/// operator can locate the offending setting. +fn parse_proxy_url(raw: &str, var_name: &str) -> Result { + let addr = openshell_core::driver_utils::parse_upstream_proxy_url(raw) + .map_err(|err| format!("{var_name} is invalid: {err}"))?; + Ok(ProxyEndpoint { + host: addr.host, + port: addr.port, + proxy_authorization: None, + }) +} + +/// Build a `Proxy-Authorization: Basic ` header value from a raw +/// `user:pass` credential. +/// +/// The credential is used verbatim after trimming: it is delivered through a +/// trusted operator file, not a URL, so there is no percent-encoding to +/// decode. Validation is shared with the compute driver through +/// [`parse_upstream_proxy_credential`](openshell_core::driver_utils::parse_upstream_proxy_credential), +/// so a credential the driver staged at sandbox-create time is never rejected +/// here. +/// +/// # Errors +/// +/// Rejects an empty credential, one containing control characters that could +/// inject additional HTTP headers, and one not in `user:pass` form. Error +/// messages never include the credential content. +fn basic_auth_header(credential: &str) -> Result { + let credential = openshell_core::driver_utils::parse_upstream_proxy_credential(credential) + .map_err(|err| err.to_string())?; + Ok(format!( + "Basic {}", + base64::engine::general_purpose::STANDARD.encode(credential) + )) +} + +/// A `TcpStream` that first replays bytes already read from the socket. +/// +/// The CONNECT handshake reads from the proxy socket in chunks, so the read +/// that completes the response header block may also contain the first +/// tunneled payload bytes (a server-speaks-first destination, or a proxy +/// that coalesces writes). Those bytes belong to the destination byte +/// stream and must reach the caller rather than being discarded; this +/// wrapper yields them before reading from the socket again. Writes pass +/// straight through. +#[derive(Debug)] +pub struct PrefixedStream { + inner: TcpStream, + /// Bytes read past the CONNECT header terminator, replayed first. + prefix: Vec, + /// Read offset into `prefix`. + pos: usize, +} + +impl PrefixedStream { + /// Wrap `inner`, replaying `prefix` before socket reads. + #[must_use] + pub fn new(inner: TcpStream, prefix: Vec) -> Self { + Self { + inner, + prefix, + pos: 0, + } + } + + /// Wrap a directly dialed stream with nothing to replay. + #[must_use] + pub fn without_prefix(inner: TcpStream) -> Self { + Self::new(inner, Vec::new()) + } +} + +impl AsyncRead for PrefixedStream { + fn poll_read( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + buf: &mut ReadBuf<'_>, + ) -> Poll> { + let this = self.get_mut(); + if this.pos < this.prefix.len() { + let n = buf.remaining().min(this.prefix.len() - this.pos); + buf.put_slice(&this.prefix[this.pos..this.pos + n]); + this.pos += n; + if this.pos == this.prefix.len() { + // Drained: release the buffer instead of holding it for the + // tunnel's lifetime. + this.prefix = Vec::new(); + this.pos = 0; + } + return Poll::Ready(Ok(())); + } + Pin::new(&mut this.inner).poll_read(cx, buf) + } +} + +impl AsyncWrite for PrefixedStream { + fn poll_write( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + buf: &[u8], + ) -> Poll> { + Pin::new(&mut self.get_mut().inner).poll_write(cx, buf) + } + + fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut self.get_mut().inner).poll_flush(cx) + } + + fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut self.get_mut().inner).poll_shutdown(cx) + } + + fn poll_write_vectored( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + bufs: &[std::io::IoSlice<'_>], + ) -> Poll> { + Pin::new(&mut self.get_mut().inner).poll_write_vectored(cx, bufs) + } + + fn is_write_vectored(&self) -> bool { + self.inner.is_write_vectored() + } +} + +/// Open a tunnel to the destination through the corporate proxy with HTTP +/// CONNECT. +/// +/// Returns the connected stream once the proxy answers 200; after that the +/// stream is a transparent byte pipe to the destination. Any tunneled bytes +/// received in the same read as the CONNECT response are preserved and +/// replayed by the returned [`PrefixedStream`]. +/// +/// `target` selects the CONNECT request target. The default mode sends a +/// validated IP ([`ConnectTarget::Ip`]) so the proxy performs no DNS +/// resolution and the tunnel is bound to an address that already passed +/// SSRF and `allowed_ips` validation; `host` then only labels logs and is +/// used by the caller for TLS SNI inside the tunnel. With the operator +/// opt-in ([`ConnectTarget::Hostname`]) the hostname is sent instead so +/// hostname-filtering proxy ACLs keep working, at the cost of proxy-side +/// resolution. Local DNS resolution and SSRF validation must already have +/// happened at the call site in both modes. +/// +/// # Errors +/// +/// Returns an error when the proxy is unreachable, the handshake times out, +/// or the proxy answers with a non-200 status. +pub async fn connect_via( + endpoint: &ProxyEndpoint, + host: &str, + port: u16, + target: ConnectTarget, +) -> std::io::Result { + tokio::time::timeout( + CONNECT_HANDSHAKE_TIMEOUT, + connect_via_inner(endpoint, host, port, target), + ) + .await + .map_err(|_| { + IoError::new( + ErrorKind::TimedOut, + format!( + "upstream proxy {} CONNECT handshake timed out", + endpoint.display_addr() + ), + ) + })? +} + +/// Open a validated-IP CONNECT tunnel, trying each validated address in +/// order until one succeeds. +/// +/// The direct-dial path hands `TcpStream::connect` the whole validated list +/// and it falls back across addresses; this is the proxied equivalent, so a +/// dual-stack destination whose first validated address is unreachable +/// through the corporate proxy still connects via a later one. All attempts +/// share one aggregate handshake budget ([`CONNECT_HANDSHAKE_TIMEOUT`]), +/// matching the single-attempt paths; within it, each attempt is capped at +/// its fair share of the remaining time (`remaining / attempts_left`) so a +/// proxy that accepts a CONNECT but never answers cannot starve the +/// remaining validated addresses. Time an attempt fails without using +/// rolls over to later attempts. +/// +/// # Errors +/// +/// Returns an error when `addrs` is empty, or when every attempt fails or +/// times out (the last attempt's error, annotated with the attempt count +/// when there were several). +pub async fn connect_via_validated( + endpoint: &ProxyEndpoint, + host: &str, + port: u16, + addrs: &[SocketAddr], +) -> std::io::Result { + connect_via_validated_with_budget(endpoint, host, port, addrs, CONNECT_HANDSHAKE_TIMEOUT).await +} + +/// [`connect_via_validated`] with an explicit aggregate budget, split out so +/// tests can exercise the hang-fallback behavior without real 30s waits. +async fn connect_via_validated_with_budget( + endpoint: &ProxyEndpoint, + host: &str, + port: u16, + addrs: &[SocketAddr], + budget: Duration, +) -> std::io::Result { + if addrs.is_empty() { + return Err(IoError::new( + ErrorKind::InvalidInput, + format!("no validated addresses to CONNECT to for {host}"), + )); + } + let deadline = tokio::time::Instant::now() + budget; + let mut last_err = None; + let mut attempted = 0usize; + for (index, addr) in addrs.iter().enumerate() { + let remaining = deadline.saturating_duration_since(tokio::time::Instant::now()); + if remaining.is_zero() { + break; + } + let attempts_left = u32::try_from(addrs.len() - index).unwrap_or(u32::MAX); + let attempt_budget = remaining / attempts_left; + attempted += 1; + match tokio::time::timeout( + attempt_budget, + connect_via_inner(endpoint, host, port, ConnectTarget::Ip(addr.ip())), + ) + .await + { + Ok(Ok(stream)) => return Ok(stream), + Ok(Err(err)) => last_err = Some(err), + Err(_) => { + last_err = Some(IoError::new( + ErrorKind::TimedOut, + format!( + "upstream proxy {} CONNECT to {} timed out", + endpoint.display_addr(), + addr.ip(), + ), + )); + } + } + } + // The first iteration always runs (`remaining` starts at the full + // budget), so at least one attempt recorded an error. + let last = last_err.expect("at least one CONNECT attempt"); + if addrs.len() == 1 { + return Err(last); + } + let scope = if attempted == addrs.len() { + format!("all {} validated addresses", addrs.len()) + } else { + format!( + "{attempted} of {} validated addresses (handshake budget exhausted)", + addrs.len() + ) + }; + Err(IoError::new( + last.kind(), + format!("CONNECT failed for {scope} of {host}; last: {last}"), + )) +} + +async fn connect_via_inner( + endpoint: &ProxyEndpoint, + host: &str, + port: u16, + target: ConnectTarget, +) -> std::io::Result { + let mut stream = TcpStream::connect((endpoint.host.as_str(), endpoint.port)).await?; + + let target = match target { + ConnectTarget::Ip(IpAddr::V6(ip)) => format!("[{ip}]:{port}"), + ConnectTarget::Ip(ip) => format!("{ip}:{port}"), + ConnectTarget::Hostname if host.contains(':') => format!("[{host}]:{port}"), + ConnectTarget::Hostname => format!("{host}:{port}"), + }; + let mut request = format!("CONNECT {target} HTTP/1.1\r\nHost: {target}\r\n"); + if let Some(auth) = &endpoint.proxy_authorization { + request.push_str("Proxy-Authorization: "); + request.push_str(auth); + request.push_str("\r\n"); + } + request.push_str("\r\n"); + stream.write_all(request.as_bytes()).await?; + + // Read the proxy's response header block. A read may run past the + // `\r\n\r\n` terminator into tunneled payload; those bytes are preserved + // below, never discarded. + let mut buf = vec![0u8; MAX_CONNECT_RESPONSE_BYTES]; + let mut used = 0; + let header_end = loop { + if used == buf.len() { + return Err(IoError::other(format!( + "upstream proxy {} CONNECT response headers exceed {MAX_CONNECT_RESPONSE_BYTES} bytes", + endpoint.display_addr() + ))); + } + let n = stream.read(&mut buf[used..]).await?; + if n == 0 { + return Err(IoError::new( + ErrorKind::UnexpectedEof, + format!( + "upstream proxy {} closed the connection during CONNECT", + endpoint.display_addr() + ), + )); + } + used += n; + if let Some(pos) = buf[..used].windows(4).position(|win| win == b"\r\n\r\n") { + break pos + 4; + } + }; + + let response = String::from_utf8_lossy(&buf[..header_end]); + let status_line = response.lines().next().unwrap_or_default(); + let status_code = status_line + .split_whitespace() + .nth(1) + .and_then(|code| code.parse::().ok()); + match status_code { + Some(200) => { + debug!( + proxy = %endpoint.display_addr(), + target = %target, + "upstream proxy CONNECT tunnel established" + ); + buf.truncate(used); + let overflow = buf.split_off(header_end); + Ok(PrefixedStream::new(stream, overflow)) + } + Some(code) => Err(IoError::other(format!( + "upstream proxy {} refused CONNECT to {target}: HTTP {code}", + endpoint.display_addr() + ))), + None => Err(IoError::new( + ErrorKind::InvalidData, + format!( + "upstream proxy {} sent a malformed CONNECT response", + endpoint.display_addr() + ), + )), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use super::{ + ARG_HTTPS_PROXY as HTTPS_PROXY, ARG_NO_PROXY as NO_PROXY, + ARG_PROXY_AUTH_ALLOW_INSECURE as PROXY_AUTH_ALLOW_INSECURE, + ARG_PROXY_AUTH_FILE as PROXY_AUTH_FILE, + ARG_PROXY_CONNECT_BY_HOSTNAME as PROXY_CONNECT_BY_HOSTNAME, + }; + + fn config_from(pairs: &[(&str, &str)]) -> Result, String> { + UpstreamProxyConfig::from_lookup(|name| { + pairs + .iter() + .find(|(k, _)| *k == name) + .map(|(_, v)| (*v).to_string()) + }) + } + + /// Shorthand for tests exercising a configuration that must load. + fn config_ok(pairs: &[(&str, &str)]) -> UpstreamProxyConfig { + config_from(pairs).unwrap().unwrap() + } + + #[test] + fn no_env_yields_none() { + assert!(config_from(&[]).unwrap().is_none()); + } + + #[test] + fn from_args_maps_cli_arguments_to_config() { + // The driver-supplied argv is the authoritative source; the shared + // validation applies to it exactly as in the flag-keyed lookup. + let args = UpstreamProxyArgs { + https_proxy: Some("http://proxy.corp.com:8080".to_string()), + no_proxy: Some("*.svc.cluster.local".to_string()), + proxy_connect_by_hostname: true, + ..UpstreamProxyArgs::default() + }; + let cfg = UpstreamProxyConfig::from_args(&args).unwrap().unwrap(); + assert!(cfg.connect_by_hostname()); + assert!(bypasses(&cfg, "kubernetes.default.svc.cluster.local")); + + // No proxy URL means no configuration. + assert!( + UpstreamProxyConfig::from_args(&UpstreamProxyArgs::default()) + .unwrap() + .is_none() + ); + } + + #[test] + fn from_args_enforces_the_auth_file_acknowledgement_pairing() { + // An auth file without the acknowledgement is fatal, exactly as in + // the flag-keyed lookup the driver validation mirrors. + let args = UpstreamProxyArgs { + https_proxy: Some("http://proxy.corp.com:8080".to_string()), + proxy_auth_file: Some("/etc/openshell/auth/upstream-proxy".to_string()), + ..UpstreamProxyArgs::default() + }; + let err = UpstreamProxyConfig::from_args(&args).unwrap_err(); + assert!(err.contains(PROXY_AUTH_ALLOW_INSECURE), "{err}"); + + // Auxiliary settings without a proxy are fatal. + let args = UpstreamProxyArgs { + proxy_connect_by_hostname: true, + ..UpstreamProxyArgs::default() + }; + let err = UpstreamProxyConfig::from_args(&args).unwrap_err(); + assert!(err.contains("no upstream proxy"), "{err}"); + } + + #[test] + fn conventional_proxy_vars_are_ignored() { + // The sandbox creator controls these names; they must not steer the + // supervisor's operator-owned egress boundary. + assert!( + config_from(&[ + ("HTTPS_PROXY", "http://attacker:9999"), + ("HTTP_PROXY", "http://attacker:9999"), + ("ALL_PROXY", "http://attacker:9999"), + ("https_proxy", "http://attacker:9999"), + ]) + .unwrap() + .is_none() + ); + } + + #[test] + fn present_but_empty_values_are_fatal() { + // A setting the operator did not configure is absent, never empty: + // the driver only passes configured values. A present-but-blank + // value is therefore a misconfiguration and must not silently mean + // "no proxy". + for (name, value) in [ + (HTTPS_PROXY, ""), + (HTTPS_PROXY, " "), + (NO_PROXY, " "), + (PROXY_AUTH_FILE, ""), + (PROXY_AUTH_ALLOW_INSECURE, ""), + ] { + let err = config_from(&[(name, value)]).unwrap_err(); + assert!(err.contains(name), "{err}"); + assert!(err.contains("empty"), "{err}"); + } + } + + /// Shorthand: the proxy endpoint chosen for `host:443` with no resolved + /// addresses in play, or `None` when the destination dials directly. + fn proxy_endpoint<'a>(cfg: &'a UpstreamProxyConfig, host: &str) -> Option<&'a ProxyEndpoint> { + match cfg.decision(host, 443, &[]) { + ProxyDecision::Proxy(ep) => Some(ep), + ProxyDecision::Direct(_) => None, + } + } + + #[test] + fn https_proxy_parsed_with_port() { + let cfg = config_ok(&[(HTTPS_PROXY, "http://proxy.corp.com:8080")]); + let ep = proxy_endpoint(&cfg, "api.stripe.com").unwrap(); + assert_eq!(ep.display_addr(), "proxy.corp.com:8080"); + assert!(ep.proxy_authorization.is_none()); + } + + #[test] + fn scheme_less_or_port_less_proxy_url_is_fatal() { + // The accepted grammar is exactly `http://host:port`; lenient + // defaulting would let a typo silently target the wrong proxy. + for url in [ + "proxy.corp.com", + "proxy.corp.com:3128", + "http://proxy.corp.com", + ] { + let err = config_from(&[(HTTPS_PROXY, url)]).unwrap_err(); + assert!(err.contains(HTTPS_PROXY), "{url}: {err}"); + assert!(err.contains("explicit"), "{url}: {err}"); + } + } + + // -- Fail-closed configuration validation -- + // + // Present-but-invalid settings must be fatal, never silently treated + // as unset: a typo must not downgrade the operator's egress boundary + // to direct dialing or unauthenticated proxy access. + + #[test] + fn tls_and_socks_proxies_are_fatal() { + for url in ["https://proxy:443", "socks5://proxy:1080"] { + let err = config_from(&[(HTTPS_PROXY, url)]).unwrap_err(); + assert!(err.contains(HTTPS_PROXY), "{err}"); + assert!(err.contains("scheme"), "{err}"); + } + } + + #[test] + fn url_userinfo_is_fatal_not_used_as_credentials() { + // Inline credentials in the URL must never become the proxy auth; + // credentials come only from the auth file. Matching the compute + // driver, a URL that embeds them is rejected outright. + let err = config_from(&[(HTTPS_PROXY, "http://user:secret@proxy:8080")]).unwrap_err(); + assert!(err.contains(HTTPS_PROXY), "{err}"); + assert!( + !err.contains("secret"), + "error must not leak the credential: {err}" + ); + } + + #[test] + fn malformed_proxy_address_is_fatal() { + let err = config_from(&[(HTTPS_PROXY, "http://proxy:notaport")]).unwrap_err(); + assert!(err.contains(HTTPS_PROXY), "{err}"); + // A path/query/fragment addresses an endpoint, not a proxy; it is + // rejected rather than silently discarded. + for url in [ + "http://proxy:8080/path", + "http://proxy:8080?x=1", + "http://proxy:8080#frag", + ] { + let err = config_from(&[(HTTPS_PROXY, url)]).unwrap_err(); + assert!(err.contains(HTTPS_PROXY), "{url}: {err}"); + } + } + + #[test] + fn unreadable_auth_file_is_fatal() { + let err = config_from(&[ + (HTTPS_PROXY, "http://proxy.corp.com:8080"), + (PROXY_AUTH_FILE, "/nonexistent/upstream-proxy-auth"), + (PROXY_AUTH_ALLOW_INSECURE, "true"), + ]) + .unwrap_err(); + assert!(err.contains("auth file"), "{err}"); + } + + #[test] + fn oversized_auth_file_is_fatal() { + // The supervisor uses the same bounded reader as the driver, so an + // oversized credential file is rejected rather than read unbounded. + let file = tempfile::NamedTempFile::new().unwrap(); + std::fs::write(file.path(), vec![b'a'; 8192]).unwrap(); + let path = file.path().to_str().unwrap().to_string(); + let err = config_from(&[ + (HTTPS_PROXY, "http://proxy.corp.com:8080"), + (PROXY_AUTH_FILE, &path), + (PROXY_AUTH_ALLOW_INSECURE, "true"), + ]) + .unwrap_err(); + assert!(err.contains("limit"), "{err}"); + } + + #[test] + fn auth_file_without_insecure_acknowledgement_is_fatal() { + // Basic auth over the plain-TCP proxy connection is readable on the + // network path; sending it requires the explicit opt-in. + let err = config_from(&[ + (HTTPS_PROXY, "http://proxy.corp.com:8080"), + (PROXY_AUTH_FILE, "/etc/openshell/auth/upstream-proxy"), + ]) + .unwrap_err(); + assert!(err.contains(PROXY_AUTH_ALLOW_INSECURE), "{err}"); + assert!(err.contains("cleartext"), "{err}"); + } + + #[test] + fn invalid_insecure_acknowledgement_value_is_fatal() { + for value in ["false", "yes", "1", "TRUE"] { + let err = config_from(&[ + (HTTPS_PROXY, "http://proxy.corp.com:8080"), + (PROXY_AUTH_FILE, "/etc/openshell/auth/upstream-proxy"), + (PROXY_AUTH_ALLOW_INSECURE, value), + ]) + .unwrap_err(); + assert!(err.contains(PROXY_AUTH_ALLOW_INSECURE), "{value}: {err}"); + } + } + + #[test] + fn insecure_acknowledgement_without_auth_file_is_fatal() { + let err = config_from(&[ + (HTTPS_PROXY, "http://proxy.corp.com:8080"), + (PROXY_AUTH_ALLOW_INSECURE, "true"), + ]) + .unwrap_err(); + assert!(err.contains(PROXY_AUTH_ALLOW_INSECURE), "{err}"); + assert!(err.contains(PROXY_AUTH_FILE), "{err}"); + } + + #[test] + fn malformed_auth_file_credential_is_fatal() { + // Empty, header-injecting, and non-`user:pass` credentials are all + // rejected by the parser shared with the compute driver. + for credential in [" ", "user:pa\r\nss", "userpass", ":pass"] { + let file = tempfile::NamedTempFile::new().unwrap(); + std::fs::write(file.path(), credential).unwrap(); + let path = file.path().to_str().unwrap().to_string(); + let err = config_from(&[ + (HTTPS_PROXY, "http://proxy.corp.com:8080"), + (PROXY_AUTH_FILE, &path), + (PROXY_AUTH_ALLOW_INSECURE, "true"), + ]) + .unwrap_err(); + assert!(err.contains("auth file"), "{err}"); + assert!( + !err.contains("pa\r\nss"), + "error must not leak the credential: {err}" + ); + } + } + + #[test] + fn auxiliary_settings_without_proxy_are_fatal() { + // An auth file or NO_PROXY list only makes sense relative to a proxy + // boundary the operator believed was in effect. + for (name, value) in [ + (PROXY_AUTH_FILE, "/etc/openshell/auth/upstream-proxy"), + (PROXY_AUTH_ALLOW_INSECURE, "true"), + (NO_PROXY, "*.svc.cluster.local"), + ] { + let err = config_from(&[(name, value)]).unwrap_err(); + assert!(err.contains(name), "{err}"); + assert!(err.contains("no upstream proxy"), "{err}"); + } + } + + #[test] + fn auth_file_credentials_are_applied_to_the_endpoint() { + let file = tempfile::NamedTempFile::new().unwrap(); + std::fs::write(file.path(), "user:secret\n").unwrap(); + let path = file.path().to_str().unwrap().to_string(); + let cfg = config_ok(&[ + (HTTPS_PROXY, "http://proxy:8080"), + (PROXY_AUTH_FILE, &path), + (PROXY_AUTH_ALLOW_INSECURE, "true"), + ]); + let expected = format!( + "Basic {}", + base64::engine::general_purpose::STANDARD.encode("user:secret") + ); + let ep = proxy_endpoint(&cfg, "example.com").unwrap(); + assert_eq!(ep.proxy_authorization.as_deref(), Some(expected.as_str())); + } + + #[test] + fn basic_auth_header_encodes_and_rejects_malformed_credentials() { + assert_eq!( + basic_auth_header("user:p@ss").as_deref(), + Ok(format!( + "Basic {}", + base64::engine::general_purpose::STANDARD.encode("user:p@ss") + ) + .as_str()) + ); + assert!(basic_auth_header(" ").is_err()); + assert!(basic_auth_header("user:pa\r\nss").is_err()); + assert!(basic_auth_header("user:pa\nInjected: header").is_err()); + assert!(basic_auth_header("no-separator").is_err()); + } + + #[test] + fn debug_output_hides_credentials() { + let mut cfg = config_ok(&[(HTTPS_PROXY, "http://proxy:8080")]); + cfg.https.proxy_authorization = Some(basic_auth_header("user:secret").unwrap()); + let debug = format!("{cfg:?}"); + assert!(!debug.contains("secret")); + assert!(!cfg.summary().contains("secret")); + } + + #[test] + fn ipv6_proxy_address_parses() { + let cfg = config_ok(&[(HTTPS_PROXY, "http://[fd00::1]:8080")]); + let ep = proxy_endpoint(&cfg, "example.com").unwrap(); + assert_eq!(ep.display_addr(), "fd00::1:8080"); + } + + // -- NO_PROXY matching -- + + fn no_proxy_cfg(no_proxy: &str) -> UpstreamProxyConfig { + config_ok(&[(HTTPS_PROXY, "http://proxy:8080"), (NO_PROXY, no_proxy)]) + } + + /// Hostname-level bypass check at an arbitrary port with no resolved + /// addresses in play. + fn bypasses(cfg: &UpstreamProxyConfig, host: &str) -> bool { + bypasses_port(cfg, host, 443) + } + + fn bypasses_port(cfg: &UpstreamProxyConfig, host: &str, port: u16) -> bool { + matches!(cfg.decision(host, port, &[]), ProxyDecision::Direct(_)) + } + + fn bypasses_with(cfg: &UpstreamProxyConfig, host: &str, resolved: &[SocketAddr]) -> bool { + matches!(cfg.decision(host, 443, resolved), ProxyDecision::Direct(_)) + } + + fn sock(ip: &str, port: u16) -> SocketAddr { + SocketAddr::new(ip.parse().unwrap(), port) + } + + #[test] + fn no_proxy_domain_suffix_matches_host_and_subdomains() { + let cfg = no_proxy_cfg("corp.com,other.example"); + assert!(bypasses(&cfg, "corp.com")); + assert!(bypasses(&cfg, "api.corp.com")); + assert!(!bypasses(&cfg, "notcorp.com")); + assert!(!bypasses(&cfg, "corp.com.evil.io")); + } + + #[test] + fn no_proxy_leading_dot_and_wildcard_prefix_are_equivalent() { + for entry in [".svc.cluster.local", "*.svc.cluster.local"] { + let cfg = no_proxy_cfg(entry); + assert!( + bypasses(&cfg, "kubernetes.default.svc.cluster.local"), + "{entry}" + ); + assert!(!bypasses(&cfg, "example.com"), "{entry}"); + } + } + + #[test] + fn no_proxy_cidr_matches_ip_literals() { + let cfg = no_proxy_cfg("10.96.0.0/12"); + assert!(bypasses(&cfg, "10.96.0.1")); + assert!(bypasses(&cfg, "10.100.20.30")); + assert!(!bypasses(&cfg, "10.200.0.9")); + assert!(!bypasses(&cfg, "93.184.216.34")); + } + + #[test] + fn no_proxy_exact_ip_matches() { + let cfg = no_proxy_cfg("192.168.1.5"); + assert!(bypasses(&cfg, "192.168.1.5")); + assert!(!bypasses(&cfg, "192.168.1.6")); + } + + #[test] + fn no_proxy_wildcard_bypasses_everything() { + let cfg = no_proxy_cfg("*"); + assert!(bypasses(&cfg, "example.com")); + } + + #[test] + fn no_proxy_port_qualifier_limits_bypass_to_that_port() { + // `internal.corp:8443` documents a bypass for one port; broadening + // it to every port would bypass the proxy for traffic the operator + // never excluded. + let cfg = no_proxy_cfg("internal.corp:8443"); + assert!(bypasses_port(&cfg, "internal.corp", 8443)); + assert!(bypasses_port(&cfg, "svc.internal.corp", 8443)); + assert!(!bypasses_port(&cfg, "internal.corp", 443)); + assert!(!bypasses_port(&cfg, "svc.internal.corp", 80)); + } + + #[test] + fn no_proxy_port_qualifier_applies_to_ip_and_cidr_entries() { + let cfg = no_proxy_cfg("192.168.1.5:8443,10.96.0.0/12:6443"); + assert!(bypasses_port(&cfg, "192.168.1.5", 8443)); + assert!(!bypasses_port(&cfg, "192.168.1.5", 443)); + assert!(bypasses_port(&cfg, "10.96.0.1", 6443)); + assert!(!bypasses_port(&cfg, "10.96.0.1", 443)); + } + + #[test] + fn no_proxy_invalid_port_qualifier_is_not_stripped() { + // A trailing qualifier that is not a valid port stays part of the + // pattern instead of silently widening the entry to every port. + let cfg = no_proxy_cfg("internal.corp:99999"); + assert!(!bypasses(&cfg, "internal.corp")); + } + + #[test] + fn no_proxy_cidr_matches_resolved_addresses_of_hostnames() { + // The operator's `10.96.0.0/12` bypass covers cluster-internal + // destinations however they are named; a hostname whose validated + // resolution lands in the range must dial directly. + let cfg = no_proxy_cfg("10.96.0.0/12"); + let inside = sock("10.96.0.7", 443); + match cfg.decision("svc.internal", 443, &[inside]) { + ProxyDecision::Direct(addrs) => assert_eq!(addrs, vec![inside]), + ProxyDecision::Proxy(ep) => panic!("expected direct dial, got proxy {ep:?}"), + } + // Resolution outside the range keeps the proxy. + assert!(matches!( + cfg.decision("example.com", 443, &[sock("93.184.216.34", 443)]), + ProxyDecision::Proxy(_) + )); + } + + #[test] + fn no_proxy_resolved_address_match_limits_direct_dial_to_matching_addrs() { + // Split resolution: only the addresses inside the bypassed range may + // be dialed directly; the others are not covered by the operator's + // exclusion and must not ride along. + let cfg = no_proxy_cfg("10.96.0.0/12"); + let inside = sock("10.96.0.7", 443); + let outside = sock("93.184.216.34", 443); + match cfg.decision("svc.internal", 443, &[outside, inside]) { + ProxyDecision::Direct(addrs) => assert_eq!(addrs, vec![inside]), + ProxyDecision::Proxy(ep) => panic!("expected direct dial, got proxy {ep:?}"), + } + } + + #[test] + fn no_proxy_ip_entry_matches_resolved_addresses() { + let cfg = no_proxy_cfg("10.0.0.5"); + let matching = sock("10.0.0.5", 443); + match cfg.decision("db.internal", 443, &[matching, sock("10.0.0.6", 443)]) { + ProxyDecision::Direct(addrs) => assert_eq!(addrs, vec![matching]), + ProxyDecision::Proxy(ep) => panic!("expected direct dial, got proxy {ep:?}"), + } + } + + #[test] + fn no_proxy_bracketed_ipv6_entry_honors_port_qualifier() { + // The colons of an IPv6 literal must not be misread as a port + // qualifier; only the bracketed form can carry one. + let cfg = no_proxy_cfg("[fd00::1]:8443"); + assert!(bypasses_port(&cfg, "fd00::1", 8443)); + assert!(bypasses_port(&cfg, "[fd00::1]", 8443)); + assert!(!bypasses_port(&cfg, "fd00::1", 443)); + assert!(!bypasses_port(&cfg, "fd00::2", 8443)); + + // A bare IPv6 entry keeps every-port semantics. + let cfg = no_proxy_cfg("fd00::1"); + assert!(bypasses_port(&cfg, "fd00::1", 8443)); + assert!(bypasses_port(&cfg, "fd00::1", 443)); + } + + #[test] + fn no_proxy_ipv6_cidr_matches_resolved_addresses_of_hostnames() { + let cfg = no_proxy_cfg("fd00::/8"); + // An IPv6-literal host inside the range bypasses at hostname level. + assert!(bypasses(&cfg, "fd00::7")); + assert!(!bypasses(&cfg, "2001:db8::1")); + + // A hostname resolving into the range dials directly, restricted to + // the resolved addresses the entry contains. + let inside = sock("fd00::42", 443); + let outside = sock("2001:db8::1", 443); + match cfg.decision("svc.internal", 443, &[outside, inside]) { + ProxyDecision::Direct(addrs) => assert_eq!(addrs, vec![inside]), + ProxyDecision::Proxy(ep) => panic!("expected direct dial, got proxy {ep:?}"), + } + } + + #[test] + fn no_proxy_ipv6_cidr_honors_port_qualifier() { + let cfg = no_proxy_cfg("fd00::/8:6443"); + assert!(bypasses_port(&cfg, "fd00::7", 6443)); + assert!(!bypasses_port(&cfg, "fd00::7", 443)); + match cfg.decision("svc.internal", 6443, &[sock("fd00::42", 6443)]) { + ProxyDecision::Direct(addrs) => assert_eq!(addrs, vec![sock("fd00::42", 6443)]), + ProxyDecision::Proxy(ep) => panic!("expected direct dial, got proxy {ep:?}"), + } + assert!(matches!( + cfg.decision("svc.internal", 443, &[sock("fd00::42", 443)]), + ProxyDecision::Proxy(_) + )); + } + + #[test] + fn no_proxy_hostname_match_authorizes_all_resolved_addresses() { + let cfg = no_proxy_cfg("internal.corp"); + let addrs = [sock("10.0.0.5", 443), sock("93.184.216.34", 443)]; + match cfg.decision("internal.corp", 443, &addrs) { + ProxyDecision::Direct(direct) => assert_eq!(direct, addrs.to_vec()), + ProxyDecision::Proxy(ep) => panic!("expected direct dial, got proxy {ep:?}"), + } + } + + #[test] + fn loopback_bypasses_without_no_proxy() { + // No NO_PROXY at all: loopback still bypasses unconditionally. + let cfg = config_ok(&[(HTTPS_PROXY, "http://proxy:8080")]); + assert!(bypasses_with(&cfg, "localhost", &[sock("127.0.0.1", 443)])); + assert!(bypasses(&cfg, "127.0.0.1")); + assert!(bypasses(&cfg, "::1")); + assert!(!bypasses(&cfg, "example.com")); + } + + /// A sandbox controls its own `/etc/hosts`, and `resolve_socket_addrs` + /// consults it before DNS, so `localhost` can resolve to any address the + /// network policy happens to allow. The name must not authorize a direct + /// dial that escapes the operator proxy — only genuinely loopback + /// resolved addresses may. + #[test] + fn spoofed_localhost_resolution_does_not_bypass_proxy() { + let cfg = config_ok(&[(HTTPS_PROXY, "http://proxy:8080")]); + assert!(!bypasses_with( + &cfg, + "localhost", + &[sock("203.0.113.10", 443)] + )); + // A mixed answer is not partially honored: one non-loopback address + // disqualifies the automatic bypass entirely. + assert!(!bypasses_with( + &cfg, + "localhost", + &[sock("127.0.0.1", 443), sock("203.0.113.10", 443)], + )); + // An empty resolution proves nothing about the destination. + assert!(!bypasses_with(&cfg, "localhost", &[])); + // Genuine loopback resolution still bypasses, including IPv6 and + // dual-stack answers. + assert!(bypasses_with(&cfg, "localhost", &[sock("127.0.0.1", 443)])); + assert!(bypasses_with(&cfg, "localhost", &[sock("::1", 443)])); + assert!(bypasses_with( + &cfg, + "localhost", + &[sock("127.0.0.1", 443), sock("::1", 443)], + )); + } + + /// Losing the automatic bypass does not disable an operator's explicit + /// `NO_PROXY` entry: the operator, not the sandbox, declares that one. + #[test] + fn spoofed_localhost_still_honors_explicit_no_proxy_entry() { + let cfg = no_proxy_cfg("localhost"); + assert!(bypasses_with( + &cfg, + "localhost", + &[sock("203.0.113.10", 443)] + )); + } + + // -- CONNECT handshake -- + + async fn fake_proxy(response: &'static str) -> (SocketAddr, tokio::task::JoinHandle) { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let handle = tokio::spawn(async move { + let (mut socket, _) = listener.accept().await.unwrap(); + let request = read_request(&mut socket).await; + socket.write_all(response.as_bytes()).await.unwrap(); + request + }); + (addr, handle) + } + + fn endpoint_for(addr: SocketAddr, auth: Option<&str>) -> ProxyEndpoint { + ProxyEndpoint { + host: addr.ip().to_string(), + port: addr.port(), + proxy_authorization: auth.map(str::to_string), + } + } + + #[tokio::test] + async fn connect_via_targets_validated_ip_by_default() { + // The default CONNECT target is a validated address, so the proxy + // performs no DNS resolution; the hostname only travels inside the + // tunnel (TLS SNI, application Host). + let (addr, handle) = fake_proxy("HTTP/1.1 200 Connection established\r\n\r\n").await; + let endpoint = endpoint_for(addr, Some("Basic dXNlcjpwYXNz")); + let stream = connect_via( + &endpoint, + "api.example.com", + 443, + ConnectTarget::Ip("93.184.216.34".parse().unwrap()), + ) + .await + .unwrap(); + drop(stream); + let request = handle.await.unwrap(); + assert!(request.starts_with("CONNECT 93.184.216.34:443 HTTP/1.1\r\n")); + assert!(request.contains("Host: 93.184.216.34:443\r\n")); + assert!( + !request.contains("api.example.com"), + "hostname must not leak into the CONNECT request in IP mode: {request}" + ); + assert!(request.contains("Proxy-Authorization: Basic dXNlcjpwYXNz\r\n")); + } + + /// Read one request's header block from a fake-proxy socket. + async fn read_request(socket: &mut TcpStream) -> String { + let mut buf = vec![0u8; 4096]; + let mut used = 0; + loop { + let n = socket.read(&mut buf[used..]).await.unwrap(); + used += n; + if n == 0 || buf[..used].windows(4).any(|w| w == b"\r\n\r\n") { + break; + } + } + String::from_utf8_lossy(&buf[..used]).into_owned() + } + + #[tokio::test] + async fn connect_via_validated_falls_back_across_validated_addresses() { + // The direct path tries every validated address; the proxied path + // must too, or a dual-stack destination whose first address is + // unreachable through the proxy fails needlessly. + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let handle = tokio::spawn(async move { + // First attempt: refuse the tunnel. + let (mut refused, _) = listener.accept().await.unwrap(); + let first = read_request(&mut refused).await; + refused + .write_all(b"HTTP/1.1 502 Bad Gateway\r\n\r\n") + .await + .unwrap(); + drop(refused); + // Second attempt: establish it. + let (mut accepted, _) = listener.accept().await.unwrap(); + let second = read_request(&mut accepted).await; + accepted + .write_all(b"HTTP/1.1 200 Connection established\r\n\r\n") + .await + .unwrap(); + (first, second, accepted) + }); + + let endpoint = endpoint_for(addr, None); + let addrs = [sock("192.0.2.1", 443), sock("192.0.2.2", 443)]; + let stream = connect_via_validated(&endpoint, "api.example.com", 443, &addrs) + .await + .unwrap(); + let (first, second, _accepted) = handle.await.unwrap(); + drop(stream); + assert!( + first.starts_with("CONNECT 192.0.2.1:443 HTTP/1.1\r\n"), + "{first}" + ); + assert!( + second.starts_with("CONNECT 192.0.2.2:443 HTTP/1.1\r\n"), + "{second}" + ); + } + + #[tokio::test] + async fn connect_via_validated_survives_a_hanging_first_attempt() { + // A proxy that accepts the CONNECT but never answers must not + // consume the whole aggregate budget: the per-address cap moves on + // to the next validated address. + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let handle = tokio::spawn(async move { + // First attempt: read the CONNECT, then hang with the socket + // held open until the client times the attempt out. + let (mut hung, _) = listener.accept().await.unwrap(); + let first = read_request(&mut hung).await; + // Second attempt: establish the tunnel. + let (mut accepted, _) = listener.accept().await.unwrap(); + let second = read_request(&mut accepted).await; + accepted + .write_all(b"HTTP/1.1 200 Connection established\r\n\r\n") + .await + .unwrap(); + drop(hung); + (first, second, accepted) + }); + + let endpoint = endpoint_for(addr, None); + let addrs = [sock("192.0.2.1", 443), sock("192.0.2.2", 443)]; + // Small real-time budget: the first attempt hangs for its fair + // share (half), then the second succeeds within the remainder. + let stream = connect_via_validated_with_budget( + &endpoint, + "api.example.com", + 443, + &addrs, + Duration::from_secs(2), + ) + .await + .unwrap(); + let (first, second, _accepted) = handle.await.unwrap(); + drop(stream); + assert!( + first.starts_with("CONNECT 192.0.2.1:443 HTTP/1.1\r\n"), + "{first}" + ); + assert!( + second.starts_with("CONNECT 192.0.2.2:443 HTTP/1.1\r\n"), + "{second}" + ); + } + + #[tokio::test] + async fn connect_via_validated_reports_failure_across_all_addresses() { + let (addr, _handle) = fake_proxy("HTTP/1.1 502 Bad Gateway\r\n\r\n").await; + let endpoint = endpoint_for(addr, None); + // Only the first attempt gets a response; the second finds the + // listener gone, and the aggregate error must say both were tried. + let addrs = [sock("192.0.2.1", 443), sock("192.0.2.2", 443)]; + let err = connect_via_validated(&endpoint, "api.example.com", 443, &addrs) + .await + .unwrap_err(); + assert!( + err.to_string().contains("all 2 validated addresses"), + "{err}" + ); + } + + #[tokio::test] + async fn connect_via_validated_rejects_empty_address_list() { + let endpoint = endpoint_for(sock("127.0.0.1", 3128), None); + let err = connect_via_validated(&endpoint, "api.example.com", 443, &[]) + .await + .unwrap_err(); + assert_eq!(err.kind(), ErrorKind::InvalidInput); + } + + #[tokio::test] + async fn validated_ip_connect_tunnels_to_upstream_tls_verified_by_hostname() { + // End-to-end composition of the SSRF-to-TLS boundary: a validated + // address is CONNECTed to the corporate proxy (never the hostname), + // the proxy tunnels to the destination, and upstream TLS is verified + // against the original hostname carried in SNI. Covers both a + // matching-hostname success and a mismatched-certificate rejection. + use crate::l7::tls; + use std::sync::{Arc, Mutex}; + use tokio::io::copy_bidirectional; + + const SERVER_HOSTNAME: &str = "upstream.example.test"; + + let _ = rustls::crypto::ring::default_provider().install_default(); + + // Trusted CA; the client config trusts it, and the fake upstream + // server presents a leaf for SERVER_HOSTNAME signed by it. + let ca = tls::SandboxCa::generate().unwrap(); + let client_config = tls::build_upstream_client_config(ca.cert_pem()); + let tls_state = Arc::new(tls::ProxyTlsState::new( + tls::CertCache::new(ca), + tls::build_upstream_client_config(""), + )); + + // Fake upstream TLS server: accepts tunneled connections and completes + // a TLS handshake presenting the SERVER_HOSTNAME cert. + let tls_listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let tls_addr = tls_listener.local_addr().unwrap(); + tokio::spawn(async move { + while let Ok((conn, _)) = tls_listener.accept().await { + let state = tls_state.clone(); + tokio::spawn(async move { + let _ = tls::tls_terminate_client(conn, &state, SERVER_HOSTNAME).await; + }); + } + }); + + // Fake corporate proxy: records each CONNECT request line and splices + // the tunnel to the upstream TLS server. + let proxy_listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let proxy_addr = proxy_listener.local_addr().unwrap(); + let connect_lines: Arc>> = Arc::new(Mutex::new(Vec::new())); + { + let connect_lines = connect_lines.clone(); + tokio::spawn(async move { + while let Ok((mut client, _)) = proxy_listener.accept().await { + let connect_lines = connect_lines.clone(); + tokio::spawn(async move { + let request = read_request(&mut client).await; + connect_lines + .lock() + .unwrap() + .push(request.lines().next().unwrap_or_default().to_string()); + client + .write_all(b"HTTP/1.1 200 Connection established\r\n\r\n") + .await + .unwrap(); + if let Ok(mut upstream) = TcpStream::connect(tls_addr).await { + let _ = copy_bidirectional(&mut client, &mut upstream).await; + } + }); + } + }); + } + + let endpoint = endpoint_for(proxy_addr, None); + + // Success: CONNECT to the validated IP, TLS verified against the + // requested hostname. + let stream = + connect_via_validated(&endpoint, SERVER_HOSTNAME, tls_addr.port(), &[tls_addr]) + .await + .unwrap(); + tls::tls_connect_upstream(stream, SERVER_HOSTNAME, &client_config) + .await + .expect("TLS must verify for the requested hostname"); + + // The proxy saw the validated IP in the CONNECT authority, never the + // hostname — the tunnel is bound to the SSRF-validated address. + { + let lines = connect_lines.lock().unwrap(); + let line = lines.last().expect("proxy received a CONNECT"); + assert!( + line.starts_with(&format!("CONNECT {}:", tls_addr.ip())), + "CONNECT must target the validated IP: {line}" + ); + assert!( + !line.contains(SERVER_HOSTNAME), + "hostname must not appear in the CONNECT authority: {line}" + ); + } + + // Mismatch: the same validated tunnel, but verifying a different + // hostname must fail — the server cert is only valid for + // SERVER_HOSTNAME, so a rebinding/split-horizon substitution cannot + // pass certificate verification. + let stream = connect_via_validated( + &endpoint, + "wrong.example.test", + tls_addr.port(), + &[tls_addr], + ) + .await + .unwrap(); + assert!( + tls::tls_connect_upstream(stream, "wrong.example.test", &client_config) + .await + .is_err(), + "TLS must reject a certificate that does not match the requested hostname" + ); + } + + #[tokio::test] + async fn connect_via_sends_hostname_on_operator_opt_in() { + let (addr, handle) = fake_proxy("HTTP/1.1 200 Connection established\r\n\r\n").await; + let endpoint = endpoint_for(addr, None); + let stream = connect_via(&endpoint, "api.example.com", 443, ConnectTarget::Hostname) + .await + .unwrap(); + drop(stream); + let request = handle.await.unwrap(); + assert!(request.starts_with("CONNECT api.example.com:443 HTTP/1.1\r\n")); + assert!(request.contains("Host: api.example.com:443\r\n")); + } + + #[tokio::test] + async fn connect_via_preserves_payload_after_connect_response() { + // The proxy's 200 response and the first tunneled bytes can arrive + // in a single read; the suffix belongs to the destination stream and + // must be replayed, not discarded. + let (addr, _handle) = + fake_proxy("HTTP/1.1 200 Connection established\r\n\r\nserver-first-payload").await; + let endpoint = endpoint_for(addr, None); + let mut stream = connect_via(&endpoint, "api.example.com", 443, ConnectTarget::Hostname) + .await + .unwrap(); + let mut payload = vec![0u8; "server-first-payload".len()]; + stream.read_exact(&mut payload).await.unwrap(); + assert_eq!(payload, b"server-first-payload"); + } + + #[tokio::test] + async fn prefixed_stream_replays_prefix_before_socket_bytes() { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let connect = tokio::spawn(async move { TcpStream::connect(addr).await.unwrap() }); + let (mut accepted, _) = listener.accept().await.unwrap(); + let dialed = connect.await.unwrap(); + + accepted.write_all(b" from-socket").await.unwrap(); + let mut stream = PrefixedStream::new(dialed, b"from-prefix".to_vec()); + let mut out = vec![0u8; "from-prefix from-socket".len()]; + stream.read_exact(&mut out).await.unwrap(); + assert_eq!(out, b"from-prefix from-socket"); + + // Writes pass through to the socket untouched by the prefix. + stream.write_all(b"reply").await.unwrap(); + let mut reply = vec![0u8; 5]; + accepted.read_exact(&mut reply).await.unwrap(); + assert_eq!(reply, b"reply"); + } + + #[tokio::test] + async fn connect_via_rejects_non_200() { + let (addr, _handle) = + fake_proxy("HTTP/1.1 407 Proxy Authentication Required\r\n\r\n").await; + let endpoint = endpoint_for(addr, None); + let err = connect_via(&endpoint, "api.example.com", 443, ConnectTarget::Hostname) + .await + .unwrap_err(); + assert!(err.to_string().contains("407"), "{err}"); + } + + #[tokio::test] + async fn connect_via_rejects_malformed_response() { + let (addr, _handle) = fake_proxy("garbage without status\r\n\r\n").await; + let endpoint = endpoint_for(addr, None); + let err = connect_via(&endpoint, "api.example.com", 443, ConnectTarget::Hostname) + .await + .unwrap_err(); + assert_eq!(err.kind(), ErrorKind::InvalidData); + } + + #[tokio::test] + async fn connect_via_ipv6_target_is_bracketed() { + // Both modes must bracket IPv6 authorities in the request line. + let (addr, handle) = fake_proxy("HTTP/1.1 200 OK\r\n\r\n").await; + let endpoint = endpoint_for(addr, None); + let _ = connect_via( + &endpoint, + "v6.example.com", + 443, + ConnectTarget::Ip("2001:db8::1".parse().unwrap()), + ) + .await + .unwrap(); + let request = handle.await.unwrap(); + assert!(request.starts_with("CONNECT [2001:db8::1]:443 HTTP/1.1\r\n")); + + let (addr, handle) = fake_proxy("HTTP/1.1 200 OK\r\n\r\n").await; + let endpoint = endpoint_for(addr, None); + let _ = connect_via(&endpoint, "2001:db8::1", 443, ConnectTarget::Hostname) + .await + .unwrap(); + let request = handle.await.unwrap(); + assert!(request.starts_with("CONNECT [2001:db8::1]:443 HTTP/1.1\r\n")); + } + + #[test] + fn connect_by_hostname_requires_exact_true() { + // Default is the validated-IP binding. + let cfg = config_ok(&[(HTTPS_PROXY, "http://proxy:8080")]); + assert!(!cfg.connect_by_hostname()); + + let cfg = config_ok(&[ + (HTTPS_PROXY, "http://proxy:8080"), + (PROXY_CONNECT_BY_HOSTNAME, "true"), + ]); + assert!(cfg.connect_by_hostname()); + + // Anything other than the exact opt-in value the driver writes is a + // misconfiguration, not a silent fallback to either mode. + for value in ["false", "yes", "1", "TRUE"] { + let err = config_from(&[ + (HTTPS_PROXY, "http://proxy:8080"), + (PROXY_CONNECT_BY_HOSTNAME, value), + ]) + .unwrap_err(); + assert!(err.contains(PROXY_CONNECT_BY_HOSTNAME), "{value}: {err}"); + } + } + + #[test] + fn connect_by_hostname_without_proxy_is_fatal() { + let err = config_from(&[(PROXY_CONNECT_BY_HOSTNAME, "true")]).unwrap_err(); + assert!(err.contains(PROXY_CONNECT_BY_HOSTNAME), "{err}"); + assert!(err.contains("no upstream proxy"), "{err}"); + } +} diff --git a/docs/reference/gateway-config.mdx b/docs/reference/gateway-config.mdx index 56f5d15348..75ac6f7382 100644 --- a/docs/reference/gateway-config.mdx +++ b/docs/reference/gateway-config.mdx @@ -391,6 +391,66 @@ sandbox_pids_limit = 2048 # but increase process churn (each check spawns a conmon subprocess). # Set to 0 to disable health checks entirely. Default: 10. health_check_interval_secs = 10 +# Corporate forward proxy for sandbox egress. When set, the in-container +# supervisor chains policy-approved TLS tunnels through this proxy with HTTP +# CONNECT instead of dialing destinations directly. Plain-HTTP requests are +# not proxied and always dial the destination directly. Only http:// proxy +# URLs in explicit http://host:port form are supported: the scheme and port +# are both required, and a URL carrying a path, query, or fragment is +# rejected rather than silently truncated. +# NO_PROXY entries (hostnames, domain suffixes, IPs, CIDRs, each with an +# optional :port qualifier) are dialed directly. A port-qualified entry only +# bypasses that destination port. IP and CIDR entries also match hostnames +# through their validated DNS resolution; such a match dials directly only +# the resolved addresses inside the entry. This is an operator-owned egress +# boundary: +# sandbox and template environment cannot override it, and the conventional +# HTTPS_PROXY/HTTP_PROXY/NO_PROXY variables a sandbox sets do not affect it. +# +# The CONNECT request sent to the proxy targets a validated resolved IP, +# not the hostname, so the proxy performs no DNS resolution of its own and +# the tunnel stays bound to the address that passed the sandbox's SSRF and +# allowed_ips validation. The hostname still travels inside the tunnel (TLS +# SNI, application Host), so destination servers behave normally. In +# split-horizon networks, point the gateway host at the corporate resolver +# so internal names validate to their internal addresses. If the proxy's +# ACLs filter on hostnames and reject IP CONNECT targets, set +# proxy_connect_by_hostname = true as a last resort: the proxy then +# resolves the name itself, so a name that resolves differently at the +# proxy (split-horizon DNS, rebinding) can reach destinations the sandbox +# policy never approved, and the proxy's own ACLs become the effective +# egress control for proxied TLS. +# +# Configuration is fail-closed: an invalid proxy URL is rejected at gateway +# startup, setting no_proxy, proxy_auth_file, or proxy_connect_by_hostname +# without a proxy URL is rejected as well, and a set-but-invalid value +# reaching a sandbox (for example an unreadable or malformed auth file) is +# fatal to that sandbox's supervisor instead of silently falling back to +# direct or unauthenticated egress. +# +# Credentials must NOT be embedded in the URL (an inline user:pass@ is +# rejected at startup, since it would be stored here and exposed in container +# metadata). Instead point proxy_auth_file at a file containing "user:pass"; +# the gateway delivers it to the supervisor through a root-only secret mount. +# The credential must use the user:pass form (non-empty user, no control +# characters); the same validation runs at sandbox-create time and in the +# supervisor, so a credential accepted here is never rejected in-container. +# Keep gateway.toml and the auth file owner-readable only (mode 0600). +# +# WARNING: the supervisor sends the credential as a Proxy-Authorization: +# Basic header over the plain-TCP connection to the http:// proxy. Basic +# auth is base64, not encryption: anyone on the network path between the +# sandbox host and the proxy can recover the credential. Because of that, +# proxy_auth_file requires the explicit acknowledgement +# proxy_auth_allow_insecure = true; without it the configuration is +# rejected at gateway startup. Only opt in when the path to the proxy is a +# trusted network segment. +# https_proxy = "http://proxy.corp.com:8080" +# no_proxy = "*.svc.cluster.local,10.0.0.0/8" +# proxy_auth_file = "/etc/openshell/secrets/proxy-auth" +# proxy_auth_allow_insecure = true +# Last resort for hostname-filtering proxy ACLs; see the warning above. +# proxy_connect_by_hostname = true ``` ### MicroVM diff --git a/docs/reference/sandbox-compute-drivers.mdx b/docs/reference/sandbox-compute-drivers.mdx index 280849b5f6..e0eec81285 100644 --- a/docs/reference/sandbox-compute-drivers.mdx +++ b/docs/reference/sandbox-compute-drivers.mdx @@ -182,6 +182,8 @@ For maintainer-level implementation details, refer to the [Podman driver README] Select Podman with `compute_drivers = ["podman"]` in `[openshell.gateway]`. Configure Podman driver values such as `socket_path`, `network_name`, `supervisor_image`, `stop_timeout_secs`, `image_pull_policy`, `grpc_endpoint`, `host_gateway_ip`, `sandbox_ssh_socket_path`, `sandbox_pids_limit`, and `guest_tls_*` in `[openshell.drivers.podman]`. +For proxy-required networks, the Podman driver also accepts the corporate egress proxy keys `https_proxy`, `no_proxy`, `proxy_auth_file`, `proxy_auth_allow_insecure`, and `proxy_connect_by_hostname`. The supervisor chains policy-approved TLS tunnels through the proxy with HTTP CONNECT instead of dialing destinations directly. See the [Gateway Configuration File](./gateway-config) reference for the full contract, including the cleartext-credential acknowledgement and the validated-IP CONNECT behavior. + On macOS with `podman machine`, the driver uses gvproxy's host-loopback IP, `192.168.127.254`, for sandbox host aliases by default. Set `host_gateway_ip` only when your Podman machine uses a non-standard host-loopback address. On Linux, an empty `host_gateway_ip` keeps Podman's `host-gateway` resolver behavior. ### Podman Driver Config Mounts diff --git a/e2e/rust/Cargo.toml b/e2e/rust/Cargo.toml index e4d99dc45c..b36a32203f 100644 --- a/e2e/rust/Cargo.toml +++ b/e2e/rust/Cargo.toml @@ -62,6 +62,11 @@ name = "podman_gateway_resume" path = "tests/podman_gateway_resume.rs" required-features = ["e2e-podman"] +[[test]] +name = "podman_corporate_proxy" +path = "tests/podman_corporate_proxy.rs" +required-features = ["e2e-podman"] + [[test]] name = "vm_gateway_resume" path = "tests/vm_gateway_resume.rs" diff --git a/e2e/rust/src/harness/container.rs b/e2e/rust/src/harness/container.rs index e4511e00b9..764ee6d0f6 100644 --- a/e2e/rust/src/harness/container.rs +++ b/e2e/rust/src/harness/container.rs @@ -182,6 +182,149 @@ impl ContainerHttpServer { } } +/// A generic support container running on the shared e2e container network. +/// +/// Unlike [`ContainerHttpServer`], this helper requires the network mode used +/// by the Docker/Podman gateway lanes (`OPENSHELL_E2E_NETWORK_NAME`), probes +/// readiness with a plain TCP connect instead of an HTTP GET (so it can host +/// non-HTTP fixtures such as forward proxies and TLS servers), and exposes the +/// container's logs and network IP for test assertions. +pub struct SupportContainer { + /// Network alias other containers on the e2e network reach this one by. + pub alias: String, + container_id: String, + network: String, + engine: ContainerEngine, +} + +impl SupportContainer { + /// Start a `python3 -c