diff --git a/Cargo.lock b/Cargo.lock index 420fdbe795..305c08903d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4878,6 +4878,7 @@ dependencies = [ "tonic", "tonic-prost", "tonic-prost-build", + "tonic-reflection", "tonic-types", "tracing", "tracing-subscriber", diff --git a/crates/openshell-cli/src/commands/provider.rs b/crates/openshell-cli/src/commands/provider.rs index b619cfb96e..2522c7db2d 100644 --- a/crates/openshell-cli/src/commands/provider.rs +++ b/crates/openshell-cli/src/commands/provider.rs @@ -3,6 +3,7 @@ use super::provider_readiness::{ ProviderMutationExpectation, ProviderWaitOptions, finish_provider_mutation, + warn_frozen_sandboxes_withholding, }; use crate::color::Colorize; use crate::commands::common::{ @@ -1784,6 +1785,8 @@ pub async fn provider_profile_import( "s" } ); + // Warnings, such as frozen sandboxes that keep their captured profile. + print_profile_diagnostics(&diagnostics); return Ok(()); } } @@ -1831,6 +1834,8 @@ pub async fn provider_profile_update( diagnostics.extend(response.diagnostics); if response.updated { println!("Updated provider profile."); + // Warnings, such as frozen sandboxes that keep their captured profile. + print_profile_diagnostics(&diagnostics); return Ok(()); } } @@ -2957,7 +2962,15 @@ pub async fn provider_update(options: ProviderUpdateOptions<'_>) -> Result<()> { "gateway did not return a provider mutation receipt; saved credentials cannot establish readiness" )); } - finish_provider_mutation( + // Only sandboxes the caller selected: this workspace and this provider. + let attached_sandboxes = response + .target_receipts + .iter() + .filter(|receipt| receipt.workspace == workspace && receipt.provider == name) + .filter_map(|receipt| receipt.desired.as_ref()) + .map(|desired| desired.sandbox.clone()) + .collect(); + let finished = finish_provider_mutation( &client, &response.mutation_id, response.target_receipts, @@ -2970,7 +2983,10 @@ pub async fn provider_update(options: ProviderUpdateOptions<'_>) -> Result<()> { }, readiness, ) - .await + .await; + // The update is saved either way. A frozen sandbox may now be cut off. + warn_frozen_sandboxes_withholding(server, tls, workspace, name, attached_sandboxes).await; + finished } pub async fn provider_delete( diff --git a/crates/openshell-cli/src/commands/provider_readiness.rs b/crates/openshell-cli/src/commands/provider_readiness.rs index 114b4c558a..157139c3c8 100644 --- a/crates/openshell-cli/src/commands/provider_readiness.rs +++ b/crates/openshell-cli/src/commands/provider_readiness.rs @@ -19,6 +19,8 @@ use std::time::Duration; use tokio::time::Instant; const PROVIDER_WAIT_CONCURRENCY: usize = 16; +/// Bound on one freeze read behind the frozen-sandbox warning. +const FROZEN_WARNING_TIMEOUT: Duration = Duration::from_secs(10); /// Output and deadline choices shared by provider mutation and status commands. #[derive(Clone, Copy)] @@ -256,6 +258,62 @@ async fn wait_for_mutation_statuses( results.into_iter().map(|(_, result)| result).collect() } +/// Name the frozen sandboxes that no longer receive this provider's credentials. +/// +/// A frozen sandbox keeps the provider authorization it captured. A provider +/// change that no longer matches it succeeds, and the gateway then withholds +/// the credentials from that sandbox. The readiness reason is the generic +/// `credentials_withheld`, so say which sandbox, why, and what repairs it. +/// Best effort: the mutation or status this follows has already succeeded. +pub(super) async fn warn_frozen_sandboxes_withholding( + server: &str, + tls: &TlsOptions, + workspace: &str, + provider: &str, + sandboxes: Vec, +) { + if sandboxes.is_empty() { + return; + } + let Ok(Some(client)) = crate::tls::frozen_policies_client(server, tls).await else { + return; + }; + let mut warnings = stream::iter(sandboxes.into_iter().map(|sandbox| { + let mut client = client.clone(); + async move { + // Best effort: a slow gateway costs the warning, not the command. + let state = tokio::time::timeout( + FROZEN_WARNING_TIMEOUT, + client.get_policy(openshell_core::proto::GetFrozenSandboxPolicyRequest { + workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), + name: sandbox.clone(), + }), + ) + .await + .ok()? + .ok()? + .into_inner(); + let withheld = state + .withheld_providers + .into_iter() + .filter(|withheld| withheld.provider == provider) + .collect::>(); + let line = crate::run::withheld_provider_lines(&withheld) + .into_iter() + .next()?; + Some(format!("frozen sandbox '{workspace}/{sandbox}': {line}")) + } + })) + .buffer_unordered(PROVIDER_WAIT_CONCURRENCY) + .filter_map(|warning| async move { warning }) + .collect::>() + .await; + warnings.sort(); + for warning in warnings { + eprintln!("Warning: {warning}"); + } +} + /// Show desired/observed provider state, optionally waiting for that exact state. pub async fn sandbox_provider_status( server: &str, @@ -313,6 +371,10 @@ pub async fn sandbox_provider_status( }; let complete = result.complete; print_statuses(&mutation_id, &[result], options.output)?; + // The readiness state lags until the supervisor reports. The freeze + // record already knows whether this provider is withheld. + warn_frozen_sandboxes_withholding(server, tls, workspace, provider, vec![name.to_string()]) + .await; if options.wait && !complete { return Err(miette!( "provider readiness wait did not complete; inspect the reported outcome" diff --git a/crates/openshell-cli/src/main.rs b/crates/openshell-cli/src/main.rs index 8b362d6328..b114e797b5 100644 --- a/crates/openshell-cli/src/main.rs +++ b/crates/openshell-cli/src/main.rs @@ -1608,6 +1608,14 @@ enum SandboxCommands { #[arg(long, value_hint = ValueHint::FilePath)] policy: Option, + /// Freeze the first accepted policy and provider authorization until the sandbox is deleted. + /// + /// Policy edits, proposal approvals, and provider attach or detach + /// then fail; recreate the sandbox to change them. Every gateway + /// replica must support frozen policies. + #[arg(long)] + frozen: bool, + /// Forward a local port to the sandbox before the initial command or shell starts. /// Accepts [`bind_address`:]port (e.g. 8080, 0.0.0.0:8080). Keeps the sandbox alive. #[arg(long, conflicts_with = "no_keep")] @@ -1767,6 +1775,11 @@ enum SandboxCommands { #[arg(long)] selector: Option, + /// Show only sandboxes created with `--frozen`, with their freeze state. + /// Pages without a frozen sandbox are skipped. + #[arg(long)] + frozen: bool, + /// Output format. #[arg(short = 'o', long = "output", value_enum, default_value_t = OutputFormat::Table, conflicts_with_all = ["ids", "names"])] output: OutputFormat, @@ -3637,6 +3650,7 @@ async fn run_async() -> Result<()> { driver_config_json, providers, policy, + frozen, forward, expose, expose_authorization_mode, @@ -3753,6 +3767,7 @@ async fn run_async() -> Result<()> { restart_policy: &restart_policy, provision_timeout_secs: timeout.map(std::num::NonZeroU32::get), create_retry_timeout_secs, + frozen, }, &cli.workspace, &tls, @@ -3837,6 +3852,7 @@ async fn run_async() -> Result<()> { ids, names, selector, + frozen, output, all_workspaces, } => { @@ -3847,6 +3863,11 @@ async fn run_async() -> Result<()> { ids, names, selector.as_deref(), + if frozen { + run::SandboxListFilter::Frozen + } else { + run::SandboxListFilter::All + }, output.as_str(), &cli.workspace, all_workspaces, @@ -6741,6 +6762,38 @@ mod tests { } } + #[test] + fn sandbox_create_frozen_supports_inline_and_named_templates() { + for args in [ + vec!["openshell", "sandbox", "create", "--frozen"], + vec![ + "openshell", + "sandbox", + "create", + "--template", + "agent", + "--frozen", + ], + ] { + let cli = Cli::try_parse_from(args).unwrap(); + assert!(matches!( + cli.command, + Some(Commands::Sandbox { + command: Some(SandboxCommands::Create { frozen: true, .. }), + .. + }) + )); + } + let cli = Cli::try_parse_from(["openshell", "sandbox", "create"]).unwrap(); + assert!(matches!( + cli.command, + Some(Commands::Sandbox { + command: Some(SandboxCommands::Create { frozen: false, .. }), + .. + }) + )); + } + #[test] fn sandbox_create_restart_policy_defaults_to_never() { let cli = Cli::try_parse_from(["openshell", "sandbox", "create"]).unwrap(); diff --git a/crates/openshell-cli/src/run.rs b/crates/openshell-cli/src/run.rs index bd44344b43..445ad60b41 100644 --- a/crates/openshell-cli/src/run.rs +++ b/crates/openshell-cli/src/run.rs @@ -42,7 +42,8 @@ pub use crate::commands::secret::{ use crate::color::Colorize; use crate::policy_update::build_policy_update_plan; use crate::tls::{ - GrpcClient, TlsOptions, grpc_client, owner_replica, retry_unrouted, routed_to, with_owner_hint, + FrozenPoliciesClient, GrpcClient, TlsOptions, grpc_client, owner_replica, retry_unrouted, + routed_to, with_owner_hint, }; use futures::StreamExt; use miette::{IntoDiagnostic, Result, WrapErr, miette}; @@ -440,6 +441,7 @@ async fn finalize_sandbox_create_session( /// on the function signature, following the `provider_refresh_config(server, input, tls)` /// precedent. This struct captures sandbox-specific options. #[derive(Debug)] +#[allow(clippy::struct_excessive_bools)] // Independent command-line switches. pub struct SandboxCreateConfig<'a> { pub name: Option<&'a str>, pub template: Option<&'a str>, @@ -472,6 +474,9 @@ pub struct SandboxCreateConfig<'a> { /// disables retries; `None` reads `OPENSHELL_CREATE_RETRY_TIMEOUT` or the /// 60s default. pub create_retry_timeout_secs: Option, + /// Create through the frozen-policy service, so the first accepted + /// effective policy and provider permissions stay fixed until deletion. + pub frozen: bool, } impl Default for SandboxCreateConfig<'_> { @@ -505,6 +510,7 @@ impl Default for SandboxCreateConfig<'_> { restart_policy: "never", provision_timeout_secs: None, create_retry_timeout_secs: None, + frozen: false, } } } @@ -697,13 +703,67 @@ fn create_conflict_report( miette::miette!("{message}") } +/// Send one create, through the opt-in frozen service when `frozen` is set. +/// +/// A frozen create that the gateway does not acknowledge as frozen fails: the +/// sandbox exists without the requested guarantee, so the error names it for +/// cleanup. That failure is not a lock timeout, so the retry loop surfaces it. +async fn send_create( + client: &mut GrpcClient, + frozen: Option<&mut FrozenPoliciesClient>, + request: CreateSandboxRequest, + workspace: &str, +) -> Result { + let Some(frozen) = frozen else { + return client + .create_sandbox(request) + .await + .map(tonic::Response::into_inner); + }; + let response = frozen + .create_sandbox(openshell_core::proto::CreateFrozenSandboxRequest { + workspace_scope: request.workspace_scope, + spec: request.spec, + name: request.name, + labels: request.labels, + annotations: request.annotations, + await_main_process_attachment: request.await_main_process_attachment, + workload_template: request.workload_template, + request_id: request.request_id, + service_exposures: request.service_exposures, + }) + .await? + .into_inner(); + if !response.frozen_policy.is_some_and(|state| state.requested) { + let name = response + .sandbox + .as_ref() + .map_or("unknown", ObjectName::object_name); + let id = response + .sandbox + .as_ref() + .map_or("unknown", ObjectId::object_id); + return Err(Status::failed_precondition(format!( + "gateway did not acknowledge frozen creation for sandbox '{name}' (id {id}, workspace {workspace}); inspect it before retrying and remove it with: openshell --workspace {workspace} sandbox delete {name}" + ))); + } + Ok(SandboxResponse { + sandbox: response.sandbox, + service_urls: response.service_urls, + application_service_urls: response.application_service_urls, + gateway_service_urls: response.gateway_service_urls, + }) +} + /// Send one create attempt without retrying. async fn create_sandbox_once( client: &mut GrpcClient, + frozen: Option<&mut FrozenPoliciesClient>, request: CreateSandboxRequest, + workspace: &str, ) -> Result { - match client.create_sandbox(request).await { - Ok(response) => Ok(response.into_inner()), + match send_create(client, frozen, request, workspace).await { + Ok(response) => Ok(response), Err(status) if status.code() == Code::AlreadyExists => Err(already_exists_report(&status)), Err(status) => Err(miette::miette!(status.to_string())), } @@ -717,6 +777,7 @@ async fn create_sandbox_once( /// parseable. async fn create_sandbox_with_retry( client: &mut GrpcClient, + mut frozen: Option<&mut FrozenPoliciesClient>, request: CreateSandboxRequest, workspace: &str, retry: CreateRetry, @@ -740,8 +801,8 @@ async fn create_sandbox_with_retry( loop { create_attempts += 1; let sent = Instant::now(); - match client.create_sandbox(request.clone()).await { - Ok(response) => return Ok(response.into_inner()), + match send_create(client, frozen.as_deref_mut(), request.clone(), workspace).await { + Ok(response) => return Ok(response), // A lock timeout means different things per gateway step. The // pre-record creation guard rejects before any write ran, so the // request stays repeatable as-is. The SSH identity step also @@ -1051,6 +1112,7 @@ pub async fn sandbox_create( restart_policy, provision_timeout_secs, create_retry_timeout_secs, + frozen, } = config; if editor.is_some() && !command.is_empty() { @@ -1235,14 +1297,34 @@ pub async fn sandbox_create( .collect(), }; + let mut frozen_client = if frozen { + Some( + crate::tls::frozen_policies_client(&effective_server, &effective_tls) + .await? + .ok_or_else(|| { + miette!( + "this gateway does not support frozen sandbox policies; no sandbox was created. Upgrade every gateway replica to a release that supports --frozen, then retry" + ) + })?, + ) + } else { + None + }; let create_retry_timeout = resolve_create_retry_timeout(create_retry_timeout_secs); // Box the attempts: the retry loop carries enough state that inlining it // pushes every caller's future past clippy's size lint. let response = if create_retry_timeout.is_zero() { - Box::pin(create_sandbox_once(&mut client, request)).await? + Box::pin(create_sandbox_once( + &mut client, + frozen_client.as_mut(), + request, + workspace, + )) + .await? } else { Box::pin(create_sandbox_with_retry( &mut client, + frozen_client.as_mut(), request, workspace, CreateRetry::new(create_retry_timeout, create_retry_seed()), @@ -1580,6 +1662,38 @@ pub async fn sandbox_create( drop(stream); drop(client); + // `--frozen` promises a captured policy, and Ready alone does not + // prove one. Confirm it, or fail before anything runs unfrozen. + let frozen_state = if frozen { + let state = frozen_policy_state( + &effective_server, + &sandbox_name, + workspace, + &effective_tls, + ) + .await + .wrap_err_with(|| { + format!( + "sandbox '{sandbox_name}' is ready but its freeze state could not be read; inspect it with: openshell --workspace {workspace} sandbox get {sandbox_name}, or remove it with: openshell --workspace {workspace} sandbox delete {sandbox_name}" + ) + })?; + let Some(policy) = state.policy.as_ref() else { + return Err(miette!( + "sandbox '{sandbox_name}' is ready but its policy is not frozen yet; inspect it with: openshell --workspace {workspace} sandbox get {sandbox_name}, or remove it with: openshell --workspace {workspace} sandbox delete {sandbox_name}" + )); + }; + if !structured_output { + eprintln!( + " {} Policy frozen (hash: {})", + "\u{2713}".green().bold(), + policy.policy_hash, + ); + } + Some(state) + } else { + None + }; + let upload_count = uploads.len(); for (idx, ((local_path, sandbox_path, _), upload_plan)) in uploads.iter().zip(upload_plans).enumerate() @@ -1661,6 +1775,9 @@ pub async fn sandbox_create( if structured_output { let mut value = sandbox_to_json(&last_sandbox); + if let Some(state) = frozen_state.as_ref() { + append_frozen_policy_json(&mut value, state)?; + } if let Some(object) = value.as_object_mut() { object.insert("service_urls".to_string(), serde_json::json!(service_urls)); } @@ -2207,7 +2324,9 @@ where return Ok(()); } - let detail_json = sandbox_detail_to_json(&sandbox, &config)?; + let frozen_state = frozen_policy_state(server, name, workspace, tls).await?; + let mut detail_json = sandbox_detail_to_json(&sandbox, &config)?; + append_frozen_policy_json(&mut detail_json, &frozen_state)?; if crate::output::print_output_single(output, &detail_json, Clone::clone)? { return Ok(()); } @@ -2227,6 +2346,27 @@ where println!(" {} {}", "Id:".dimmed(), id); println!(" {} {}", "Name:".dimmed(), name); println!(" {} {}", "Phase:".dimmed(), phase_name(sandbox.phase())); + if let Some(frozen) = frozen_state.policy.as_ref() { + println!(" {} frozen", "Policy state:".dimmed()); + println!(" {} {}", "Frozen hash:".dimmed(), frozen.policy_hash); + if let Some(time) = &frozen.frozen_time { + println!(" {} {}", "Frozen at:".dimmed(), time); + } + if !frozen.providers.is_empty() { + let providers = frozen + .providers + .iter() + .map(|provider| format!("{} ({})", provider.provider, provider.r#type)) + .collect::>() + .join(", "); + println!(" {} {providers}", "Frozen providers:".dimmed()); + } + for line in withheld_provider_lines(&frozen_state.withheld_providers) { + println!(" {} {line}", "Withheld:".dimmed()); + } + } else if frozen_state.requested { + println!(" {} pending freeze", "Policy state:".dimmed()); + } if let Some(status) = sandbox.status.as_ref() { for condition in &status.conditions { if matches!( @@ -2364,11 +2504,7 @@ where println!( " {} {}", "Policy source:".dimmed(), - if policy_from_global { - "global" - } else { - "sandbox" - } + policy_source_name(config.policy_source) ); let revision = if policy_from_global { if config.global_policy_version > 0 { @@ -3389,6 +3525,14 @@ async fn sandbox_exec_streaming_grpc( Ok(exit_code) } +/// Which sandboxes `sandbox list` shows. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SandboxListFilter { + All, + /// Only sandboxes created with `--frozen`, with their freeze state. + Frozen, +} + /// List sandboxes. #[allow(clippy::too_many_arguments)] pub async fn sandbox_list( @@ -3398,28 +3542,96 @@ pub async fn sandbox_list( ids_only: bool, names_only: bool, label_selector: Option<&str>, + filter: SandboxListFilter, output: &str, workspace: &str, all_workspaces: bool, tls: &TlsOptions, ) -> Result<()> { - let mut client = grpc_client(server, tls).await?; - - let response = client - .list_sandboxes(ListSandboxesRequest { - page_size, - page_token: page_token.to_string(), - label_selector: label_selector.unwrap_or("").to_string(), - workspace_scope: Some(if all_workspaces { - openshell_core::proto::all_workspaces_selector() - } else { - openshell_core::proto::workspace_selector(workspace) - }), - }) - .await - .into_diagnostic()?; + let frozen_only = filter == SandboxListFilter::Frozen; + let workspace_scope = Some(if all_workspaces { + openshell_core::proto::all_workspaces_selector() + } else { + openshell_core::proto::workspace_selector(workspace) + }); + let label_selector = label_selector.unwrap_or("").to_string(); + // `--frozen` keeps the sandboxes of a page that were created frozen and + // skips a page that has none, so an empty answer means none remain. The + // freeze state of each sandbox is keyed by workspace and name. + let (response, frozen) = if frozen_only { + let mut client = crate::tls::frozen_policies_client(server, tls) + .await? + .ok_or_else(|| miette!("this gateway does not support frozen sandbox policies"))?; + let mut page_token = page_token.to_string(); + loop { + let response = match client + .list_sandboxes(openshell_core::proto::ListFrozenSandboxesRequest { + workspace_scope: workspace_scope.clone(), + page_size, + page_token, + label_selector: label_selector.clone(), + }) + .await + { + Ok(response) => response.into_inner(), + // A gateway built before the list RPC still has the service. + Err(status) if status.code() == Code::Unimplemented => { + return Err(miette!( + "this gateway cannot list frozen sandboxes; upgrade it, or check one sandbox with: openshell sandbox get " + )); + } + Err(status) => return Err(status).into_diagnostic(), + }; + let frozen = response + .frozen_sandboxes + .into_iter() + .map(|summary| { + ( + (summary.workspace.clone(), summary.sandbox.clone()), + summary, + ) + }) + .collect::>(); + let mut sandboxes = response.sandboxes; + sandboxes.retain(|sandbox| { + frozen.contains_key(&( + sandbox.object_workspace().to_string(), + sandbox.object_name().to_string(), + )) + }); + if sandboxes.is_empty() && !response.next_page_token.is_empty() { + page_token = response.next_page_token; + continue; + } + break ( + openshell_core::proto::ListSandboxesResponse { + sandboxes, + next_page_token: response.next_page_token, + }, + frozen, + ); + } + } else { + let mut client = grpc_client(server, tls).await?; + let response = client + .list_sandboxes(ListSandboxesRequest { + page_size, + page_token: page_token.to_string(), + label_selector, + workspace_scope, + }) + .await + .into_diagnostic()? + .into_inner(); + (response, HashMap::new()) + }; + let summary = |sandbox: &Sandbox| { + frozen.get(&( + sandbox.object_workspace().to_string(), + sandbox.object_name().to_string(), + )) + }; - let response = response.into_inner(); let next_page_token = response.next_page_token; let sandboxes = response.sandboxes; @@ -3428,7 +3640,30 @@ pub async fn sandbox_list( "sandboxes", &sandboxes, &next_page_token, - sandbox_to_json, + |sandbox| { + let mut value = sandbox_to_json(sandbox); + if let (Some(summary), Some(object)) = (summary(sandbox), value.as_object_mut()) { + // The same keys `sandbox get` prints, without the policy body. + let captured = summary.policy_hash.is_some(); + object.insert("frozen".into(), serde_json::json!(captured)); + object.insert( + "policy_state".into(), + serde_json::json!(if captured { "frozen" } else { "pending" }), + ); + object.insert( + "frozen_policy".into(), + if captured { + serde_json::json!({ + "policy_hash": summary.policy_hash, + "frozen_time": summary.frozen_time.as_ref().map(ToString::to_string), + }) + } else { + serde_json::Value::Null + }, + ); + } + value + }, )? { return Ok(()); } @@ -3436,7 +3671,11 @@ pub async fn sandbox_list( if sandboxes.is_empty() { if !ids_only && !names_only { - println!("No sandboxes found."); + if frozen_only { + println!("No frozen sandboxes found."); + } else { + println!("No sandboxes found."); + } } return Ok(()); } @@ -3478,10 +3717,19 @@ pub async fn sandbox_list( 0 }; + // `--frozen` adds the freeze state after the phase. + let policy_header = if frozen_only { + format!(" {}", "POLICY".bold()) + } else { + String::new() + }; + // The widest phase name, so the trailing column stays aligned. + let phase_width = if frozen_only { 12 } else { 0 }; + // Print header if all_workspaces { println!( - "{: &'static str { + match PolicySource::try_from(source) { + Ok(PolicySource::Global) => "global", + _ => "sandbox", + } +} + fn configuration_failure_message(sandbox: &Sandbox) -> Option<&str> { sandbox .status @@ -3551,6 +3813,166 @@ fn configuration_failure_message(sandbox: &Sandbox) -> Option<&str> { .filter(|message| !message.is_empty()) } +async fn frozen_policy_state( + server: &str, + name: &str, + workspace: &str, + tls: &TlsOptions, +) -> Result { + let Some(mut client) = crate::tls::frozen_policies_client(server, tls).await? else { + return Ok(openshell_core::proto::FrozenSandboxPolicyState::default()); + }; + client + .get_policy(openshell_core::proto::GetFrozenSandboxPolicyRequest { + workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), + name: name.to_string(), + }) + .await + .map(tonic::Response::into_inner) + .into_diagnostic() +} + +/// `pending` until the first accepted configuration is captured, then `frozen`. +/// `None` for a sandbox that was not created frozen. +fn frozen_policy_state_name( + state: &openshell_core::proto::FrozenSandboxPolicyState, +) -> Option<&'static str> { + match (state.requested, state.policy.is_some()) { + (false, _) => None, + (true, false) => Some("pending"), + (true, true) => Some("frozen"), + } +} + +fn frozen_provider_change_name( + change: openshell_core::proto::FrozenProviderChange, +) -> &'static str { + use openshell_core::proto::FrozenProviderChange; + match change { + FrozenProviderChange::Replaced => "replaced", + FrozenProviderChange::Type => "type_changed", + FrozenProviderChange::ProfileScope => "profile_scope_changed", + FrozenProviderChange::Config => "config_changed", + FrozenProviderChange::Authorization => "authorization_changed", + FrozenProviderChange::Unspecified => "changed", + } +} + +/// One line per withheld provider: what changed and the repair that works. +/// Authorizing the provider again never restores a frozen sandbox. +pub(crate) fn withheld_provider_lines( + withheld: &[openshell_core::proto::FrozenSandboxWithheldProvider], +) -> Vec { + use openshell_core::proto::FrozenProviderChange; + withheld + .iter() + .map(|withheld| { + let (what, repair) = match withheld.change() { + FrozenProviderChange::Config => ( + "its configuration changed after the freeze", + "restore the frozen configuration, or delete and recreate the sandbox", + ), + FrozenProviderChange::Replaced => ( + "it was deleted or replaced after the freeze", + "delete and recreate the sandbox", + ), + FrozenProviderChange::Authorization => ( + "its authorization changed after the freeze", + "delete and recreate the sandbox", + ), + FrozenProviderChange::Type => ( + "its type changed after the freeze", + "restore the frozen type, or delete and recreate the sandbox", + ), + FrozenProviderChange::ProfileScope => ( + "its profile now comes from another scope", + "restore the profile scope it had at the freeze, or delete and recreate the sandbox", + ), + FrozenProviderChange::Unspecified => ( + "it changed after the freeze", + "delete and recreate the sandbox", + ), + }; + format!( + "provider '{}' credentials are withheld because {what}; {repair}", + withheld.provider + ) + }) + .collect() +} + +fn append_frozen_policy_json( + value: &mut serde_json::Value, + state: &openshell_core::proto::FrozenSandboxPolicyState, +) -> Result<()> { + let Some(policy_state) = frozen_policy_state_name(state) else { + return Ok(()); + }; + let object = value.as_object_mut().expect("sandbox output is an object"); + // True only once the policy is captured, so a script that gates on it + // cannot pass while the freeze is still pending. + object.insert("frozen".into(), serde_json::json!(state.policy.is_some())); + object.insert("policy_state".into(), serde_json::json!(policy_state)); + let frozen_policy = match state.policy.as_ref() { + None => serde_json::Value::Null, + Some(policy) => { + // The captured provider authorization, with each profile in the + // shape profile commands print, without the gateway's internal ID. + let providers = policy + .providers + .iter() + .map(|provider| { + let profile = provider + .profile + .as_ref() + .map(|profile| { + openshell_providers::profile_to_json( + &openshell_providers::ProviderTypeProfile::from_proto(profile), + ) + .into_diagnostic() + .and_then(|json| { + serde_json::from_str::(&json).into_diagnostic() + }) + }) + .transpose()?; + Ok(serde_json::json!({ + "name": provider.provider, + "type": provider.r#type, + "profile_workspace": provider.profile_workspace, + "config": provider.config, + "profile": profile, + })) + }) + .collect::>>()?; + serde_json::json!({ + "version": policy.version, + "policy_hash": policy.policy_hash, + "frozen_time": policy.frozen_time.as_ref().map(ToString::to_string), + "policy_source": policy_source_name(policy.policy_source), + "global_policy_version": policy.global_policy_version, + "providers": providers, + }) + } + }; + object.insert("frozen_policy".into(), frozen_policy); + if !state.withheld_providers.is_empty() { + object.insert( + "withheld_providers".into(), + state + .withheld_providers + .iter() + .map(|withheld| { + serde_json::json!({ + "provider": withheld.provider, + "change": frozen_provider_change_name(withheld.change()), + }) + }) + .collect(), + ); + } + Ok(()) +} + fn sandbox_to_json(sandbox: &Sandbox) -> serde_json::Value { use openshell_core::proto::ConfigurationAdmissionState; @@ -3879,11 +4301,7 @@ fn sandbox_detail_to_json( ); } - let policy_source = if config.policy_source == PolicySource::Global as i32 { - "global" - } else { - "sandbox" - }; + let policy_source = policy_source_name(config.policy_source); obj.insert("policy_source".into(), serde_json::json!(policy_source)); let policy_from_global = config.policy_source == PolicySource::Global as i32; @@ -5926,6 +6344,47 @@ pub async fn sandbox_upload( // Sandbox policy commands // --------------------------------------------------------------------------- +async fn update_global_config_with_frozen_report( + server: &str, + tls: &TlsOptions, + request: UpdateConfigRequest, +) -> Result<(openshell_core::proto::UpdateConfigResponse, Vec)> { + let Some(mut client) = crate::tls::frozen_policies_client(server, tls).await? else { + let update = grpc_client(server, tls) + .await? + .update_config(request) + .await + .into_diagnostic()? + .into_inner(); + return Ok((update, Vec::new())); + }; + let response = client + .update_global_config(openshell_core::proto::UpdateFrozenGlobalConfigRequest { + workspace_scope: request.workspace_scope.clone(), + policy: request.policy.clone(), + setting_key: request.setting_key.clone(), + setting_value: request.setting_value.clone(), + delete_setting: request.delete_setting, + global: request.global, + merge_operations: request.merge_operations.clone(), + expected_resource_version: request.expected_resource_version, + annotations: request.annotations.clone(), + sandbox: request.sandbox.clone(), + request_id: request.request_id.clone(), + }) + .await; + match response { + Ok(response) => { + let response = response.into_inner(); + let update = response + .update + .ok_or_else(|| miette!("gateway returned no global configuration result"))?; + Ok((update, response.frozen_sandboxes)) + } + Err(status) => Err(status).into_diagnostic(), + } +} + pub fn sandbox_policy_lint(policy_path: &str) -> Result<()> { let policy = openshell_policy::parse_sandbox_policy_file(Path::new(policy_path))?; let size = policy.encoded_len(); @@ -5982,16 +6441,16 @@ pub async fn sandbox_policy_set_global( let policy = load_sandbox_policy(Some(policy_path))? .ok_or_else(|| miette::miette!("No policy loaded from {policy_path}"))?; - let mut client = grpc_client(server, tls).await?; - let response = client - .update_config(UpdateConfigRequest { + let (response, frozen_sandboxes) = update_global_config_with_frozen_report( + server, + tls, + UpdateConfigRequest { policy: Some(policy), global: true, ..Default::default() - }) - .await - .into_diagnostic()? - .into_inner(); + }, + ) + .await?; eprintln!( "{} Global policy configured (hash: {}, settings revision: {})", @@ -6003,6 +6462,12 @@ pub async fn sandbox_policy_set_global( }, response.settings_revision, ); + if !frozen_sandboxes.is_empty() { + eprintln!( + "Frozen sandboxes retain their policy: {}", + frozen_sandboxes.join(", ") + ); + } Ok(()) } @@ -6032,11 +6497,7 @@ pub async fn sandbox_settings_get( return Ok(()); } - let policy_source = if response.policy_source == PolicySource::Global as i32 { - "global" - } else { - "sandbox" - }; + let policy_source = policy_source_name(response.policy_source); println!("Sandbox: {name}"); println!("Config Rev: {}", response.config_revision); @@ -6108,11 +6569,7 @@ fn settings_to_json_sandbox( workspace: &str, response: &GetSandboxConfigResponse, ) -> serde_json::Value { - let policy_source = if response.policy_source == PolicySource::Global as i32 { - "global" - } else { - "sandbox" - }; + let policy_source = policy_source_name(response.policy_source); let mut settings = serde_json::Map::new(); let mut keys: Vec<_> = response.settings.keys().cloned().collect(); @@ -6241,17 +6698,17 @@ pub async fn gateway_setting_delete( ) -> Result<()> { confirm_global_setting_delete(key, yes)?; - let mut client = grpc_client(server, tls).await?; - let response = client - .update_config(UpdateConfigRequest { + let (response, frozen_sandboxes) = update_global_config_with_frozen_report( + server, + tls, + UpdateConfigRequest { setting_key: key.to_string(), delete_setting: true, global: true, ..Default::default() - }) - .await - .into_diagnostic()? - .into_inner(); + }, + ) + .await?; if response.deleted { println!( @@ -6263,6 +6720,12 @@ pub async fn gateway_setting_delete( } else { println!("{} Global setting {} not found", "!".yellow(), key); } + if !frozen_sandboxes.is_empty() { + eprintln!( + "Frozen sandboxes retain their policy: {}", + frozen_sandboxes.join(", ") + ); + } Ok(()) } @@ -6796,6 +7259,17 @@ where } else { config.version }; + // Whoever is about to edit this policy learns here that the edit will be + // refused, or that a pending freeze is about to capture it. + // The policy itself is already in hand, so a failed freeze read only + // costs the marker. + let policy_state = match frozen_policy_state(server, name, workspace, tls).await { + Ok(state) => frozen_policy_state_name(&state), + Err(error) => { + eprintln!("Warning: could not read the freeze state of sandbox '{name}': {error}"); + None + } + }; match output { "json" => { @@ -6806,6 +7280,9 @@ where obj.insert("active_version".to_string(), serde_json::json!(version)); obj.insert("hash".to_string(), serde_json::json!(config.policy_hash)); obj.insert("status".to_string(), serde_json::json!("effective")); + if let Some(policy_state) = policy_state { + obj.insert("policy_state".to_string(), serde_json::json!(policy_state)); + } obj.insert( "config_revision".to_string(), serde_json::json!(config.config_revision), @@ -6838,6 +7315,19 @@ where writeln!(stdout, "Version: {version}").into_diagnostic()?; writeln!(stdout, "Hash: {}", config.policy_hash).into_diagnostic()?; writeln!(stdout, "Status: Effective").into_diagnostic()?; + match policy_state { + Some("frozen") => writeln!( + stdout, + "Frozen: yes (delete and recreate the sandbox to change it)" + ) + .into_diagnostic()?, + Some(_) => writeln!( + stdout, + "Frozen: pending (changes still apply until the sandbox accepts its configuration)" + ) + .into_diagnostic()?, + None => {} + } writeln!(stdout, "Source: {policy_source_label}").into_diagnostic()?; writeln!(stdout, "Config rev: {}", config.config_revision).into_diagnostic()?; if config.global_policy_version > 0 { @@ -9722,6 +10212,74 @@ mod tests { ); } + #[test] + fn sandbox_json_distinguishes_pending_and_frozen_policy() { + let sandbox = Sandbox::default(); + let mut state = openshell_core::proto::FrozenSandboxPolicyState { + requested: true, + ..Default::default() + }; + let mut pending = super::sandbox_to_json(&sandbox); + super::append_frozen_policy_json(&mut pending, &state).unwrap(); + // A script that gates on `frozen` must not pass before the capture. + assert_eq!(pending["frozen"], false); + assert_eq!(pending["policy_state"], "pending"); + assert!(pending["frozen_policy"].is_null()); + state.policy = Some(openshell_core::proto::FrozenSandboxPolicy { + version: 3, + policy_hash: "accepted-hash".into(), + frozen_time: openshell_core::time::timestamp_from_millis(600_000).ok(), + policy_source: PolicySource::Global as i32, + global_policy_version: 7, + providers: vec![openshell_core::proto::FrozenSandboxProvider { + provider: "github".into(), + provider_id: "internal-id".into(), + r#type: "github".into(), + config: std::collections::HashMap::from([("region".to_string(), "eu".to_string())]), + ..Default::default() + }], + ..Default::default() + }); + state.withheld_providers = vec![openshell_core::proto::FrozenSandboxWithheldProvider { + provider: "github".into(), + change: openshell_core::proto::FrozenProviderChange::Config as i32, + }]; + super::append_frozen_policy_json(&mut pending, &state).unwrap(); + assert_eq!(pending["frozen"], true); + assert_eq!(pending["policy_state"], "frozen"); + assert_eq!(pending["frozen_policy"]["policy_hash"], "accepted-hash"); + assert_eq!(pending["frozen_policy"]["policy_source"], "global"); + assert_eq!( + pending["frozen_policy"]["frozen_time"], + "1970-01-01T00:10:00Z" + ); + // The captured provider authorization is comparable, and the internal + // provider identity stays out of the output. + let provider = &pending["frozen_policy"]["providers"][0]; + assert_eq!(provider["name"], "github"); + assert_eq!(provider["type"], "github"); + assert_eq!(provider["config"]["region"], "eu"); + assert!(!pending.to_string().contains("internal-id")); + assert_eq!(pending["withheld_providers"][0]["provider"], "github"); + assert_eq!(pending["withheld_providers"][0]["change"], "config_changed"); + // Reauthorizing is the wrong advice, so the repair names what works. + let lines = super::withheld_provider_lines(&state.withheld_providers); + assert_eq!( + lines, + [ + "provider 'github' credentials are withheld because its configuration changed after the freeze; restore the frozen configuration, or delete and recreate the sandbox" + ] + ); + let mut live = super::sandbox_to_json(&sandbox); + super::append_frozen_policy_json( + &mut live, + &openshell_core::proto::FrozenSandboxPolicyState::default(), + ) + .unwrap(); + assert!(live.get("frozen").is_none()); + assert!(live.get("policy_state").is_none()); + } + #[test] fn sandbox_json_exposes_repair_diagnostic_and_accepted_generation() { use openshell_core::proto::{ConfigurationAdmissionState, SandboxConfigurationAdmission}; diff --git a/crates/openshell-cli/src/tls.rs b/crates/openshell-cli/src/tls.rs index fd138aae5b..089766b0b6 100644 --- a/crates/openshell-cli/src/tls.rs +++ b/crates/openshell-cli/src/tls.rs @@ -21,6 +21,11 @@ pub type GrpcClient = openshell_sdk::raw::GrpcClient< tonic::service::interceptor::InterceptedService, >; +/// Client for the opt-in frozen-policy service, built by [`frozen_policies_client`]. +pub(crate) type FrozenPoliciesClient = openshell_sdk::raw::FrozenSandboxPoliciesClient< + tonic::service::interceptor::InterceptedService, +>; + /// Interceptor stack applied to gateway requests from clients built by /// [`grpc_client`]. /// @@ -344,15 +349,8 @@ pub async fn build_channel(server: &str, tls: &TlsOptions) -> Result { /// `TRACEPARENT`/`TRACESTATE` trace context from the environment on every /// request. With no token and no trace context, the interceptor is a no-op. pub async fn grpc_client(server: &str, tls: &TlsOptions) -> Result { - let config = sdk_client_config(server, tls)?; - // Keep the SDK's transport state machine out of every command future. - // Most CLI commands compose this helper into larger async operations. - let client = Box::pin(OpenShellClient::connect(config)) - .await - .into_diagnostic()?; - // tonic allows a single interceptor per channel: compose the SDK's auth - // interceptor (sharing its live bearer slot) with the CLI's passive - // trace-context forwarding. + let client = sdk_client(server, tls).await?; + // Share the SDK's live bearer slot and preserve passive trace forwarding. let interceptor = GatewayInterceptor { auth: client.auth_interceptor(), trace: EnvTraceContextInterceptor::from_env(), @@ -363,6 +361,33 @@ pub async fn grpc_client(server: &str, tls: &TlsOptions) -> Result { )) } +pub(crate) async fn frozen_policies_client( + server: &str, + tls: &TlsOptions, +) -> Result> { + let client = sdk_client(server, tls).await?; + let interceptor = GatewayInterceptor { + auth: client.auth_interceptor(), + trace: EnvTraceContextInterceptor::from_env(), + }; + let channel = + tonic::service::interceptor::InterceptedService::new(client.channel(), interceptor); + if !openshell_core::grpc_client::frozen_policies_supported(channel.clone()).await? { + return Ok(None); + } + Ok(Some(openshell_sdk::raw::FrozenSandboxPoliciesClient::new( + channel, + ))) +} + +async fn sdk_client(server: &str, tls: &TlsOptions) -> Result { + let config = sdk_client_config(server, tls)?; + // Keep the SDK's transport state machine out of every command future. + Box::pin(OpenShellClient::connect(config)) + .await + .into_diagnostic() +} + #[cfg(test)] mod tests { use super::{GatewayInterceptor, TlsOptions, sdk_client_config}; diff --git a/crates/openshell-cli/tests/sandbox_create_lifecycle_integration.rs b/crates/openshell-cli/tests/sandbox_create_lifecycle_integration.rs index 8d616c69ba..16ec3562c4 100644 --- a/crates/openshell-cli/tests/sandbox_create_lifecycle_integration.rs +++ b/crates/openshell-cli/tests/sandbox_create_lifecycle_integration.rs @@ -31,6 +31,9 @@ use openshell_core::proto::{ tcp_forward_init, }; use openshell_core::rpc_error::StatusExt as _; +use openshell_server::test_support::grpc::frozen_sandbox_policies_server::{ + FrozenSandboxPolicies, FrozenSandboxPoliciesServer, +}; use openshell_server::test_support::grpc::open_shell_server::{OpenShell, OpenShellServer}; use std::collections::{HashMap, VecDeque}; use std::fs; @@ -74,6 +77,14 @@ struct SandboxState { sandbox_config_policy: Arc>>, /// Scripted `create_sandbox` failures, oldest first. Empty means success. create_failures: Arc>>, + /// Every `FrozenSandboxPolicies/CreateSandbox` request, in call order. + frozen_create_requests: Arc>>, + /// Answer a frozen create without acknowledging the freeze. + frozen_create_unacknowledged: Arc, + /// Report the freeze as still pending after the sandbox is ready. + frozen_policy_pending: Arc, + /// The page token of every frozen `ListSandboxes` request, in call order. + frozen_list_page_tokens: Arc>>, /// Delay applied by `create_sandbox` before it answers, to spend a retry /// budget the way a slow gateway would. create_delay: Arc>>, @@ -157,59 +168,12 @@ enum GetSandboxOutcome { NoMetadata(SandboxPhase), } -#[tonic::async_trait] -impl OpenShell for TestOpenShell { - // The rejected-suspend test checks that this error preserves active forwards. - async fn suspend_sandbox( - &self, - _request: tonic::Request, - ) -> Result, Status> { - Err(Status::unimplemented("unused")) - } - - async fn begin_rootfs_tar_staging( - &self, - request: tonic::Request, - ) -> Result, Status> { - let request = request.into_inner(); - let Some(dir) = self.state.rootfs_staging_dir.lock().await.clone() else { - return Err(Status::unimplemented("not used by this test server")); - }; - let mut requests = self.state.staging_requests.lock().await; - let token = format!("staging-token-{}", requests.len()); - requests.push(request); - Ok(Response::new( - openshell_core::proto::BeginRootfsTarStagingResponse { - staging_token: token.clone(), - upload_path: dir.join(format!("{token}.tar")).display().to_string(), - max_bytes: 1 << 20, - expiration_time: None, - }, - )) - } - - async fn health( - &self, - _request: tonic::Request, - ) -> Result, Status> { - self.state.health_requests.fetch_add(1, Ordering::SeqCst); - Ok(Response::new(HealthResponse { - status: ServiceStatus::Healthy.into(), - version: "test".to_string(), - })) - } - - async fn get_gateway_info( +impl TestOpenShell { + /// Answer a create the way the mock gateway does for either create RPC. + async fn answer_create( &self, - _request: tonic::Request, - ) -> Result, Status> { - Err(Status::permission_denied("platform administrator required")) - } - async fn create_sandbox( - &self, - request: tonic::Request, - ) -> Result, Status> { - let request = request.into_inner(); + request: &CreateSandboxRequest, + ) -> Result { let name = request.name.clone(); let service_urls = request .service_exposures @@ -226,7 +190,6 @@ impl OpenShell for TestOpenShell { .as_ref() .and_then(|spec| spec.policy.as_ref()) .is_some_and(openshell_core::proto::SandboxPolicy::is_cedar); - self.state.create_requests.lock().await.push(request); if cedar && self.state.reject_cedar_policy.load(Ordering::SeqCst) { return Err(Status::failed_precondition( "this gateway was built without Cedar policy support", @@ -270,14 +233,180 @@ impl OpenShell for TestOpenShell { SandboxPhase::Provisioning as i32 }, ); - Ok(Response::new(SandboxResponse { + Ok(SandboxResponse { application_service_urls: HashMap::new(), gateway_service_urls: HashMap::new(), sandbox: Some(sandbox), service_urls, + }) + } +} + +#[tonic::async_trait] +impl FrozenSandboxPolicies for TestOpenShell { + async fn create_sandbox( + &self, + request: tonic::Request, + ) -> Result, Status> { + let request = request.into_inner(); + self.state + .frozen_create_requests + .lock() + .await + .push(request.clone()); + let response = self + .answer_create(&CreateSandboxRequest { + workspace_scope: request.workspace_scope, + spec: request.spec, + name: request.name, + labels: request.labels, + annotations: request.annotations, + await_main_process_attachment: request.await_main_process_attachment, + workload_template: request.workload_template, + request_id: request.request_id, + service_exposures: request.service_exposures, + }) + .await?; + let acknowledged = !self + .state + .frozen_create_unacknowledged + .load(Ordering::SeqCst); + Ok(Response::new( + openshell_core::proto::FrozenSandboxResponse { + sandbox: response.sandbox, + frozen_policy: acknowledged.then_some( + openshell_core::proto::FrozenSandboxPolicyState { + requested: true, + ..Default::default() + }, + ), + service_urls: response.service_urls, + application_service_urls: response.application_service_urls, + gateway_service_urls: response.gateway_service_urls, + }, + )) + } + + async fn get_policy( + &self, + _request: tonic::Request, + ) -> Result, Status> { + let pending = self.state.frozen_policy_pending.load(Ordering::SeqCst); + Ok(Response::new( + openshell_core::proto::FrozenSandboxPolicyState { + requested: true, + policy: (!pending).then(|| openshell_core::proto::FrozenSandboxPolicy { + version: 1, + policy_hash: "frozen-hash".into(), + ..Default::default() + }), + ..Default::default() + }, + )) + } + + /// Two pages: only the second holds a sandbox that was created frozen. + async fn list_sandboxes( + &self, + request: tonic::Request, + ) -> Result, Status> { + let page_token = request.into_inner().page_token; + self.state + .frozen_list_page_tokens + .lock() + .await + .push(page_token.clone()); + let sandbox = |name: &str| Sandbox { + metadata: Some(openshell_core::proto::datamodel::v1::ObjectMeta { + name: name.to_string(), + workspace: "default".to_string(), + ..Default::default() + }), + ..Default::default() + }; + let response = if page_token.is_empty() { + openshell_core::proto::ListFrozenSandboxesResponse { + sandboxes: vec![sandbox("ordinary")], + next_page_token: "page-2".to_string(), + frozen_sandboxes: Vec::new(), + } + } else { + openshell_core::proto::ListFrozenSandboxesResponse { + sandboxes: vec![sandbox("kept")], + next_page_token: String::new(), + frozen_sandboxes: vec![openshell_core::proto::FrozenSandboxSummary { + workspace: "default".to_string(), + sandbox: "kept".to_string(), + policy_hash: None, + frozen_time: None, + }], + } + }; + Ok(Response::new(response)) + } +} + +#[tonic::async_trait] +impl OpenShell for TestOpenShell { + // The rejected-suspend test checks that this error preserves active forwards. + async fn suspend_sandbox( + &self, + _request: tonic::Request, + ) -> Result, Status> { + Err(Status::unimplemented("unused")) + } + + async fn begin_rootfs_tar_staging( + &self, + request: tonic::Request, + ) -> Result, Status> { + let request = request.into_inner(); + let Some(dir) = self.state.rootfs_staging_dir.lock().await.clone() else { + return Err(Status::unimplemented("not used by this test server")); + }; + let mut requests = self.state.staging_requests.lock().await; + let token = format!("staging-token-{}", requests.len()); + requests.push(request); + Ok(Response::new( + openshell_core::proto::BeginRootfsTarStagingResponse { + staging_token: token.clone(), + upload_path: dir.join(format!("{token}.tar")).display().to_string(), + max_bytes: 1 << 20, + expiration_time: None, + }, + )) + } + + async fn health( + &self, + _request: tonic::Request, + ) -> Result, Status> { + self.state.health_requests.fetch_add(1, Ordering::SeqCst); + Ok(Response::new(HealthResponse { + status: ServiceStatus::Healthy.into(), + version: "test".to_string(), })) } + async fn get_gateway_info( + &self, + _request: tonic::Request, + ) -> Result, Status> { + Err(Status::permission_denied("platform administrator required")) + } + async fn create_sandbox( + &self, + request: tonic::Request, + ) -> Result, Status> { + let request = request.into_inner(); + self.state + .create_requests + .lock() + .await + .push(request.clone()); + self.answer_create(&request).await.map(Response::new) + } + async fn stop_sandbox( &self, _request: tonic::Request, @@ -1040,6 +1169,12 @@ struct TestServer { } async fn run_server() -> TestServer { + run_server_with(false).await +} + +/// Start the mock gateway; `frozen_policies` adds the frozen-policy service +/// and the reflection service that advertises it. +async fn run_server_with(frozen_policies: bool) -> TestServer { let (ca, ca_key) = build_ca(); let (server_cert, server_key) = build_server_cert(&ca, &ca_key); let (client_cert, client_key) = build_client_cert(&ca, &ca_key); @@ -1059,13 +1194,16 @@ async fn run_server() -> TestServer { let svc_openshell = openshell.clone(); tokio::spawn(async move { - Server::builder() + let mut router = Server::builder() .tls_config(tls_config) .unwrap() - .add_service(OpenShellServer::new(svc_openshell)) - .serve_with_incoming(incoming) - .await - .unwrap(); + .add_service(OpenShellServer::new(svc_openshell.clone())); + if frozen_policies { + router = router + .add_service(FrozenSandboxPoliciesServer::new(svc_openshell)) + .add_service(openshell_server::test_support::reflection_service()); + } + router.serve_with_incoming(incoming).await.unwrap(); }); let dir = helpers::tempdir().unwrap(); @@ -1656,6 +1794,252 @@ async fn sandbox_create_tolerates_an_unreachable_profile_catalog() { .await; } +#[tokio::test] +async fn sandbox_create_frozen_retries_through_the_frozen_service() { + let server = run_server_with(true).await; + let fake_ssh_dir = helpers::tempdir().unwrap(); + let xdg_dir = helpers::tempdir().unwrap(); + server + .openshell + .state + .create_failures + .lock() + .await + .push_back(mutation_lock_timeout(Duration::from_millis(1))); + + test_env(&fake_ssh_dir, &xdg_dir) + .run_async(async { + let tls = test_tls(&server); + install_fake_ssh(&fake_ssh_dir); + run::sandbox_create( + &server.endpoint, + "openshell", + run::SandboxCreateConfig { + name: Some("frozen-retry"), + command: &["echo".into(), "OK".into()], + create_retry_timeout_secs: Some(5), + frozen: true, + ..test_config() + }, + "default", + &tls, + ) + .await + .expect("a frozen create should retry a lock timeout inside the budget"); + + let frozen = server + .openshell + .state + .frozen_create_requests + .lock() + .await + .clone(); + assert_eq!( + frozen.len(), + 2, + "the frozen create should be sent again after the lock timeout" + ); + assert_eq!(frozen[1].name, "frozen-retry"); + assert_eq!(frozen[1].request_id, ""); + // A retry never becomes an ordinary, unfrozen create. + assert!(create_requests(&server).await.is_empty()); + }) + .await; +} + +#[tokio::test] +async fn sandbox_create_frozen_fails_when_the_gateway_does_not_acknowledge_the_freeze() { + let server = run_server_with(true).await; + let fake_ssh_dir = helpers::tempdir().unwrap(); + let xdg_dir = helpers::tempdir().unwrap(); + server + .openshell + .state + .frozen_create_unacknowledged + .store(true, Ordering::SeqCst); + + test_env(&fake_ssh_dir, &xdg_dir) + .run_async(async { + let error = run::sandbox_create( + &server.endpoint, + "openshell", + run::SandboxCreateConfig { + name: Some("unacknowledged"), + command: &["/opt/agent".into()], + create_retry_timeout_secs: Some(5), + frozen: true, + ..test_config() + }, + "default", + &test_tls(&server), + ) + .await + .expect_err("an unacknowledged freeze must stop the client workflow"); + + let message = error.to_string(); + assert!( + message + .contains("did not acknowledge frozen creation for sandbox 'unacknowledged'"), + "{message}" + ); + assert!( + message.contains("sandbox delete unacknowledged"), + "{message}" + ); + // The failure is terminal: no retry and no ordinary create. + assert_eq!( + server + .openshell + .state + .frozen_create_requests + .lock() + .await + .len(), + 1 + ); + assert!(create_requests(&server).await.is_empty()); + assert_eq!( + server + .openshell + .state + .ssh_session_requests + .load(Ordering::SeqCst), + 0 + ); + }) + .await; +} + +/// Ready does not prove the policy froze. A frozen create that cannot confirm +/// the capture must fail before the command runs in an unfrozen sandbox. +#[tokio::test] +async fn sandbox_create_frozen_fails_when_ready_without_a_captured_policy() { + let server = run_server_with(true).await; + let fake_ssh_dir = helpers::tempdir().unwrap(); + let xdg_dir = helpers::tempdir().unwrap(); + server + .openshell + .state + .frozen_policy_pending + .store(true, Ordering::SeqCst); + + test_env(&fake_ssh_dir, &xdg_dir) + .run_async(async { + let error = run::sandbox_create( + &server.endpoint, + "openshell", + run::SandboxCreateConfig { + name: Some("still-pending"), + command: &["/opt/agent".into()], + frozen: true, + ..test_config() + }, + "default", + &test_tls(&server), + ) + .await + .expect_err("a ready sandbox with a pending freeze must fail the create"); + + let message = error.to_string(); + assert!( + message.contains("'still-pending' is ready but its policy is not frozen yet"), + "{message}" + ); + assert!( + message.contains("sandbox delete still-pending"), + "{message}" + ); + // The command never ran in the unfrozen sandbox. + assert_eq!( + server + .openshell + .state + .ssh_session_requests + .load(Ordering::SeqCst), + 0 + ); + }) + .await; +} + +#[tokio::test] +async fn sandbox_list_frozen_skips_a_page_without_frozen_sandboxes() { + let server = run_server_with(true).await; + let fake_ssh_dir = helpers::tempdir().unwrap(); + let xdg_dir = helpers::tempdir().unwrap(); + + test_env(&fake_ssh_dir, &xdg_dir) + .run_async(async { + run::sandbox_list( + &server.endpoint, + 1, + "", + false, + true, + None, + run::SandboxListFilter::Frozen, + "table", + "default", + false, + &test_tls(&server), + ) + .await + .expect("frozen list"); + + // An empty first page is not the answer while more pages remain. + assert_eq!( + *server.openshell.state.frozen_list_page_tokens.lock().await, + vec![String::new(), "page-2".to_string()] + ); + }) + .await; +} + +#[tokio::test] +async fn sandbox_create_frozen_rejects_unsupported_gateway_before_creation() { + let server = run_server().await; + let fake_ssh_dir = helpers::tempdir().unwrap(); + let xdg_dir = helpers::tempdir().unwrap(); + + test_env(&fake_ssh_dir, &xdg_dir) + .run_async(async { + // This legacy gateway has no frozen-policy service. No ordinary + // create is allowed as a fallback for the explicit frozen request. + let error = run::sandbox_create( + &server.endpoint, + "openshell", + run::SandboxCreateConfig { + name: Some("legacy-frozen"), + command: &["/opt/agent".into()], + frozen: true, + ..test_config() + }, + "default", + &test_tls(&server), + ) + .await + .expect_err("an unsupported freeze must stop the client workflow"); + + let message = error.to_string(); + assert!( + message.contains("does not support frozen sandbox policies"), + "{message}" + ); + assert!(create_requests(&server).await.is_empty()); + assert_eq!( + server + .openshell + .state + .ssh_session_requests + .load(Ordering::SeqCst), + 0 + ); + assert!(deleted_names(&server).await.is_empty()); + assert_eq!(load_last_sandbox("openshell", "default"), None); + }) + .await; +} + #[tokio::test] async fn sandbox_create_keeps_command_sessions_by_default() { let server = run_server().await; diff --git a/crates/openshell-core/Cargo.toml b/crates/openshell-core/Cargo.toml index 8157c9b219..6d5a468f69 100644 --- a/crates/openshell-core/Cargo.toml +++ b/crates/openshell-core/Cargo.toml @@ -21,6 +21,7 @@ prost = { workspace = true } prost-types = { workspace = true } tonic = { workspace = true, features = ["channel"] } tonic-prost = { workspace = true } +tonic-reflection = { workspace = true } tonic-types = { workspace = true } tokio = { workspace = true } tokio-stream = { workspace = true } diff --git a/crates/openshell-core/src/grpc_client.rs b/crates/openshell-core/src/grpc_client.rs index 2429f255cc..d40609fe06 100644 --- a/crates/openshell-core/src/grpc_client.rs +++ b/crates/openshell-core/src/grpc_client.rs @@ -1291,6 +1291,181 @@ async fn fetch_settings_snapshot_with_client( Ok(settings_poll_result(response.into_inner())) } +/// Runtime configuration paired with its authoritative frozen-policy state. +/// Existing polling results retain their source-compatible shape. +#[derive(Clone, Debug)] +pub struct FrozenSettingsPollResult { + pub snapshot: SettingsPollResult, + pub frozen: bool, + pub frozen_requested: bool, +} + +impl From for FrozenSettingsPollResult { + fn from(snapshot: SettingsPollResult) -> Self { + Self { + snapshot, + frozen: false, + frozen_requested: false, + } + } +} + +impl std::ops::Deref for FrozenSettingsPollResult { + type Target = SettingsPollResult; + + fn deref(&self) -> &Self::Target { + &self.snapshot + } +} + +impl std::ops::DerefMut for FrozenSettingsPollResult { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.snapshot + } +} + +async fn fetch_frozen_snapshot_on_channel( + channel: AuthedChannel, + sandbox: &str, + workspace: Option<&str>, + supported_capabilities: Vec, +) -> Result { + use crate::proto::frozen_sandbox_policies_client::FrozenSandboxPoliciesClient; + + if !frozen_policies_supported(channel.clone()).await? { + return fetch_settings_snapshot_with_client( + &mut OpenShellClient::new(channel), + sandbox, + workspace, + supported_capabilities, + ) + .await + .map(Into::into); + } + + let response = FrozenSandboxPoliciesClient::new(channel.clone()) + .get_config(crate::proto::GetFrozenSandboxConfigRequest { + workspace_scope: workspace.map(crate::proto::workspace_selector), + name: sandbox.to_string(), + supported_capabilities, + }) + .await; + match response { + Ok(response) => { + let response = response.into_inner(); + let config = response.config.ok_or_else(|| { + miette::miette!("gateway returned no frozen-policy configuration snapshot") + })?; + if response.frozen && !response.frozen_requested { + return Err(miette::miette!( + "gateway returned inconsistent frozen-policy state" + )); + } + Ok(FrozenSettingsPollResult { + snapshot: settings_poll_result(config), + frozen: response.frozen, + frozen_requested: response.frozen_requested, + }) + } + Err(status) => Err(grpc_status_error(status)), + } +} + +/// Negotiate the optional policy service before sending an authenticated RPC. +/// Legacy authorization routers can deny unknown methods before dispatch. +pub async fn frozen_policies_supported( + channel: InterceptedService, +) -> Result { + use tonic_reflection::pb::v1::{ + ServerReflectionRequest, server_reflection_client::ServerReflectionClient, + server_reflection_request::MessageRequest, server_reflection_response::MessageResponse, + }; + + let response = ServerReflectionClient::new(channel) + .server_reflection_info(tokio_stream::iter([ServerReflectionRequest { + host: String::new(), + message_request: Some(MessageRequest::ListServices(String::new())), + }])) + .await; + let mut stream = match response { + Ok(response) => response.into_inner(), + Err(status) if status.code() == tonic::Code::Unimplemented => return Ok(false), + Err(status) => return Err(grpc_status_error(status)), + }; + let response = stream + .message() + .await + .map_err(grpc_status_error)? + .ok_or_else(|| miette::miette!("gateway returned no service discovery response"))?; + match response.message_response { + Some(MessageResponse::ListServicesResponse(services)) => Ok(services + .service + .iter() + .any(|service| service.name == "openshell.v1.FrozenSandboxPolicies")), + _ => Err(miette::miette!( + "gateway returned invalid service discovery response" + )), + } +} + +/// Fetch runtime configuration and freeze state without extending old messages. +/// +/// Supervisor startup calls this in place of [`fetch_settings_snapshot`], so +/// it keeps that call's client span. +#[tracing::instrument( + name = "supervisor.gateway.fetch_settings_snapshot", + skip_all, + fields(otel.kind = "client", otel.status_code = tracing::field::Empty) +)] +pub async fn fetch_frozen_settings_snapshot( + gateway: &GatewayEndpoint, + sandbox: &str, +) -> Result { + let status = ClientSpanStatus::current(); + let channel = connect_channel(gateway).await?; + status.finish( + fetch_frozen_snapshot_on_channel( + channel, + sandbox, + None, + gateway.supported_capabilities.clone(), + ) + .await, + ) +} + +/// Sync an initialization policy and retain the freeze signal on the same channel. +#[tracing::instrument( + name = "supervisor.gateway.sync_policy_and_fetch_snapshot", + skip_all, + fields(otel.kind = "client", otel.status_code = tracing::field::Empty) +)] +pub async fn sync_policy_and_fetch_frozen_snapshot( + gateway: &GatewayEndpoint, + sandbox: &str, + policy: &ProtoSandboxPolicy, + workspace: &str, +) -> Result { + let status = ClientSpanStatus::current(); + let channel = connect_channel(gateway).await?; + sync_policy_with_client( + &mut OpenShellClient::new(channel.clone()), + sandbox, + policy, + workspace, + ) + .await?; + status.finish( + fetch_frozen_snapshot_on_channel( + channel, + sandbox, + Some(workspace), + gateway.supported_capabilities.clone(), + ) + .await, + ) +} + fn learned_workspace_selector(workspace: Option<&str>) -> Option { workspace.map(crate::proto::workspace_selector) } @@ -1384,32 +1559,6 @@ pub async fn sync_policy( sync_policy_with_client(&mut client, sandbox, policy, workspace).await } -/// Sync an enriched policy and return the authoritative revision snapshot. -#[tracing::instrument( - name = "supervisor.gateway.sync_policy_and_fetch_snapshot", - skip_all, - fields(otel.kind = "client", otel.status_code = tracing::field::Empty) -)] -pub async fn sync_policy_and_fetch_snapshot( - gateway: &GatewayEndpoint, - sandbox: &str, - policy: &ProtoSandboxPolicy, - workspace: &str, -) -> Result { - let status = ClientSpanStatus::current(); - let mut client = connect(gateway).await?; - sync_policy_with_client(&mut client, sandbox, policy, workspace).await?; - status.finish( - fetch_settings_snapshot_with_client( - &mut client, - sandbox, - Some(workspace), - gateway.supported_capabilities.clone(), - ) - .await, - ) -} - /// Report an exact runtime configuration generation. Pending registration uses /// the snapshot's instance fence; retain that snapshot across registration retries. #[tracing::instrument( @@ -2642,3 +2791,220 @@ impl CachedOpenShellClient { Ok(()) } } + +#[cfg(test)] +mod frozen_snapshot_tests { + use super::*; + use crate::proto::frozen_sandbox_policies_server::{ + FrozenSandboxPolicies, FrozenSandboxPoliciesServer, + }; + use crate::proto::{ + CreateFrozenSandboxRequest, FrozenSandboxConfigResponse, FrozenSandboxPolicyState, + FrozenSandboxResponse, GetFrozenSandboxConfigRequest, GetFrozenSandboxPolicyRequest, + ListFrozenSandboxesRequest, ListFrozenSandboxesResponse, UpdateFrozenGlobalConfigRequest, + UpdateFrozenGlobalConfigResponse, + }; + use std::convert::Infallible; + use std::sync::atomic::{AtomicUsize, Ordering}; + use std::task::{Context, Poll}; + use tokio_stream::wrappers::TcpListenerStream; + use tonic::codegen::http; + use tonic::{Request, Response, Status}; + + #[derive(Clone)] + struct FrozenConfigService { + response: std::result::Result, + calls: Arc, + } + + #[tonic::async_trait] + impl FrozenSandboxPolicies for FrozenConfigService { + async fn create_sandbox( + &self, + _: Request, + ) -> std::result::Result, Status> { + Err(Status::unimplemented("unused")) + } + async fn get_policy( + &self, + _: Request, + ) -> std::result::Result, Status> { + Err(Status::unimplemented("unused")) + } + async fn list_sandboxes( + &self, + _: Request, + ) -> std::result::Result, Status> { + Err(Status::unimplemented("unused")) + } + async fn update_global_config( + &self, + _: Request, + ) -> std::result::Result, Status> { + Err(Status::unimplemented("unused")) + } + async fn get_config( + &self, + request: Request, + ) -> std::result::Result, Status> { + assert_eq!( + request.metadata().get("authorization").unwrap(), + "Bearer test-token" + ); + assert_eq!(request.get_ref().name, "sandbox"); + self.calls.fetch_add(1, Ordering::SeqCst); + self.response.clone().map(Response::new) + } + } + + // A real tonic unary endpoint for the one legacy method this projection + // uses, without implementing unrelated OpenShell operations in the fixture. + #[derive(Clone)] + struct LegacyConfigService(Arc); + impl tonic::server::NamedService for LegacyConfigService { + const NAME: &'static str = "openshell.v1.OpenShell"; + } + impl tonic::codegen::Service> for LegacyConfigService { + type Response = http::Response; + type Error = Infallible; + type Future = tonic::codegen::BoxFuture; + fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll> { + Poll::Ready(Ok(())) + } + fn call(&mut self, request: http::Request) -> Self::Future { + let calls = self.0.clone(); + Box::pin(async move { + struct GetConfig(Arc); + impl tonic::server::UnaryService for GetConfig { + type Response = crate::proto::GetSandboxConfigResponse; + type Future = + std::future::Ready, Status>>; + fn call(&mut self, request: Request) -> Self::Future { + assert_eq!( + request.metadata().get("authorization").unwrap(), + "Bearer test-token" + ); + assert_eq!(request.get_ref().name, "sandbox"); + self.0.fetch_add(1, Ordering::SeqCst); + std::future::ready(Ok(Response::new( + crate::proto::GetSandboxConfigResponse { + version: 3, + policy_hash: "legacy".into(), + workspace: "default".into(), + ..Default::default() + }, + ))) + } + } + assert_eq!( + request.uri().path(), + "/openshell.v1.OpenShell/GetSandboxConfig" + ); + Ok(tonic::server::Grpc::new(tonic_prost::ProstCodec::default()) + .unary(GetConfig(calls), request) + .await) + }) + } + } + + async fn gateway( + response: Option>, + ) -> (GatewayEndpoint, Arc, Arc) { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let endpoint = format!("http://{}", listener.local_addr().unwrap()); + let legacy = Arc::new(AtomicUsize::new(0)); + let frozen = Arc::new(AtomicUsize::new(0)); + let mut reflection = tonic_reflection::server::Builder::configure() + .register_encoded_file_descriptor_set(crate::FILE_DESCRIPTOR_SET) + .with_service_name("openshell.v1.OpenShell"); + if response.is_some() { + reflection = reflection.with_service_name("openshell.v1.FrozenSandboxPolicies"); + } + let router = tonic::transport::Server::builder() + .tcp_nodelay(true) + .add_service(LegacyConfigService(legacy.clone())) + .add_service(reflection.build_v1().unwrap()); + tokio::spawn( + router + .add_service(FrozenSandboxPoliciesServer::new(FrozenConfigService { + // Legacy authorization routers deny unknown methods before + // dispatch, rather than returning UNIMPLEMENTED. + response: response.unwrap_or_else(|| { + Err(Status::permission_denied("unknown sandbox method")) + }), + calls: frozen.clone(), + })) + .serve_with_incoming(TcpListenerStream::new(listener)), + ); + ( + GatewayEndpoint::new( + endpoint, + GatewayCredentials::from_gateway_token("test-token").unwrap(), + ), + legacy, + frozen, + ) + } + + #[tokio::test] + async fn frozen_snapshot_preserves_mode_and_supports_legacy_gateways() { + for captured in [false, true] { + let (gateway, legacy, frozen) = gateway(Some(Ok(FrozenSandboxConfigResponse { + config: Some(crate::proto::GetSandboxConfigResponse { + version: 7, + policy_hash: "captured".into(), + workspace: "default".into(), + ..Default::default() + }), + frozen: captured, + frozen_requested: true, + }))) + .await; + let snapshot = fetch_frozen_settings_snapshot(&gateway, "sandbox") + .await + .unwrap(); + assert_eq!(snapshot.version, 7); + assert_eq!(snapshot.policy_hash, "captured"); + assert_eq!(snapshot.frozen, captured); + assert!(snapshot.frozen_requested); + assert_eq!(frozen.load(Ordering::SeqCst), 1); + assert_eq!(legacy.load(Ordering::SeqCst), 0); + } + let (gateway, legacy, frozen) = gateway(None).await; + let snapshot = fetch_frozen_settings_snapshot(&gateway, "sandbox") + .await + .unwrap(); + assert_eq!(snapshot.version, 3); + assert!(!snapshot.frozen); + assert!(!snapshot.frozen_requested); + assert_eq!(legacy.load(Ordering::SeqCst), 1); + assert_eq!(frozen.load(Ordering::SeqCst), 0); + } + + #[tokio::test] + async fn frozen_snapshot_denials_and_inconsistent_state_never_use_legacy_fallback() { + for response in [ + Err(Status::permission_denied("denied")), + Err(Status::unimplemented("advertised service is unavailable")), + Ok(FrozenSandboxConfigResponse { + config: Some(crate::proto::GetSandboxConfigResponse::default()), + frozen: true, + frozen_requested: false, + }), + Ok(FrozenSandboxConfigResponse { + config: None, + frozen: true, + frozen_requested: true, + }), + ] { + let (gateway, legacy, frozen) = gateway(Some(response)).await; + assert!( + fetch_frozen_settings_snapshot(&gateway, "sandbox") + .await + .is_err() + ); + assert_eq!(frozen.load(Ordering::SeqCst), 1); + assert_eq!(legacy.load(Ordering::SeqCst), 0); + } + } +} diff --git a/crates/openshell-gateway-interceptors/src/plan.rs b/crates/openshell-gateway-interceptors/src/plan.rs index cec0711876..51c0e0d0d2 100644 --- a/crates/openshell-gateway-interceptors/src/plan.rs +++ b/crates/openshell-gateway-interceptors/src/plan.rs @@ -370,6 +370,23 @@ impl ExecutionPlan { .any(|phase| self.bindings.contains_key(&(selector.clone(), *phase))) } + /// The gated ordinary RPC that `selector` would let a caller skip. + /// + /// That is the case when `selector` is a frozen-policy twin, an + /// interceptor modifies or validates the ordinary RPC, and none does so + /// for the twin. A `post_commit` binding observes and cannot gate. + pub(crate) fn skipped_gate(&self, selector: &RpcSelector) -> Option { + let (service, method) = + OpenShellRouteIndex::ordinary_twin(&selector.service, &selector.method)?; + let ordinary = RpcSelector::new(service, method); + let gated = |selector: &RpcSelector| { + [Phase::ModifyOperation, Phase::Validate] + .iter() + .any(|phase| self.bindings.contains_key(&(selector.clone(), *phase))) + }; + (gated(&ordinary) && !gated(selector)).then_some(ordinary) + } + pub(crate) fn input_type(&self, selector: &RpcSelector) -> Option<&str> { self.routes.input_type(&selector.service, &selector.method) } diff --git a/crates/openshell-gateway-interceptors/src/routes.rs b/crates/openshell-gateway-interceptors/src/routes.rs index 43afa43467..1400d1d5a3 100644 --- a/crates/openshell-gateway-interceptors/src/routes.rs +++ b/crates/openshell-gateway-interceptors/src/routes.rs @@ -11,10 +11,16 @@ use crate::{InterceptorError, Result}; const SERVICE_OPEN_SHELL: &str = "openshell.v1.OpenShell"; const SERVICE_SANDBOX_UPDATES: &str = "openshell.v1.SandboxUpdates"; +const SERVICE_FROZEN_POLICIES: &str = "openshell.v1.FrozenSandboxPolicies"; /// Unary sandbox-update methods that may be targeted by gateway interceptors. pub const INTERCEPTABLE_SANDBOX_UPDATE_METHODS: &[&str] = &["UpdateSandbox"]; +/// Unary frozen-policy methods that may be targeted by gateway interceptors. +/// Both carry an ordinary mutation under another name; see +/// [`OpenShellRouteIndex::ordinary_twin`]. +pub const INTERCEPTABLE_FROZEN_POLICY_METHODS: &[&str] = &["CreateSandbox", "UpdateGlobalConfig"]; + /// Unary `openshell.v1.OpenShell` methods that may be targeted by gateway /// interceptors. New methods are non-interceptable until deliberately added /// here. @@ -76,12 +82,16 @@ impl OpenShellRouteIndex { // SandboxUpdates is an optional extension: baseline descriptor sets // still need only OpenShell, but a present extension must be valid. let sandbox_updates = pool.get_service_by_name(SERVICE_SANDBOX_UPDATES); + let frozen_policies = pool.get_service_by_name(SERVICE_FROZEN_POLICIES); let mut all_methods = BTreeSet::new(); let mut unary_methods = BTreeSet::new(); let mut input_types = BTreeMap::new(); let mut output_types = BTreeMap::new(); - for service in std::iter::once(&open_shell).chain(sandbox_updates.as_ref()) { + for service in std::iter::once(&open_shell) + .chain(sandbox_updates.as_ref()) + .chain(frozen_policies.as_ref()) + { let service_name = service.full_name(); for method in service.methods() { let route = format!("{service_name}/{}", method.name()); @@ -107,14 +117,38 @@ impl OpenShellRouteIndex { INTERCEPTABLE_SANDBOX_UPDATE_METHODS, )?; } + if frozen_policies.is_some() { + index.validate_interceptable_list( + SERVICE_FROZEN_POLICIES, + INTERCEPTABLE_FROZEN_POLICY_METHODS, + )?; + } Ok(index) } + /// The ordinary RPC that a frozen-policy RPC carries under another name. + /// + /// A gate on the ordinary RPC must not be skipped by calling its twin, so + /// the gateway refuses the twin until an interceptor binds it as well. + #[must_use] + pub fn ordinary_twin(service: &str, method: &str) -> Option<(&'static str, &'static str)> { + match (service, method) { + (SERVICE_FROZEN_POLICIES, "CreateSandbox") => { + Some((SERVICE_OPEN_SHELL, "CreateSandbox")) + } + (SERVICE_FROZEN_POLICIES, "UpdateGlobalConfig") => { + Some((SERVICE_OPEN_SHELL, "UpdateConfig")) + } + _ => None, + } + } + #[must_use] pub fn is_interceptable(&self, service: &str, method: &str) -> bool { let allowed = match service { SERVICE_OPEN_SHELL => INTERCEPTABLE_METHODS, SERVICE_SANDBOX_UPDATES => INTERCEPTABLE_SANDBOX_UPDATE_METHODS, + SERVICE_FROZEN_POLICIES => INTERCEPTABLE_FROZEN_POLICY_METHODS, _ => return false, }; allowed.contains(&method) && self.unary_methods.contains(&format!("{service}/{method}")) @@ -343,6 +377,37 @@ mod tests { .input_type(SERVICE_OPEN_SHELL, "UpdateSandbox") .is_none() ); + // The frozen-policy twins of two ordinary mutations are bindable, and + // each names the ordinary RPC it must not let callers skip. + for (method, input, twin) in [ + ( + "CreateSandbox", + "openshell.v1.CreateFrozenSandboxRequest", + "CreateSandbox", + ), + ( + "UpdateGlobalConfig", + "openshell.v1.UpdateFrozenGlobalConfigRequest", + "UpdateConfig", + ), + ] { + assert!(index.is_interceptable(SERVICE_FROZEN_POLICIES, method)); + assert_eq!( + index.input_type(SERVICE_FROZEN_POLICIES, method), + Some(input) + ); + assert_eq!( + OpenShellRouteIndex::ordinary_twin(SERVICE_FROZEN_POLICIES, method), + Some((SERVICE_OPEN_SHELL, twin)) + ); + assert!(index.is_interceptable(SERVICE_OPEN_SHELL, twin)); + } + assert!(!index.is_interceptable(SERVICE_FROZEN_POLICIES, "GetPolicy")); + assert!(!index.is_interceptable(SERVICE_FROZEN_POLICIES, "GetConfig")); + assert_eq!( + OpenShellRouteIndex::ordinary_twin(SERVICE_OPEN_SHELL, "CreateSandbox"), + None + ); assert!(index.is_interceptable("openshell.v1.OpenShell", "StopSandbox")); assert!(index.is_interceptable("openshell.v1.OpenShell", "StartSandbox")); assert!(index.is_interceptable("openshell.v1.OpenShell", "SuspendSandbox")); diff --git a/crates/openshell-gateway-interceptors/src/runtime.rs b/crates/openshell-gateway-interceptors/src/runtime.rs index 21de44fb9c..87d8113906 100644 --- a/crates/openshell-gateway-interceptors/src/runtime.rs +++ b/crates/openshell-gateway-interceptors/src/runtime.rs @@ -118,6 +118,16 @@ impl GatewayInterceptorRuntime { self.plan.should_intercept(&selector) } + /// The gated ordinary RPC, as `service/method`, that the frozen-policy RPC + /// at `path` would let a caller skip. The gateway refuses such a call. + #[must_use] + pub fn skipped_gate(&self, path: &str) -> Option { + let selector = RpcSelector::from_grpc_path(path)?; + self.plan + .skipped_gate(&selector) + .map(|ordinary| ordinary.rpc()) + } + pub async fn evaluate_request( &self, path: &str, diff --git a/crates/openshell-sdk/README.md b/crates/openshell-sdk/README.md index fb7c4f3dce..c6ccfe9f03 100644 --- a/crates/openshell-sdk/README.md +++ b/crates/openshell-sdk/README.md @@ -28,6 +28,29 @@ Code constructing complete raw Rust message literals must add Exhaustive destructuring patterns must include `service_routes` or end with `..`. The curated SDK API is unchanged. +## Frozen sandbox policies + +`create_frozen_sandbox(FrozenSandboxCreateSpec { sandbox, policy })` creates a +sandbox through the optional frozen-policy service. The template equivalent is +`create_frozen_sandbox_from_template(SandboxTemplateCreateSpec)`. Both are also +available on a workspace-scoped client. Existing create specs and sandbox +references retain their ordinary shape. + +Use `get_frozen_policy(name)` to distinguish a requested, pending freeze from +the captured policy, hash and timestamp. Once initialization accepts the first +configuration, subsequent reads return that snapshot, including the captured +provider authorization in `providers` for comparison with approved artifacts. +`withheld_providers` names each captured provider whose credentials the +gateway withholds now, and what changed. Changing the sandbox's access +requires recreating it. `update_global_config(UpdateConfigRequest)` +returns the mutation result and names of sandboxes retaining a frozen policy. +List frozen sandboxes with `raw_frozen_policies().list_sandboxes(...)`. + +Older gateways reject frozen requests before creation; the SDK never retries +through ordinary creation. `raw_frozen_policies` and +`raw_frozen_policies_fresh` share the client's transport and live bearer slot, +with the same refresh distinction as the main raw client. + ## Auth and refresh The curated surface drives OIDC refresh automatically: proactively before a diff --git a/crates/openshell-sdk/src/client.rs b/crates/openshell-sdk/src/client.rs index 7d11bf3e9c..caef3c486d 100644 --- a/crates/openshell-sdk/src/client.rs +++ b/crates/openshell-sdk/src/client.rs @@ -12,12 +12,16 @@ use crate::auth::{BearerSlot, EdgeAuthInterceptor, bearer_metadata}; use crate::config::{AuthConfig, ClientConfig}; use crate::error::{Result, SdkError}; use crate::pagination::{Page, Pager}; -use crate::raw::{AuthedGrpcClient, AuthedSandboxUpdatesClient, AuthedServiceDiscoveryClient}; +use crate::raw::{ + AuthedFrozenSandboxPoliciesClient, AuthedGrpcClient, AuthedSandboxUpdatesClient, + AuthedServiceDiscoveryClient, +}; use crate::refresh::{RefreshedToken, TokenSource}; use crate::routing::OwnerCache; use crate::types::{ - CreateRetryOptions, DeleteOptions, DeletionResult, ExecOptions, ExecResult, Health, - ListOptions, ResumeOptions, SandboxPhase, SandboxRef, SandboxSpec, SandboxTemplateCreateSpec, + CreateRetryOptions, DeleteOptions, DeletionResult, ExecOptions, ExecResult, + FrozenGlobalConfigUpdate, FrozenPolicyState, FrozenSandboxCreateSpec, Health, ListOptions, + ResumeOptions, SandboxPhase, SandboxRef, SandboxSpec, SandboxTemplateCreateSpec, SandboxTemplateListOptions, SandboxWorkloadTemplate, WorkspaceRef, }; use crate::{WatchEvent, WatchOptions, transport}; @@ -54,6 +58,94 @@ pub struct OpenShellClient { } impl OpenShellClient { + /// Authenticated optional frozen-policy service; no proactive OIDC refresh. + pub fn raw_frozen_policies(&self) -> AuthedFrozenSandboxPoliciesClient { + proto::frozen_sandbox_policies_client::FrozenSandboxPoliciesClient::with_interceptor( + self.channel.clone(), + self.interceptor.clone(), + ) + } + + /// Optional frozen-policy service after proactive OIDC refresh. + pub async fn raw_frozen_policies_fresh(&self) -> Result { + self.ensure_fresh().await?; + Ok(self.raw_frozen_policies()) + } + + /// Create a frozen sandbox. Older gateways fail before creating a sandbox. + pub async fn create_frozen_sandbox(&self, spec: FrozenSandboxCreateSpec) -> Result { + self.workspace("default").create_frozen_sandbox(spec).await + } + + /// Create a frozen sandbox from a workspace-scoped workload template. + pub async fn create_frozen_sandbox_from_template( + &self, + spec: SandboxTemplateCreateSpec, + ) -> Result { + self.workspace("default") + .create_frozen_sandbox_from_template(spec) + .await + } + + /// Read the requested freeze and accepted policy in the default workspace. + pub async fn get_frozen_policy(&self, name: &str) -> Result { + self.workspace("default").get_frozen_policy(name).await + } + + /// Apply a global configuration update and report frozen-policy exceptions. + pub async fn update_global_config( + &self, + request: proto::UpdateConfigRequest, + ) -> Result { + let request = proto::UpdateFrozenGlobalConfigRequest { + workspace_scope: request.workspace_scope, + sandbox: request.sandbox, + policy: request.policy, + setting_key: request.setting_key, + setting_value: request.setting_value, + delete_setting: request.delete_setting, + global: true, + merge_operations: request.merge_operations, + expected_resource_version: request.expected_resource_version, + annotations: request.annotations, + request_id: request.request_id, + }; + let response = self + .frozen_unary(|mut grpc| { + let request = request.clone(); + async move { grpc.update_global_config(request).await } + }) + .await?; + Ok(FrozenGlobalConfigUpdate { + update: response.update.ok_or_else(|| { + SdkError::invalid_config("global update result missing from gateway response") + })?, + frozen_sandboxes: response.frozen_sandboxes, + }) + } + + async fn frozen_unary(&self, call: F) -> Result + where + F: Fn(AuthedFrozenSandboxPoliciesClient) -> Fut, + Fut: Future, tonic::Status>>, + { + self.ensure_fresh().await?; + match call(self.raw_frozen_policies()).await { + Ok(response) => Ok(response.into_inner()), + Err(status) if status.code() == tonic::Code::Unauthenticated => { + if self.refresh_on_unauthorized().await? { + call(self.raw_frozen_policies()) + .await + .map(tonic::Response::into_inner) + .map_err(map_status) + } else { + Err(map_status(status)) + } + } + Err(status) => Err(map_status(status)), + } + } + /// Open a connection to the gateway described by `config`. /// /// Performs the gRPC channel handshake immediately; subsequent RPCs reuse @@ -1336,6 +1428,73 @@ pub struct WorkspaceScopedClient { } impl WorkspaceScopedClient { + /// Create a frozen sandbox in this workspace using a distinct optional RPC. + pub async fn create_frozen_sandbox(&self, spec: FrozenSandboxCreateSpec) -> Result { + let mut request = create_sandbox_request(spec.sandbox); + request + .spec + .as_mut() + .expect("create request has a spec") + .policy = spec.policy; + self.create_frozen(request).await + } + + /// Create a frozen sandbox from a workload template in this workspace. + pub async fn create_frozen_sandbox_from_template( + &self, + spec: SandboxTemplateCreateSpec, + ) -> Result { + self.create_frozen(create_sandbox_from_template_request(spec)) + .await + } + + async fn create_frozen(&self, request: proto::CreateSandboxRequest) -> Result { + let request = proto::CreateFrozenSandboxRequest { + workspace_scope: Some(proto::workspace_selector(&self.workspace)), + request_id: request.request_id, + spec: request.spec, + name: request.name, + labels: request.labels, + annotations: request.annotations, + await_main_process_attachment: request.await_main_process_attachment, + workload_template: request.workload_template, + service_exposures: request.service_exposures, + }; + let response = self + .client + .frozen_unary(|mut grpc| { + let request = request.clone(); + async move { grpc.create_sandbox(request).await } + }) + .await?; + let mut sandbox = sandbox_from_response(response.sandbox)?; + if !response.frozen_policy.is_some_and(|state| state.requested) { + return Err(SdkError::invalid_config(format!( + "gateway did not acknowledge frozen creation for sandbox '{}' (ID '{}', workspace '{}'); remove the sandbox before retrying", + sandbox.name, sandbox.id, sandbox.workspace, + ))); + } + sandbox.service_urls = response.service_urls; + sandbox.application_service_urls = response.application_service_urls; + sandbox.gateway_service_urls = response.gateway_service_urls; + Ok(sandbox) + } + + /// Read a pending freeze or the immutable accepted snapshot in this workspace. + pub async fn get_frozen_policy(&self, name: &str) -> Result { + let request = proto::GetFrozenSandboxPolicyRequest { + workspace_scope: Some(proto::workspace_selector(&self.workspace)), + name: name.to_string(), + }; + self.client + .frozen_unary(|mut grpc| { + let request = request.clone(); + async move { grpc.get_policy(request).await } + }) + .await + .map(Into::into) + } + /// The workspace this client targets. pub fn workspace_name(&self) -> &str { &self.workspace diff --git a/crates/openshell-sdk/src/lib.rs b/crates/openshell-sdk/src/lib.rs index 2ca6fa6ec8..101234a4e7 100644 --- a/crates/openshell-sdk/src/lib.rs +++ b/crates/openshell-sdk/src/lib.rs @@ -52,10 +52,11 @@ pub use pagination::{Page, Pager}; pub use refresh::{Refresh, RefreshError, RefreshedToken, TokenSource}; pub use types::{ CreateRetryOptions, DeleteOptions, DeletionOutcome, DeletionResult, ExecOptions, ExecResult, - Health, ListOptions, LogLine, PlatformEvent, ResumeOptions, SandboxPhase, SandboxRef, - SandboxResources, SandboxRestartPolicy, SandboxServiceLevel, SandboxSpec, SandboxStartup, - SandboxTemplateCreateSpec, SandboxTemplateListOptions, SandboxWorkloadConfig, - SandboxWorkloadTemplate, SandboxWorkloadTemplateProvenance, SandboxWorkloadTemplateSpec, - ServiceAuthorizationMode, ServiceExposure, ServiceStatus, WatchEvent, WatchOptions, - WorkspaceRef, + FrozenGlobalConfigUpdate, FrozenPolicyState, FrozenProvider, FrozenSandboxCreateSpec, + FrozenSandboxPolicy, FrozenWithheldProvider, Health, ListOptions, LogLine, PlatformEvent, + ResumeOptions, SandboxPhase, SandboxRef, SandboxResources, SandboxRestartPolicy, + SandboxServiceLevel, SandboxSpec, SandboxStartup, SandboxTemplateCreateSpec, + SandboxTemplateListOptions, SandboxWorkloadConfig, SandboxWorkloadTemplate, + SandboxWorkloadTemplateProvenance, SandboxWorkloadTemplateSpec, ServiceAuthorizationMode, + ServiceExposure, ServiceStatus, WatchEvent, WatchOptions, WorkspaceRef, }; diff --git a/crates/openshell-sdk/src/raw.rs b/crates/openshell-sdk/src/raw.rs index 4bfe7676a7..1cfc67f89e 100644 --- a/crates/openshell-sdk/src/raw.rs +++ b/crates/openshell-sdk/src/raw.rs @@ -19,23 +19,28 @@ //! ``` pub use openshell_core::proto; +pub use openshell_core::proto::frozen_sandbox_policies_client::FrozenSandboxPoliciesClient; pub use openshell_core::proto::open_shell_client::OpenShellClient as GrpcClient; pub use openshell_core::proto::sandbox_updates_client::SandboxUpdatesClient; pub use openshell_core::proto::service_discovery_client::ServiceDiscoveryClient; pub use openshell_core::proto::{ - CreateSandboxRequest, CreateSandboxTemplateRequest, CreateWorkspaceRequest, - DeleteSandboxRequest, DeleteSandboxTemplateRequest, DeleteWorkspaceRequest, ExecSandboxRequest, - GetSandboxProviderStatusRequest, GetSandboxProviderStatusResponse, GetSandboxRequest, - GetSandboxTemplateRequest, GetWorkspaceRequest, HealthRequest, ListProvidersRequest, - ListSandboxTemplatesRequest, ListSandboxesRequest, ListWorkspacesRequest, - ProviderDesiredIdentity, ProviderMutationKind, ProviderMutationReceipt, - ProviderReadinessObservation, ProviderReadinessReason, ProviderReadinessState, - ProviderReadinessStatus, ResumeSandboxRequest, Sandbox, SandboxCommandUpdate, SandboxMapUpdate, - SandboxPhase as ProtoSandboxPhase, SandboxResources, SandboxServiceLevel, - SandboxSpec as ProtoSandboxSpec, SandboxStartup, SandboxTemplate, SandboxTemplateResponse, - SandboxWorkloadConfig, SandboxWorkloadTemplate, SandboxWorkloadTemplateProvenance, - SandboxWorkloadTemplateSpec, ServiceStatus as ProtoServiceStatus, StartSandboxRequest, - StopSandboxRequest, SuspendSandboxRequest, UpdateSandboxRequest, Workspace, + CreateFrozenSandboxRequest, CreateSandboxRequest, CreateSandboxTemplateRequest, + CreateWorkspaceRequest, DeleteSandboxRequest, DeleteSandboxTemplateRequest, + DeleteWorkspaceRequest, ExecSandboxRequest, FrozenSandboxConfigResponse, + FrozenSandboxPolicyState, FrozenSandboxResponse, GetFrozenSandboxConfigRequest, + GetFrozenSandboxPolicyRequest, GetSandboxProviderStatusRequest, + GetSandboxProviderStatusResponse, GetSandboxRequest, GetSandboxTemplateRequest, + GetWorkspaceRequest, HealthRequest, ListProvidersRequest, ListSandboxTemplatesRequest, + ListSandboxesRequest, ListWorkspacesRequest, ProviderDesiredIdentity, ProviderMutationKind, + ProviderMutationReceipt, ProviderReadinessObservation, ProviderReadinessReason, + ProviderReadinessState, ProviderReadinessStatus, ResumeSandboxRequest, Sandbox, + SandboxCommandUpdate, SandboxMapUpdate, SandboxPhase as ProtoSandboxPhase, SandboxResources, + SandboxServiceLevel, SandboxSpec as ProtoSandboxSpec, SandboxStartup, SandboxTemplate, + SandboxTemplateResponse, SandboxWorkloadConfig, SandboxWorkloadTemplate, + SandboxWorkloadTemplateProvenance, SandboxWorkloadTemplateSpec, + ServiceStatus as ProtoServiceStatus, StartSandboxRequest, StopSandboxRequest, + SuspendSandboxRequest, UpdateFrozenGlobalConfigRequest, UpdateFrozenGlobalConfigResponse, + UpdateSandboxRequest, Workspace, }; /// Type alias for the gRPC client wrapped in the SDK's auth interceptor. @@ -62,3 +67,11 @@ pub type AuthedServiceDiscoveryClient = ServiceDiscoveryClient< crate::EdgeAuthInterceptor, >, >; + +/// Frozen-policy service sharing the client's transport and live auth slot. +pub type AuthedFrozenSandboxPoliciesClient = FrozenSandboxPoliciesClient< + tonic::service::interceptor::InterceptedService< + tonic::transport::Channel, + crate::EdgeAuthInterceptor, + >, +>; diff --git a/crates/openshell-sdk/src/types.rs b/crates/openshell-sdk/src/types.rs index aaf6231dca..abbdd6f40d 100644 --- a/crates/openshell-sdk/src/types.rs +++ b/crates/openshell-sdk/src/types.rs @@ -327,6 +327,111 @@ pub struct SandboxSpec { pub restart_policy: SandboxRestartPolicy, } +/// Create a sandbox whose first accepted effective policy is retained for its lifetime. +#[derive(Clone, Debug, Default)] +pub struct FrozenSandboxCreateSpec { + pub sandbox: SandboxSpec, + /// Omit to discover the initial policy from the image. + pub policy: Option, +} + +/// Freeze request and accepted snapshot, queried independently of sandbox status. +#[derive(Clone, Debug, Default, PartialEq)] +#[non_exhaustive] +pub struct FrozenPolicyState { + pub requested: bool, + /// Absent until initialization successfully accepts a configuration. + pub policy: Option, + /// Captured providers whose credentials the gateway withholds now. + pub withheld_providers: Vec, +} + +/// Immutable accepted policy, its provenance, and the provider authorization +/// captured with it. +#[derive(Clone, Debug, PartialEq)] +#[non_exhaustive] +pub struct FrozenSandboxPolicy { + pub policy: Option, + pub version: u32, + pub policy_hash: String, + pub frozen_at_ms: Option, + pub policy_source: proto::PolicySource, + pub global_policy_version: u32, + /// Compare these with the approved provider and profile artifacts. + pub providers: Vec, +} + +/// Provider authorization a frozen sandbox captured. It holds no credential +/// value or handle, and omits the gateway's internal provider identity. +#[derive(Clone, Debug, PartialEq)] +#[non_exhaustive] +pub struct FrozenProvider { + pub name: String, + pub r#type: String, + /// Workspace that supplied the profile. Empty selects the platform scope. + pub profile_workspace: String, + pub config: HashMap, + /// The profile as captured. A later profile change does not apply. + pub profile: Option, +} + +/// A captured provider that changed after the policy was frozen. +#[derive(Clone, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub struct FrozenWithheldProvider { + pub provider: String, + /// Reverting a `Config` change restores delivery. Other changes need a + /// new sandbox. + pub change: proto::FrozenProviderChange, +} + +impl From for FrozenPolicyState { + fn from(value: proto::FrozenSandboxPolicyState) -> Self { + Self { + requested: value.requested, + policy: value.policy.map(|policy| FrozenSandboxPolicy { + policy: policy.policy, + version: policy.version, + policy_hash: policy.policy_hash, + frozen_at_ms: policy + .frozen_time + .as_ref() + .and_then(|time| openshell_core::time::timestamp_to_millis(time).ok()), + policy_source: proto::PolicySource::try_from(policy.policy_source) + .unwrap_or_default(), + global_policy_version: policy.global_policy_version, + providers: policy + .providers + .into_iter() + .map(|provider| FrozenProvider { + name: provider.provider, + r#type: provider.r#type, + profile_workspace: provider.profile_workspace, + config: provider.config, + profile: provider.profile, + }) + .collect(), + }), + withheld_providers: value + .withheld_providers + .into_iter() + .map(|withheld| FrozenWithheldProvider { + change: withheld.change(), + provider: withheld.provider, + }) + .collect(), + } + } +} + +/// Global mutation result including sandboxes retaining their frozen policy. +#[derive(Clone, Debug, PartialEq)] +#[non_exhaustive] +pub struct FrozenGlobalConfigUpdate { + pub update: proto::UpdateConfigResponse, + pub frozen_sandboxes: Vec, +} + /// A loopback HTTP service to expose during sandbox creation. #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct ServiceExposure { diff --git a/crates/openshell-sdk/tests/client_mock.rs b/crates/openshell-sdk/tests/client_mock.rs index 39d2f6b01e..db6938b025 100644 --- a/crates/openshell-sdk/tests/client_mock.rs +++ b/crates/openshell-sdk/tests/client_mock.rs @@ -9,6 +9,9 @@ //! `mtls_integration` and OIDC tests. use openshell_core::proto; +use openshell_core::proto::frozen_sandbox_policies_server::{ + FrozenSandboxPolicies, FrozenSandboxPoliciesServer, +}; use openshell_core::proto::open_shell_server::{OpenShell, OpenShellServer}; use openshell_core::proto::sandbox_updates_server::{SandboxUpdates, SandboxUpdatesServer}; use openshell_core::replica_routing; @@ -48,7 +51,18 @@ fn selects_all_workspaces(scope: &Option>, + frozen_create_response: Option, + frozen_policy: Option, + frozen_withheld_providers: Vec, + last_frozen_get: Mutex>, + frozen_list_response: proto::ListFrozenSandboxesResponse, + last_frozen_list: Mutex>, + last_frozen_global_update: Mutex>, last_get_name: Mutex>, last_get_workspace: Mutex>, last_create: Mutex>, @@ -1340,6 +1354,104 @@ impl proto::service_discovery_server::ServiceDiscovery for TestOpenShell { } } +#[tonic::async_trait] +impl FrozenSandboxPolicies for TestOpenShell { + async fn create_sandbox( + &self, + request: tonic::Request, + ) -> Result, Status> { + self.check_frozen_auth(&request)?; + let request = request.into_inner(); + let service_urls: HashMap = request + .service_exposures + .iter() + .map(|exposure| { + ( + exposure.service.clone(), + format!("https://{}.example.test/", exposure.service), + ) + }) + .collect(); + let response = proto::FrozenSandboxResponse { + sandbox: Some(sandbox_with_phase_ws( + &request.name, + proto::SandboxPhase::Provisioning, + selected_workspace(&request.workspace_scope).unwrap_or("default"), + )), + frozen_policy: self.state.frozen_create_response.clone(), + application_service_urls: service_urls.clone(), + gateway_service_urls: HashMap::from([( + "web".into(), + "https://web.gateway.test:8080/".into(), + )]), + service_urls, + }; + *self.state.last_frozen_create.lock().await = Some(request); + Ok(Response::new(response)) + } + + async fn get_policy( + &self, + request: tonic::Request, + ) -> Result, Status> { + self.check_frozen_auth(&request)?; + *self.state.last_frozen_get.lock().await = Some(request.into_inner()); + Ok(Response::new(proto::FrozenSandboxPolicyState { + requested: true, + policy: self.state.frozen_policy.clone(), + withheld_providers: self.state.frozen_withheld_providers.clone(), + })) + } + + async fn list_sandboxes( + &self, + request: tonic::Request, + ) -> Result, Status> { + self.check_frozen_auth(&request)?; + *self.state.last_frozen_list.lock().await = Some(request.into_inner()); + Ok(Response::new(self.state.frozen_list_response.clone())) + } + + async fn get_config( + &self, + _request: tonic::Request, + ) -> Result, Status> { + Err(Status::unimplemented( + "runtime config is not used by the curated SDK", + )) + } + + async fn update_global_config( + &self, + request: tonic::Request, + ) -> Result, Status> { + self.check_frozen_auth(&request)?; + *self.state.last_frozen_global_update.lock().await = Some(request.into_inner()); + Ok(Response::new(proto::UpdateFrozenGlobalConfigResponse { + update: Some(proto::UpdateConfigResponse { + version: 7, + ..Default::default() + }), + frozen_sandboxes: vec!["staging/frozen".into()], + })) + } +} + +impl TestOpenShell { + fn check_frozen_auth(&self, request: &tonic::Request) -> Result<(), Status> { + if let Some(expected) = &self.state.require_bearer { + let got = request + .metadata() + .get("authorization") + .and_then(|value| value.to_str().ok()); + if got != Some(expected.as_str()) { + return Err(Status::unauthenticated("invalid or missing bearer token")); + } + } + Ok(()) + } +} + /// Spin up the mock gateway, return its endpoint URL. async fn start_mock(state: Arc) -> String { let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); @@ -1352,12 +1464,18 @@ async fn start_mock(state: Arc) -> String { let discovery = proto::service_discovery_server::ServiceDiscoveryServer::new(TestOpenShell { state: state.clone(), }); + let frozen = (!state.omit_frozen_service).then(|| { + FrozenSandboxPoliciesServer::new(TestOpenShell { + state: state.clone(), + }) + }); let svc = OpenShellServer::new(TestOpenShell { state }); tokio::spawn(async move { let _ = tonic::transport::Server::builder() .add_service(svc) .add_service(updates) .add_service(discovery) + .add_optional_service(frozen) .serve_with_incoming(stream) .await; }); @@ -3697,3 +3815,221 @@ async fn watch_logs_addresses_the_sandbox_by_canonical_name() { ); } } + +#[tokio::test] +async fn frozen_creation_preserves_request_and_requires_acknowledgement() { + use openshell_sdk::FrozenSandboxCreateSpec; + for acknowledged in [None, Some(false), Some(true)] { + let state = Arc::new(MockState { + frozen_create_response: acknowledged.map(|requested| proto::FrozenSandboxPolicyState { + requested, + ..Default::default() + }), + ..Default::default() + }); + let endpoint = start_mock(state.clone()).await; + let client = connect(&endpoint).await; + for (workspace, template) in [ + ("default", false), + ("default", true), + ("staging", false), + ("staging", true), + ] { + let policy = proto::SandboxPolicy { + version: 1, + ..Default::default() + }; + let spec = SandboxSpec { + name: Some("frozen".into()), + providers: vec!["github".into()], + service_exposures: vec![ServiceExposure { + service: "web".into(), + target_port: 8080, + ..Default::default() + }], + ..Default::default() + }; + let template_spec = SandboxTemplateCreateSpec { + name: Some("frozen".into()), + template_name: "agent".into(), + policy: Some(policy.clone()), + providers: spec.providers.clone(), + service_exposures: spec.service_exposures.clone(), + ..Default::default() + }; + let frozen_spec = FrozenSandboxCreateSpec { + sandbox: spec, + policy: Some(policy), + }; + let created = match (workspace, template) { + ("default", false) => Box::pin(client.create_frozen_sandbox(frozen_spec)).await, + ("default", true) => { + client + .create_frozen_sandbox_from_template(template_spec) + .await + } + (_, false) => { + client + .workspace(workspace) + .create_frozen_sandbox(frozen_spec) + .await + } + (_, true) => { + client + .workspace(workspace) + .create_frozen_sandbox_from_template(template_spec) + .await + } + }; + if acknowledged == Some(true) { + let created = created.expect("acknowledged freeze may be pending"); + assert_eq!( + created.service_urls.get("web").map(String::as_str), + Some("https://web.example.test/") + ); + assert_eq!(created.application_service_urls, created.service_urls); + assert_eq!( + created.gateway_service_urls["web"], + "https://web.gateway.test:8080/" + ); + } else { + let error = created.expect_err("missing acknowledgement must fail"); + assert!( + error + .to_string() + .contains("did not acknowledge frozen creation") + ); + assert!(error.to_string().contains("frozen")); + } + let request = state.last_frozen_create.lock().await.clone().unwrap(); + assert_eq!( + selected_workspace(&request.workspace_scope), + Some(workspace) + ); + assert_eq!( + request.workload_template, + if template { "agent" } else { "" } + ); + let spec = request.spec.unwrap(); + assert_eq!(spec.policy.unwrap().version, 1); + assert_eq!(spec.providers, ["github"]); + assert!(state.last_create.lock().await.is_none()); + assert!(state.last_delete_name.lock().await.is_none()); + } + } +} + +#[tokio::test] +async fn frozen_creation_on_older_gateway_never_uses_ordinary_create() { + let state = Arc::new(MockState { + omit_frozen_service: true, + ..Default::default() + }); + let endpoint = start_mock(state.clone()).await; + let client = connect(&endpoint).await; + let error = + Box::pin(client.create_frozen_sandbox(openshell_sdk::FrozenSandboxCreateSpec::default())) + .await + .expect_err("old gateway lacks service"); + assert_eq!( + error.grpc_status().map(Status::code), + Some(tonic::Code::Unimplemented) + ); + assert!(state.last_create.lock().await.is_none()); +} + +#[tokio::test] +async fn frozen_policy_reads_and_global_updates_share_authentication() { + let state = Arc::new(MockState { + require_bearer: Some("Bearer test-token".into()), + frozen_policy: Some(proto::FrozenSandboxPolicy { + policy: Some(proto::SandboxPolicy { + version: 1, + ..Default::default() + }), + version: 3, + policy_hash: "accepted-hash".into(), + frozen_time: openshell_core::time::timestamp_from_millis(600_000).ok(), + policy_source: proto::PolicySource::Global as i32, + global_policy_version: 7, + providers: vec![proto::FrozenSandboxProvider { + provider: "github".into(), + provider_id: "internal-id".into(), + r#type: "github".into(), + config: HashMap::from([("region".into(), "eu".into())]), + ..Default::default() + }], + }), + frozen_withheld_providers: vec![proto::FrozenSandboxWithheldProvider { + provider: "github".into(), + change: proto::FrozenProviderChange::Config as i32, + }], + ..Default::default() + }); + let endpoint = start_mock(state.clone()).await; + let mut config = ClientConfig::new(endpoint); + config.auth = Some(AuthConfig::oidc("test-token")); + let client = OpenShellClient::connect(config).await.unwrap(); + let captured = client + .workspace("staging") + .get_frozen_policy("frozen") + .await + .unwrap(); + assert!(captured.requested); + // The captured provider authorization is comparable; what changed since is named. + assert_eq!(captured.withheld_providers.len(), 1); + assert_eq!(captured.withheld_providers[0].provider, "github"); + assert_eq!( + captured.withheld_providers[0].change, + proto::FrozenProviderChange::Config + ); + let policy = captured.policy.unwrap(); + assert_eq!(policy.providers.len(), 1); + assert_eq!(policy.providers[0].name, "github"); + assert_eq!(policy.providers[0].config["region"], "eu"); + assert_eq!(policy.policy_hash, "accepted-hash"); + assert_eq!(policy.frozen_at_ms, Some(600_000)); + assert_eq!(policy.policy.unwrap().version, 1); + assert_eq!(policy.policy_source, proto::PolicySource::Global); + assert_eq!( + selected_workspace( + &state + .last_frozen_get + .lock() + .await + .as_ref() + .unwrap() + .workspace_scope + ), + Some("staging") + ); + let result = client + .update_global_config(proto::UpdateConfigRequest { + policy: Some(proto::SandboxPolicy { + version: 1, + ..Default::default() + }), + ..Default::default() + }) + .await + .unwrap(); + assert_eq!(result.update.version, 7); + assert_eq!(result.frozen_sandboxes, ["staging/frozen"]); + assert!( + state + .last_frozen_global_update + .lock() + .await + .as_ref() + .unwrap() + .global + ); + let pending_state = Arc::new(MockState::default()); + let endpoint = start_mock(pending_state).await; + let pending = connect(&endpoint) + .await + .get_frozen_policy("pending") + .await + .unwrap(); + assert!(pending.requested && pending.policy.is_none()); +} diff --git a/crates/openshell-server/README.md b/crates/openshell-server/README.md index 61e458a23f..49d4a4e689 100644 --- a/crates/openshell-server/README.md +++ b/crates/openshell-server/README.md @@ -18,6 +18,43 @@ Retries reuse that generation and session, including after gateway restart. Credential renewal retains both; credentials for an older launch cannot authorize the new one. +## Frozen sandbox policy + +`FrozenSandboxPolicies.CreateSandbox` chooses frozen mode atomically with +creation, using a gateway-private `StoredFrozenSandboxPolicy` record keyed by +sandbox ID. First unary configuration acceptance captures the policy and +non-secret provider authorization in the same transaction as the sandbox CAS. +Session admission cannot activate a pending freeze. Existing public sandbox +messages and the `PolicySource` enum retain their source shape. + +Configuration, credential and token delivery share the captured policy and +profile catalog. Reads spanning first capture reload that authority before +returning. Credential values remain fresh; changed provider identity, +configuration or refresh authorization withholds credentials. Policy writes +are fenced again inside their storage transaction; sandbox deletion removes +the private record atomically. + +The additive runtime configuration response carries requested and captured +state together. A captured YAML policy cannot gain implicit filesystem paths on +restart. An incompatible runtime rejects launch with recreation guidance; +initial frozen global policies must already contain required proxy paths. +A Cedar policy derives its filesystem grants from policy text, so the runtime +adds its proxy baseline paths at each start, outside the snapshot. +All gateways sharing the store must support freezing before use. Older binary +versions do not enforce the private feature, so mixed-version fleets and +subsequent downgrade are unsupported while frozen sandboxes exist. + +`GetPolicy` also reports the captured providers whose credentials are withheld +now and what changed, using the comparison that delivery uses. Their token +grants fail as a configuration error, never as authorization required: +authorizing again cannot restore a frozen grant. `ListSandboxes` wraps the +ordinary list and adds the freeze state of each listed sandbox. A rejected +configuration of a frozen sandbox gets a frozen-specific public diagnostic on +the configuration read and the configuration report, because a captured policy +and its providers cannot be repaired in place. The gateway logs each capture +at info with the sandbox name. Delivery evaluates withheld providers on every +poll, so it logs them at debug only. + ## Shared supervisor pool The `SharedSupervision` the gateway hands a compute driver that asks for it diff --git a/crates/openshell-server/build.rs b/crates/openshell-server/build.rs index cc1d5163fd..c7bdf68560 100644 --- a/crates/openshell-server/build.rs +++ b/crates/openshell-server/build.rs @@ -33,11 +33,13 @@ fn main() -> Result<(), Box> { let refresh_proto = storage_proto_dir.join("provider_refresh.proto"); let image_proto = storage_proto_dir.join("sandbox_image.proto"); let secret_proto = storage_proto_dir.join("workspace_secret.proto"); + let frozen_proto = storage_proto_dir.join("sandbox_frozen_policy.proto"); println!("cargo:rerun-if-changed={}", storage_proto.display()); println!("cargo:rerun-if-changed={}", refresh_proto.display()); println!("cargo:rerun-if-changed={}", image_proto.display()); println!("cargo:rerun-if-changed={}", secret_proto.display()); + println!("cargo:rerun-if-changed={}", frozen_proto.display()); for imported_proto in [ "datamodel.proto", "openshell.proto", @@ -79,7 +81,13 @@ fn main() -> Result<(), Box> { .file_descriptor_set_path(&descriptor_path) .compile_with_config( proto_config, - &[storage_proto, refresh_proto, image_proto, secret_proto], + &[ + storage_proto, + refresh_proto, + image_proto, + secret_proto, + frozen_proto, + ], &include_dirs, )?; diff --git a/crates/openshell-server/proto/sandbox_frozen_policy.proto b/crates/openshell-server/proto/sandbox_frozen_policy.proto new file mode 100644 index 0000000000..bbbe377ead --- /dev/null +++ b/crates/openshell-server/proto/sandbox_frozen_policy.proto @@ -0,0 +1,15 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +syntax = "proto3"; + +// Gateway-private freeze state. Existing public sandbox rows and frozen +// openshell.storage.v1 declarations remain unchanged. +package openshell.storage.frozen.v1; +import "openshell.proto"; + +// Existence chooses frozen mode at creation; an absent policy is pending. +// The snapshot is captured once in the same transaction as first acceptance. +message StoredFrozenSandboxPolicy { + string sandbox_id = 1; + openshell.v1.FrozenSandboxPolicy policy = 2; +} diff --git a/crates/openshell-server/src/auth/descriptor_authz.rs b/crates/openshell-server/src/auth/descriptor_authz.rs index 18a76bc021..e00279a5b7 100644 --- a/crates/openshell-server/src/auth/descriptor_authz.rs +++ b/crates/openshell-server/src/auth/descriptor_authz.rs @@ -334,6 +334,56 @@ mod tests { ); } + #[test] + fn frozen_policy_methods_keep_distinct_user_and_sandbox_access() { + let table = + DescriptorAuthTable::from_descriptor_set(openshell_core::FILE_DESCRIPTOR_SET).unwrap(); + for (method, mode, scope, workspace_role, global_role) in [ + ( + "CreateSandbox", + AuthMode::Bearer, + "sandbox:write", + Some("user"), + None, + ), + ( + "GetPolicy", + AuthMode::Bearer, + "sandbox:read", + Some("user"), + None, + ), + ( + "ListSandboxes", + AuthMode::Bearer, + "sandbox:read", + Some("user"), + None, + ), + ( + "GetConfig", + AuthMode::Dual, + "config:read", + Some("user"), + None, + ), + ( + "UpdateGlobalConfig", + AuthMode::Bearer, + "config:write", + None, + Some("platform_admin"), + ), + ] { + let path = format!("/openshell.v1.FrozenSandboxPolicies/{method}"); + let entry = table.entries.get(&path).unwrap(); + assert_eq!(entry.auth_mode, mode, "{path}"); + assert_eq!(entry.scope.as_deref(), Some(scope), "{path}"); + assert_eq!(entry.workspace_role.as_deref(), workspace_role, "{path}"); + assert_eq!(entry.global_role.as_deref(), global_role, "{path}"); + } + } + #[test] fn no_duplicate_paths() { let paths: Vec<&str> = all_paths().collect(); diff --git a/crates/openshell-server/src/compute/mod.rs b/crates/openshell-server/src/compute/mod.rs index fb835b43a3..5d03f6eeb4 100644 --- a/crates/openshell-server/src/compute/mod.rs +++ b/crates/openshell-server/src/compute/mod.rs @@ -117,6 +117,7 @@ use provisioning_operation::ProvisioningOperationError; /// creation without expanding the public compute-driver protobuf contract. #[derive(Clone, Default)] pub struct SandboxCreateRuntimeInputs { + pub freeze_policy: bool, pub effective_policy: Option, pub launch_authentication: Option>, } @@ -127,6 +128,7 @@ impl SandboxCreateRuntimeInputs { Self { effective_policy: Some(effective_policy), launch_authentication: None, + freeze_policy: false, } } } @@ -2100,31 +2102,34 @@ impl ComputeRuntime { .map_err(|e| Status::internal(format!("failed to serialize labels: {e}")))?, ) }; - let result = self - .store - .put_if( - Sandbox::object_type(), - &sandbox_id, - sandbox.object_name(), - sandbox.object_workspace(), - &sandbox.encode_to_vec(), - labels_json.as_deref(), - WriteCondition::MustCreate, - ) - .await - .map_err(|e| { - if matches!( - e, - crate::persistence::PersistenceError::UniqueViolation { .. } - ) { - Status::already_exists(format!( - "sandbox '{}' already exists", - sandbox.object_name() - )) - } else { - Status::internal(format!("persist sandbox failed: {e}")) - } - })?; + let result = if runtime_inputs.freeze_policy { + self.store.create_frozen_sandbox(&sandbox).await + } else { + self.store + .put_if( + Sandbox::object_type(), + &sandbox_id, + sandbox.object_name(), + sandbox.object_workspace(), + &sandbox.encode_to_vec(), + labels_json.as_deref(), + WriteCondition::MustCreate, + ) + .await + } + .map_err(|e| { + if matches!( + e, + crate::persistence::PersistenceError::UniqueViolation { .. } + ) { + Status::already_exists(format!( + "sandbox '{}' already exists", + sandbox.object_name() + )) + } else { + Status::internal(format!("persist sandbox failed: {e}")) + } + })?; if let Some(metadata) = sandbox.metadata.as_mut() { metadata.resource_version = result.resource_version; } @@ -6356,6 +6361,21 @@ impl ComputeRuntime { terminal_delivery_finalized, } => (false, None, None, terminal_delivery_finalized, false), }; + // Frozen mode is creation-only and capture is monotone. A streamed + // acceptance may confirm a captured policy, but first acceptance must + // use the unary path that atomically captures its effective inputs. + if admission.is_some_and(|admission| { + admission.state + == i32::from(openshell_core::proto::ConfigurationAdmissionState::Accepted) + }) && self + .store + .get_sandbox_frozen_policy(sandbox_id) + .await + .map_err(|error| error.to_string())? + .is_some_and(|state| state.policy.is_none()) + { + return Err("frozen sandbox must first accept configuration through ReportSandboxConfiguration before session acceptance".into()); + } for attempt in 1..=SUPERVISOR_SESSION_CAS_RETRY_LIMIT { let Some(current) = existing else { return Ok(()); diff --git a/crates/openshell-server/src/grpc/frozen_policy.rs b/crates/openshell-server/src/grpc/frozen_policy.rs new file mode 100644 index 0000000000..846ad4c10c --- /dev/null +++ b/crates/openshell-server/src/grpc/frozen_policy.rs @@ -0,0 +1,242 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Additive creation and inspection APIs for gateway-owned policy freezing. + +use super::{ + OpenShellService, extract_principal, mutation_audit, mutation_replay, policy, sandbox, +}; +use crate::ServerState; +use crate::auth::workspace_authz::{MinWorkspaceRole, selected_workspace_name}; +use openshell_core::proto::{ + CreateFrozenSandboxRequest, CreateSandboxRequest, FrozenSandboxConfigResponse, + FrozenSandboxPolicyState, FrozenSandboxResponse, FrozenSandboxSummary, + GetFrozenSandboxConfigRequest, GetFrozenSandboxPolicyRequest, GetSandboxConfigRequest, + ListFrozenSandboxesRequest, ListFrozenSandboxesResponse, ListSandboxesRequest, + UpdateConfigRequest, UpdateFrozenGlobalConfigRequest, UpdateFrozenGlobalConfigResponse, +}; +use openshell_core::{ObjectId, ObjectName, ObjectWorkspace}; +use std::sync::Arc; +use tonic::{Request, Response, Status}; + +#[derive(Clone)] +pub(super) struct FrozenSandboxes(pub Vec); + +pub(super) async fn state_for( + store: &crate::persistence::Store, + sandbox_id: &str, +) -> Result { + let state = store + .get_sandbox_frozen_policy(sandbox_id) + .await + .map_err(|error| Status::internal(format!("fetch frozen policy failed: {error}")))?; + Ok(FrozenSandboxPolicyState { + requested: state.is_some(), + policy: state.and_then(|state| state.policy), + withheld_providers: Vec::new(), + }) +} + +#[tonic::async_trait] +impl openshell_core::proto::frozen_sandbox_policies_server::FrozenSandboxPolicies + for OpenShellService +{ + async fn create_sandbox( + &self, + request: Request, + ) -> Result, Status> { + let targets = { + let request = request.get_ref(); + mutation_audit::scoped( + request.workspace_scope.as_ref(), + [mutation_audit::requested("sandbox", &request.name)], + ) + }; + mutation_audit::audited(targets, mutation_replay::run(&self.state, request)).await + } + + async fn get_policy( + &self, + request: Request, + ) -> Result, Status> { + let principal = extract_principal(&request)?; + let request = request.into_inner(); + let sandbox = sandbox::resolve_and_authorize_sandbox_name( + &self.state, + &principal, + &request.name, + selected_workspace_name(request.workspace_scope.as_ref())?, + MinWorkspaceRole::User, + ) + .await?; + let mut frozen = state_for(self.state.store.as_ref(), sandbox.object_id()).await?; + if let Some(captured) = frozen.policy.as_ref() { + frozen.withheld_providers = + policy::frozen::withheld_providers(&self.state, &sandbox, captured).await?; + } + Ok(Response::new(frozen)) + } + + async fn list_sandboxes( + &self, + request: Request, + ) -> Result, Status> { + // The ordinary handler authorizes the selector and pages the result. + let list = sandbox::handle_list_sandboxes( + &self.state, + request.map(|request| ListSandboxesRequest { + workspace_scope: request.workspace_scope, + page_size: request.page_size, + page_token: request.page_token, + label_selector: request.label_selector, + }), + ) + .await? + .into_inner(); + let mut frozen_sandboxes = Vec::new(); + for sandbox in &list.sandboxes { + let state = state_for(self.state.store.as_ref(), sandbox.object_id()).await?; + if !state.requested { + continue; + } + let (policy_hash, frozen_time) = state.policy.map_or((None, None), |captured| { + (Some(captured.policy_hash), captured.frozen_time) + }); + frozen_sandboxes.push(FrozenSandboxSummary { + workspace: sandbox.object_workspace().to_string(), + sandbox: sandbox.object_name().to_string(), + policy_hash, + frozen_time, + }); + } + Ok(Response::new(ListFrozenSandboxesResponse { + sandboxes: list.sandboxes, + next_page_token: list.next_page_token, + frozen_sandboxes, + })) + } + + async fn get_config( + &self, + request: Request, + ) -> Result, Status> { + let (response, frozen, frozen_requested) = policy::handle_get_sandbox_config_with_frozen( + &self.state, + request.map(|request| GetSandboxConfigRequest { + name: request.name, + workspace_scope: request.workspace_scope, + supported_capabilities: request.supported_capabilities, + }), + ) + .await?; + Ok(response.map(|config| FrozenSandboxConfigResponse { + config: Some(config), + frozen, + frozen_requested, + })) + } + + async fn update_global_config( + &self, + request: Request, + ) -> Result, Status> { + // Record the same targets and no-op outcome as the ordinary UpdateConfig. + let view = update_config_request(request.get_ref().clone()); + let targets = mutation_audit::update_config_targets( + &view, + self.state.config.audit.capture_setting_values, + ); + let deleting_only = mutation_audit::deletes_only_a_setting(&view); + mutation_audit::audited( + targets, + mutation_audit::record_absent_delete( + deleting_only, + mutation_replay::run(&self.state, request), + ), + ) + .await + } +} + +/// The ordinary request a frozen global update carries, field for field. +fn update_config_request(request: UpdateFrozenGlobalConfigRequest) -> UpdateConfigRequest { + UpdateConfigRequest { + workspace_scope: request.workspace_scope, + policy: request.policy, + setting_key: request.setting_key, + setting_value: request.setting_value, + delete_setting: request.delete_setting, + global: request.global, + merge_operations: request.merge_operations, + expected_resource_version: request.expected_resource_version, + annotations: request.annotations, + sandbox: request.sandbox, + request_id: request.request_id, + } +} + +pub(super) async fn handle_create( + state: &Arc, + request: Request, +) -> Result, Status> { + let request = request.map(|request| CreateSandboxRequest { + workspace_scope: request.workspace_scope, + spec: request.spec, + name: request.name, + labels: request.labels, + annotations: request.annotations, + await_main_process_attachment: request.await_main_process_attachment, + workload_template: request.workload_template, + request_id: request.request_id, + service_exposures: request.service_exposures, + }); + let response = sandbox::handle_create_sandbox_with_mode(state, request, true).await?; + let sandbox = response + .get_ref() + .sandbox + .as_ref() + .ok_or_else(|| Status::internal("created sandbox is missing"))?; + let frozen_policy = state_for(state.store.as_ref(), sandbox.object_id()).await?; + Ok(response.map(|response| FrozenSandboxResponse { + sandbox: response.sandbox, + frozen_policy: Some(frozen_policy), + service_urls: response.service_urls, + application_service_urls: response.application_service_urls, + gateway_service_urls: response.gateway_service_urls, + })) +} + +pub(super) fn validate_global_request( + request: &UpdateFrozenGlobalConfigRequest, +) -> Result<(), Status> { + if !request.global { + return Err(Status::invalid_argument("global must be true")); + } + if request.workspace_scope.is_some() + || !request.sandbox.is_empty() + || !request.merge_operations.is_empty() + || !request.annotations.is_empty() + || request.expected_resource_version != 0 + { + return Err(Status::invalid_argument( + "sandbox, workspace_scope, merge_operations, annotations, and expected_resource_version are unsupported for global configuration", + )); + } + Ok(()) +} + +pub(super) async fn handle_update_global( + state: &Arc, + request: Request, +) -> Result, Status> { + validate_global_request(request.get_ref())?; + let response = policy::handle_update_config(state, request.map(update_config_request)).await?; + let names = response + .extensions() + .get::() + .map_or_else(Vec::new, |names| names.0.clone()); + Ok(response.map(|update| UpdateFrozenGlobalConfigResponse { + update: Some(update), + frozen_sandboxes: names, + })) +} diff --git a/crates/openshell-server/src/grpc/mod.rs b/crates/openshell-server/src/grpc/mod.rs index 5bfb592196..15d38a7775 100644 --- a/crates/openshell-server/src/grpc/mod.rs +++ b/crates/openshell-server/src/grpc/mod.rs @@ -4,6 +4,7 @@ //! gRPC service implementation. mod auth_rpc; +mod frozen_policy; mod mutation_audit; pub mod mutation_replay; pub mod policy; diff --git a/crates/openshell-server/src/grpc/mutation_audit.rs b/crates/openshell-server/src/grpc/mutation_audit.rs index 3aca25687b..840e44a305 100644 --- a/crates/openshell-server/src/grpc/mutation_audit.rs +++ b/crates/openshell-server/src/grpc/mutation_audit.rs @@ -14,12 +14,13 @@ use openshell_core::proto::{ DeleteProviderRefreshResponse, DeleteProviderResponse, DeleteSandboxResponse, DeleteSandboxTemplateResponse, DeleteSecretResponse, DeleteServiceResponse, DeleteWorkspaceResponse, DeletionOutcome, DetachSandboxProviderResponse, - EditDraftChunkResponse, ImportProviderProfilesResponse, InlineProviderRefreshSecretsResponse, - ProviderCredentialRefreshStatus, ProviderProfile, ProviderResponse, RejectDraftChunkResponse, - RemoveWorkspaceMemberResponse, RotateProviderCredentialResponse, Sandbox, SandboxResponse, - SandboxTemplateResponse, SecretResponse, ServiceEndpointResponse, UndoDraftChunkResponse, - UpdateConfigRequest, UpdateConfigResponse, UpdateProviderProfilesResponse, WorkspaceSelector, - setting_value, workspace_selector::Selection, + EditDraftChunkResponse, FrozenSandboxResponse, ImportProviderProfilesResponse, + InlineProviderRefreshSecretsResponse, ProviderCredentialRefreshStatus, ProviderProfile, + ProviderResponse, RejectDraftChunkResponse, RemoveWorkspaceMemberResponse, + RotateProviderCredentialResponse, Sandbox, SandboxResponse, SandboxTemplateResponse, + SecretResponse, ServiceEndpointResponse, UndoDraftChunkResponse, UpdateConfigRequest, + UpdateConfigResponse, UpdateFrozenGlobalConfigResponse, UpdateProviderProfilesResponse, + WorkspaceSelector, setting_value, workspace_selector::Selection, }; use openshell_core::proto::{ CreateSshSessionResponse, ExecSandboxRequest, RevokeSshSessionResponse, SshSession, @@ -131,6 +132,12 @@ impl Audited for SandboxResponse { } } +impl Audited for FrozenSandboxResponse { + fn produced(&self) -> Vec> { + stored_sandbox(self.sandbox.as_ref()) + } +} + impl Audited for SandboxTemplateResponse { fn produced(&self) -> Vec> { stored( @@ -299,6 +306,31 @@ impl Audited for UpdateConfigResponse { } } +impl Audited for UpdateFrozenGlobalConfigResponse { + fn produced(&self) -> Vec> { + self.update + .as_ref() + .map_or_else(Vec::new, Audited::produced) + } +} + +/// A configuration update that reports whether a delete removed a setting. +pub(super) trait ConfigUpdate { + fn deleted(&self) -> bool; +} + +impl ConfigUpdate for UpdateConfigResponse { + fn deleted(&self) -> bool { + self.deleted + } +} + +impl ConfigUpdate for UpdateFrozenGlobalConfigResponse { + fn deleted(&self) -> bool { + self.update.as_ref().is_some_and(|update| update.deleted) + } +} + impl Audited for ApproveDraftChunkResponse { fn produced(&self) -> Vec> { stored_policy(&self.policy_hash) @@ -401,15 +433,15 @@ pub(super) fn deletes_only_a_setting(request: &UpdateConfigRequest) -> bool { /// Run an `UpdateConfig` call, recording a delete that removed no setting /// and changed nothing else as a no-op. -pub(super) async fn record_absent_delete( +pub(super) async fn record_absent_delete( deleting_only: bool, - call: impl Future, Status>>, -) -> Result, Status> { + call: impl Future, Status>>, +) -> Result, Status> { let response = call.await; if deleting_only && response .as_ref() - .is_ok_and(|response| !response.get_ref().deleted) + .is_ok_and(|response| !response.get_ref().deleted()) { audit::record_outcome(Outcome::Detail("no_op:already_absent")); } diff --git a/crates/openshell-server/src/grpc/mutation_audit/tests.rs b/crates/openshell-server/src/grpc/mutation_audit/tests.rs index 16221a3dfd..ea5adb07fd 100644 --- a/crates/openshell-server/src/grpc/mutation_audit/tests.rs +++ b/crates/openshell-server/src/grpc/mutation_audit/tests.rs @@ -449,6 +449,28 @@ async fn creates_name_the_resource_they_produced() { ]) ); + let (result, event) = record_at( + "/openshell.v1.FrozenSandboxPolicies/CreateSandbox", + openshell_core::proto::frozen_sandbox_policies_server::FrozenSandboxPolicies::create_sandbox( + &service, + authed_request(openshell_core::proto::CreateFrozenSandboxRequest { + workspace_scope: Some(workspace_selector("default")), + name: "audit-frozen".into(), + spec: Some(SandboxSpec::default()), + ..Default::default() + }), + ), + ) + .await; + let sandbox = result.unwrap().into_inner().sandbox.unwrap(); + assert_eq!( + event["resources"], + json!([ + default_workspace(), + stored_json("sandbox", sandbox.metadata.as_ref().unwrap()) + ]) + ); + let (result, event) = record( "CreateWorkspace", service.create_workspace(authed_request(CreateWorkspaceRequest { @@ -1205,6 +1227,28 @@ async fn deleting_an_absent_global_setting_records_a_no_op() { event["resources"], json!([{"type": "setting", "name": "ocsf_json_enabled"}]) ); + + // The frozen-policy global update records the same targets and outcome. + let (result, event) = record_at( + "/openshell.v1.FrozenSandboxPolicies/UpdateGlobalConfig", + openshell_core::proto::frozen_sandbox_policies_server::FrozenSandboxPolicies::update_global_config( + &service, + authed_request(openshell_core::proto::UpdateFrozenGlobalConfigRequest { + global: true, + setting_key: "ocsf_json_enabled".into(), + delete_setting: true, + ..Default::default() + }), + ), + ) + .await; + + assert!(!result.unwrap().into_inner().update.unwrap().deleted); + assert_eq!(event["status_detail"], "no_op:already_absent", "{event}"); + assert_eq!( + event["resources"], + json!([{"type": "setting", "name": "ocsf_json_enabled"}]) + ); } #[tokio::test] diff --git a/crates/openshell-server/src/grpc/mutation_replay/ordinary.rs b/crates/openshell-server/src/grpc/mutation_replay/ordinary.rs index 6765171975..006c18bf4b 100644 --- a/crates/openshell-server/src/grpc/mutation_replay/ordinary.rs +++ b/crates/openshell-server/src/grpc/mutation_replay/ordinary.rs @@ -212,6 +212,13 @@ pub(in crate::grpc) enum Outcome { skipped: u32, cleared: u32, }, + FrozenGlobalConfig { + version: u32, + policy_hash: String, + settings_revision: u64, + deleted: bool, + frozen_sandboxes: Vec, + }, Refresh(Refresh), } @@ -496,6 +503,106 @@ scoped_mutation!( |response: &Response| sandbox_receipt(response.get_ref(), false), restore_sandbox_response ); +mutation!( + openshell_core::proto::CreateFrozenSandboxRequest, + openshell_core::proto::FrozenSandboxResponse, + "CreateFrozenSandbox", + crate::grpc::frozen_policy::handle_create, + async |req: &openshell_core::proto::CreateFrozenSandboxRequest, + state: &ServerState, + principal: &Principal| { + selected_scope( + state, + principal, + req.workspace_scope.as_ref(), + MinWorkspaceRole::User, + ) + .await + }, + |response: &Response| { + let response = response.get_ref(); + Ok(Outcome::Sandbox { + id: response + .sandbox + .as_ref() + .ok_or_else(uncertain)? + .object_id() + .into(), + changed: false, + service_urls: response.service_urls.clone(), + application_service_urls: response.application_service_urls.clone(), + gateway_service_urls: Some(response.gateway_service_urls.clone()), + }) + }, + async |store: &Store, outcome: Outcome| { + let response = restore_sandbox_response(store, outcome).await?; + let id = response + .sandbox + .as_ref() + .ok_or_else(replay_unavailable)? + .object_id(); + let frozen_policy = crate::grpc::frozen_policy::state_for(store, id).await?; + if !frozen_policy.requested { + return Err(replay_unavailable()); + } + Ok(openshell_core::proto::FrozenSandboxResponse { + sandbox: response.sandbox, + frozen_policy: Some(frozen_policy), + service_urls: response.service_urls, + application_service_urls: response.application_service_urls, + gateway_service_urls: response.gateway_service_urls, + }) + }, + replay_method = "/openshell.v1.FrozenSandboxPolicies/CreateSandbox" +); +mutation!( + openshell_core::proto::UpdateFrozenGlobalConfigRequest, + openshell_core::proto::UpdateFrozenGlobalConfigResponse, + "UpdateFrozenGlobalConfig", + crate::grpc::frozen_policy::handle_update_global, + async |req: &openshell_core::proto::UpdateFrozenGlobalConfigRequest, + state: &ServerState, + principal: &Principal| { + crate::grpc::frozen_policy::validate_global_request(req)?; + global_scope(state, principal) + }, + |response: &Response| { + if !facts(response)?.global { + return Err(uncertain()); + } + let update = response.get_ref().update.as_ref().ok_or_else(uncertain)?; + Ok(Outcome::FrozenGlobalConfig { + version: update.version, + policy_hash: update.policy_hash.clone(), + settings_revision: update.settings_revision, + deleted: update.deleted, + frozen_sandboxes: response.get_ref().frozen_sandboxes.clone(), + }) + }, + async |_store: &Store, outcome: Outcome| { + let Outcome::FrozenGlobalConfig { + version, + policy_hash, + settings_revision, + deleted, + frozen_sandboxes, + } = outcome + else { + return Err(replay_unavailable()); + }; + Ok(openshell_core::proto::UpdateFrozenGlobalConfigResponse { + update: Some(UpdateConfigResponse { + version, + policy_hash, + settings_revision, + deleted, + annotations: HashMap::new(), + }), + frozen_sandboxes, + }) + }, + replay_method = "/openshell.v1.FrozenSandboxPolicies/UpdateGlobalConfig" +); sandbox_mutation!( openshell_core::proto::UpdateSandboxRequest, "UpdateSandbox", diff --git a/crates/openshell-server/src/grpc/mutation_replay/ordinary/tests.rs b/crates/openshell-server/src/grpc/mutation_replay/ordinary/tests.rs index 1e0c37cb01..4c7f4b5ec1 100644 --- a/crates/openshell-server/src/grpc/mutation_replay/ordinary/tests.rs +++ b/crates/openshell-server/src/grpc/mutation_replay/ordinary/tests.rs @@ -80,6 +80,83 @@ async fn protected_state() -> (tempfile::TempDir, Arc) { (directory, state) } +#[tokio::test] +async fn global_policy_replay_preserves_frozen_sandbox_report() { + let (_directory, state) = protected_state().await; + let policy = openshell_policy::restrictive_default_policy(); + let sandbox = Sandbox { + metadata: Some(meta("frozen-report")), + ..Default::default() + }; + state.store.create_frozen_sandbox(&sandbox).await.unwrap(); + let stored = state + .store + .get_message::(sandbox.object_id()) + .await + .unwrap() + .unwrap(); + state + .store + .accept_frozen_sandbox_configuration( + stored, + openshell_core::proto::FrozenSandboxPolicy { + policy: Some(policy.clone()), + policy_hash: openshell_core::policy_identity::deterministic_policy_hash(&policy), + policy_source: openshell_core::proto::PolicySource::Sandbox.into(), + ..Default::default() + }, + ) + .await + .unwrap(); + let request = openshell_core::proto::UpdateFrozenGlobalConfigRequest { + request_id: id(), + global: true, + policy: Some(policy), + ..Default::default() + }; + let service = crate::grpc::OpenShellService::new(Arc::clone(&state)); + for field in [ + "workspace_scope", + "sandbox", + "merge_operations", + "annotations", + "expected_resource_version", + ] { + let mut invalid = request.clone(); + invalid.request_id = id(); + match field { + "workspace_scope" => { + invalid.workspace_scope = + Some(openshell_core::proto::workspace_selector("default")); + } + "sandbox" => invalid.sandbox = "frozen-report".into(), + "merge_operations" => invalid + .merge_operations + .push(openshell_core::proto::PolicyMergeOperation::default()), + "annotations" => { + invalid.annotations.insert("example".into(), "value".into()); + } + "expected_resource_version" => invalid.expected_resource_version = 1, + _ => unreachable!(), + } + let error = openshell_core::proto::frozen_sandbox_policies_server::FrozenSandboxPolicies::update_global_config( + &service, authed_request(invalid)).await.unwrap_err(); + assert_eq!(error.code(), Code::InvalidArgument, "{field}"); + assert!( + error + .message() + .contains("unsupported for global configuration"), + "{field}: {error}" + ); + } + let original = run(&state, authed_request(request.clone())) + .await + .unwrap() + .into_inner(); + assert_eq!(original.frozen_sandboxes, ["default/frozen-report"]); + assert_eq!(replay(&state, request).await, original); +} + fn configure_key(state: &mut Arc, directory: &tempfile::TempDir) { let key = directory.path().join("private-key"); std::fs::write(&key, b"test-only stable private fingerprint material").unwrap(); @@ -321,6 +398,49 @@ async fn replay(state: &Arc, req: M) -> M::Out response.into_inner() } +#[tokio::test] +async fn frozen_policy_create_replays_mode_without_colliding_with_ordinary_create() { + let (_directory, state) = protected_state().await; + let ordinary = create_sandbox("frozen-replay"); + let request = openshell_core::proto::CreateFrozenSandboxRequest { + workspace_scope: ordinary.workspace_scope.clone(), + spec: ordinary.spec.clone(), + name: ordinary.name.clone(), + request_id: ordinary.request_id.clone(), + ..Default::default() + }; + let created = run(&state, authed_request(request.clone())) + .await + .unwrap() + .into_inner(); + assert!(created.frozen_policy.as_ref().unwrap().requested); + assert!(created.frozen_policy.as_ref().unwrap().policy.is_none()); + let returned = replay(&state, request.clone()).await; + assert_eq!( + returned.sandbox.as_ref().unwrap().object_id(), + created.sandbox.as_ref().unwrap().object_id() + ); + assert!(returned.frozen_policy.unwrap().requested); + // Identical caller request ids are independent across the two RPC services. + assert_eq!( + run(&state, authed_request(ordinary)) + .await + .unwrap_err() + .code(), + Code::AlreadyExists + ); + let sandbox = created.sandbox.unwrap(); + state + .store + .delete_sandbox_with_image_state_if(sandbox.object_id(), sandbox.get_resource_version()) + .await + .unwrap(); + assert_eq!( + reason(&run(&state, authed_request(request)).await.unwrap_err()), + "REQUEST_REPLAY_UNAVAILABLE" + ); +} + #[tokio::test] async fn sandbox_replay_survives_status_churn_but_never_selects_replacement() { let (_directory, state) = protected_state().await; diff --git a/crates/openshell-server/src/grpc/policy.rs b/crates/openshell-server/src/grpc/policy.rs index b9d5fa8fff..1ad9270b8b 100644 --- a/crates/openshell-server/src/grpc/policy.rs +++ b/crates/openshell-server/src/grpc/policy.rs @@ -13,6 +13,7 @@ mod config_inputs; mod discovery_inputs; mod endpoint_status; +pub(super) mod frozen; mod provisioning_clock; #[cfg(test)] mod token_grant_owners_tests; @@ -1810,6 +1811,7 @@ async fn auto_approve_chunk( ) -> Result<(), Status> { let sandbox_id = context.sandbox.object_id(); let sandbox_name = context.sandbox.object_name(); + frozen::ensure_mutable_by_id(state.store.as_ref(), sandbox_id).await?; // Same gate the human-driven approve paths apply: if a global policy is // active, sandbox-scoped chunk approvals are meaningless because @@ -1991,6 +1993,9 @@ async fn current_effective_policy_from_records( sandbox_id: &str, records: &[super::provider::ProviderEnvironmentRecord], ) -> Result<(ProtoSandboxPolicy, PolicySource), Status> { + if let Some(snapshot) = frozen::snapshot(state.store.as_ref(), sandbox).await? { + return Ok((frozen::policy(&snapshot)?, frozen::source(&snapshot)?)); + } let global_settings = load_global_settings(state.store.as_ref()).await?; let global_policy = decode_policy_from_global_settings(&global_settings)?; let latest_policy = if global_policy.is_some() { @@ -2524,6 +2529,12 @@ async fn validate_provider_composition_for_existing_sandboxes( .map_err(|e| Status::internal(format!("list sandboxes failed: {e}")))?; for sandbox in page.messages { + if frozen::snapshot(state.store.as_ref(), &sandbox) + .await? + .is_some() + { + continue; + } let provider_names = sandbox .spec .as_ref() @@ -2811,6 +2822,16 @@ pub(super) async fn handle_get_sandbox_config( state: &Arc, request: Request, ) -> Result, Status> { + handle_get_sandbox_config_with_frozen(state, request) + .await + .map(|(response, _, _)| response) +} + +/// Return the mode from the same captured inputs as the configuration. +pub(super) async fn handle_get_sandbox_config_with_frozen( + state: &Arc, + request: Request, +) -> Result<(Response, bool, bool), Status> { let principal = super::extract_principal(&request)?; let sandbox_name = request.get_ref().name.clone(); let workspace = match (&principal, request.get_ref().workspace_scope.as_ref()) { @@ -2830,9 +2851,27 @@ pub(super) async fn handle_get_sandbox_config( MinWorkspaceRole::User, ) .await?; - Ok(Response::new(sandbox_config_response( - unadmitted_sandbox_config(state, &sandbox, &error), - ))) + let frozen_state = state + .store + .get_sandbox_frozen_policy(sandbox.object_id()) + .await + .map_err(|error| { + Status::internal(format!("fetch frozen policy failed: {error}")) + })?; + let frozen = frozen_state + .as_ref() + .is_some_and(|state| state.policy.is_some()); + let requested = frozen_state.is_some(); + let mut config = unadmitted_sandbox_config(state, &sandbox, &error); + if frozen { + config.configuration_error = + frozen_configuration_failure_diagnostic(&error).to_string(); + } + Ok(( + Response::new(sandbox_config_response(config)), + frozen, + requested, + )) } result => result, } @@ -2878,7 +2917,7 @@ pub fn unadmitted_sandbox_config( async fn handle_get_sandbox_config_inner( state: &Arc, request: Request, -) -> Result, Status> { +) -> Result<(Response, bool, bool), Status> { let principal = super::extract_principal(&request)?; let req = request.into_inner(); let workspace = match &principal { @@ -2893,11 +2932,17 @@ async fn handle_get_sandbox_config_inner( MinWorkspaceRole::User, ) .await?; - let config = load_sandbox_config(state, &sandbox).await?; + let inputs = load_sandbox_config_inputs(state, sandbox).await?; + let frozen = inputs + .frozen + .as_ref() + .is_some_and(|state| state.policy.is_some()); + let config = + sandbox_config_response(build_sandbox_config_snapshot_from_inputs(state, &inputs).await?); if matches!(principal, Principal::Sandbox(_)) { require_policy_capabilities(req.supported_capabilities, config.policy.as_ref())?; } - Ok(Response::new(config)) + Ok((Response::new(config), frozen, inputs.frozen.is_some())) } const CEDAR_SUPPORT_REQUIRED: &str = "Cedar policy requires a supervisor with Cedar support"; @@ -2944,8 +2989,7 @@ pub async fn build_sandbox_config_snapshot( build_sandbox_config_snapshot_from_inputs(state, &inputs).await } -/// Build the effective configuration from captured inputs. Sandbox settings -/// and global policy version metadata are read here. +/// Build the effective configuration from one captured set of inputs. pub async fn build_sandbox_config_snapshot_from_inputs( state: &ServerState, inputs: &SandboxConfigInputs, @@ -2958,10 +3002,12 @@ pub async fn build_sandbox_config_snapshot_from_inputs( &inputs.global_settings, inputs.latest_policy.as_ref(), None, + Some(inputs), ) .await } +#[allow(clippy::too_many_arguments)] async fn build_sandbox_config_snapshot_with_sources( state: &ServerState, sandbox: &Sandbox, @@ -2970,65 +3016,83 @@ async fn build_sandbox_config_snapshot_with_sources( global_settings: &StoredSettings, latest: Option<&PolicyRecord>, service_routes: Option>, + captured: Option<&SandboxConfigInputs>, ) -> Result { let sandbox_id = sandbox.object_id().to_string(); let workspace = sandbox.object_workspace().to_string(); + let frozen_state = captured.and_then(|inputs| inputs.frozen.as_ref()); + let frozen_policy = frozen_state.and_then(|state| state.policy.as_ref()); - let global_policy = decode_policy_from_global_settings(global_settings)?; - let mut global_policy_version: u32 = 0; + let global_policy = if frozen_policy.is_some() { + None + } else { + decode_policy_from_global_settings(global_settings)? + }; + let mut global_policy_version = captured.map_or(0, |inputs| inputs.global_policy_version); // Under a global override, only the sandbox version metadata is observed; // the dormant payload is neither decoded nor validated. - let (mut policy, version, mut policy_hash, policy_source) = - if let Some(global_policy) = global_policy { - let version = latest - .map(|record| u32::try_from(record.version).unwrap_or(0)) - .filter(|version| *version > 0) - .unwrap_or(1); - let hash = deterministic_policy_hash(&global_policy); - (Some(global_policy), version, hash, PolicySource::Global) - } else if let Some(record) = latest { - let (policy, hash) = canonical_policy_record_identity(record)?; - debug!( - sandbox_id = %sandbox_id, - version = record.version, - "GetSandboxConfig served from policy history" - ); - ( - Some(policy), - u32::try_from(record.version).unwrap_or(0), - hash, - PolicySource::Sandbox, - ) - } else { - // Older sandboxes may have policy only in the sandbox spec. Reading a - // snapshot must not create policy history, so project that baseline as - // version 1 until the startup repair persists it. - let spec = sandbox - .spec - .as_ref() - .ok_or_else(|| Status::internal("sandbox has no spec"))?; - - match spec.policy.clone() { - None => (None, 0, String::new(), PolicySource::Sandbox), - Some(spec_policy) => { - let spec_policy = validate_and_canonicalize_stored_policy( - spec_policy, - STORED_POLICY_SOURCE_SPEC, - )?; - let hash = deterministic_policy_hash(&spec_policy); - (Some(spec_policy), 1, hash, PolicySource::Sandbox) - } - } - }; + let (mut policy, version, mut policy_hash, policy_source) = if let Some(frozen) = frozen_policy + { + ( + Some(frozen::policy(frozen)?), + frozen.version, + frozen.policy_hash.clone(), + frozen::source(frozen)?, + ) + } else if let Some(global_policy) = global_policy { + let version = latest + .map(|record| u32::try_from(record.version).unwrap_or(0)) + .filter(|version| *version > 0) + .unwrap_or(1); + let hash = deterministic_policy_hash(&global_policy); + (Some(global_policy), version, hash, PolicySource::Global) + } else if let Some(record) = latest { + let (policy, hash) = canonical_policy_record_identity(record)?; + debug!( + sandbox_id = %sandbox_id, + version = record.version, + "GetSandboxConfig served from policy history" + ); + ( + Some(policy), + u32::try_from(record.version).unwrap_or(0), + hash, + PolicySource::Sandbox, + ) + } else { + // Older sandboxes may have policy only in the sandbox spec. Reading a + // snapshot must not create policy history, so project that baseline as + // version 1 until the startup repair persists it. + let spec = sandbox + .spec + .as_ref() + .ok_or_else(|| Status::internal("sandbox has no spec"))?; - let sandbox_settings = - load_sandbox_settings(state.store.as_ref(), &workspace, sandbox.object_name()).await?; - let mut provider_policy_context = - provider_policy_context_from_records(provider_profile_catalog, provider_records); + match spec.policy.clone() { + None => (None, 0, String::new(), PolicySource::Sandbox), + Some(spec_policy) => { + let spec_policy = validate_and_canonicalize_stored_policy( + spec_policy, + STORED_POLICY_SOURCE_SPEC, + )?; + let hash = deterministic_policy_hash(&spec_policy); + (Some(spec_policy), 1, hash, PolicySource::Sandbox) + } + } + }; - if matches!(policy_source, PolicySource::Global) + let live_settings; + let sandbox_settings = if let Some(inputs) = captured { + inputs.sandbox_settings.as_ref().map_err(Clone::clone)? + } else { + live_settings = + load_sandbox_settings(state.store.as_ref(), &workspace, sandbox.object_name()).await?; + &live_settings + }; + if captured.is_none() + && matches!(policy_source, PolicySource::Global) && let Ok(Some(global_rev)) = state .store .get_latest_policy(GLOBAL_POLICY_SANDBOX_ID) @@ -3036,14 +3100,19 @@ async fn build_sandbox_config_snapshot_with_sources( { global_policy_version = u32::try_from(global_rev.version).unwrap_or(0); } + let mut provider_policy_context = + provider_policy_context_from_records(provider_profile_catalog, provider_records); - if let Some(source_policy) = policy.as_mut() { + if frozen_policy.is_none() + && let Some(source_policy) = policy.as_mut() + { // Never trust provenance supplied by a persisted/user-authored policy. // The gateway derives it from the attached provider catalog below. clear_provider_credentialed_markers(source_policy); } - if !matches!(policy_source, PolicySource::Global) + if frozen_policy.is_none() + && !matches!(policy_source, PolicySource::Global) && let Some(source_policy) = policy.as_ref() && !provider_policy_context.layers.is_empty() { @@ -3073,7 +3142,9 @@ async fn build_sandbox_config_snapshot_with_sources( &provider_policy_context.endpointless_provider_names, ); let mut configuration_error = String::new(); - if let Some(effective_policy) = policy.as_mut() { + if frozen_policy.is_none() + && let Some(effective_policy) = policy.as_mut() + { stamp_provider_credentialed_endpoints( effective_policy, &provider_policy_context.credentialed_scopes, @@ -3098,7 +3169,8 @@ async fn build_sandbox_config_snapshot_with_sources( })?; } - let settings = merge_effective_settings(global_settings, &sandbox_settings)?; + let mut settings = merge_effective_settings(global_settings, sandbox_settings)?; + frozen::disable_proposals(frozen_state.is_some(), &mut settings); let supervisor_middleware_services = state.middleware_registry.required_services(policy.as_ref()); let mut config_revision = compute_config_revision_with_validation_mode( @@ -3117,13 +3189,15 @@ async fn build_sandbox_config_snapshot_with_sources( &policy_credential_bindings, )?; } - let provider_env_revision = compute_provider_env_revision_from_records_and_policy_bindings( + let empty_withheld = std::collections::BTreeSet::new(); + let provider_env_revision = frozen::provider_env_revision( provider_profile_catalog, provider_records, + captured.map_or(&empty_withheld, |inputs| &inputs.withheld_providers), &policy_credential_bindings, policy .as_ref() - .filter(|_| matches!(policy_source, PolicySource::Global)), + .filter(|_| frozen::uses_global_policy(frozen_policy, policy_source)), )?; let service_routes = match service_routes { @@ -3967,13 +4041,21 @@ fn provider_environment_target( .ok_or_else(|| Status::internal("sandbox has no spec"))?; let provider_profile_catalog = &inputs.catalog; let provider_records = &inputs.provider_records; - let (effective_policy, policy_source) = effective_policy_from_captured_inputs( - provider_profile_catalog, - provider_records, - decode_policy_from_global_settings(&inputs.global_settings)?, - inputs.latest_policy.as_ref(), - sandbox, - )?; + let (effective_policy, policy_source) = if let Some(policy) = inputs + .frozen + .as_ref() + .and_then(|state| state.policy.as_ref()) + { + (frozen::policy(policy)?, frozen::source(policy)?) + } else { + effective_policy_from_captured_inputs( + provider_profile_catalog, + provider_records, + decode_policy_from_global_settings(&inputs.global_settings)?, + inputs.latest_policy.as_ref(), + sandbox, + )? + }; let policy_credential_bindings = policy_static_credential_endpoint_bindings(Some(&effective_policy))?; validate_policy_credential_binding_context( @@ -3982,11 +4064,12 @@ fn provider_environment_target( &effective_policy, &policy_credential_bindings, )?; - let provider_env_revision = compute_provider_env_revision_from_records_and_policy_bindings( + let provider_env_revision = frozen::provider_env_revision( provider_profile_catalog, provider_records, + &inputs.withheld_providers, &policy_credential_bindings, - matches!(policy_source, PolicySource::Global).then_some(&effective_policy), + (policy_source == PolicySource::Global).then_some(&effective_policy), )?; Ok(ProviderEnvironmentTarget { spec, @@ -4017,17 +4100,31 @@ pub async fn build_provider_environment_snapshot_from_inputs( let provider_names = &spec.providers; let provider_profile_catalog = &inputs.catalog; let provider_records = &inputs.provider_records; + // A dynamic grant can use the sandbox's identity without a provider secret. + // Withhold the whole provider's delivery, including those grants, when its + // captured authorization no longer matches. Retain unrelated providers. + let authorized_records = if inputs.withheld_providers.is_empty() { + std::borrow::Cow::Borrowed(provider_records.as_slice()) + } else { + std::borrow::Cow::Owned( + provider_records + .iter() + .filter(|record| !inputs.withheld_providers.contains(&record.name)) + .cloned() + .collect::>(), + ) + }; let mut provider_environment = super::provider::resolve_provider_environment_from_records_with_policy_bindings_and_credentials( provider_profile_catalog, - provider_records, + &authorized_records, &policy_credential_bindings, &state.credentials, Some(&sandbox_id), ) .await?; - if matches!(policy_source, PolicySource::Global) { + if policy_source == PolicySource::Global { // A global policy replaces provider ACLs. Grants retain their profile // destination selectors, but only the selected global endpoint may // authorize their use. Keeping every global owner avoids reimplementing @@ -4046,7 +4143,11 @@ pub async fn build_provider_environment_snapshot_from_inputs( } } - let mut readiness_reason = provider_environment.readiness_reason; + let mut readiness_reason = if inputs.withheld_providers.is_empty() { + provider_environment.readiness_reason + } else { + ProviderReadinessReason::CredentialsWithheld + }; if supports_static_credential_bindings { let unbound_static_keys = provider_environment @@ -4352,6 +4453,12 @@ async fn handle_update_config_inner( super::persistence_error_to_status(error, "acquire policy mutation lock") })?; + let frozen_sandboxes = if has_policy || (req.delete_setting && key == POLICY_SETTING_KEY) { + frozen::names(state).await? + } else { + Vec::new() + }; + if has_merge_ops { return Err(Status::invalid_argument( "merge_operations are not supported for global policy updates", @@ -4416,13 +4523,17 @@ async fn handle_update_config_inner( save_global_settings(state.store.as_ref(), &global_settings).await?; crate::config_delivery::publish_all_connected(state); } - return Ok(update_config_response( + let mut response = update_config_response( u32::try_from(current.version).unwrap_or(0), hash, global_settings.revision, false, HashMap::new(), - )); + ); + response + .extensions_mut() + .insert(super::frozen_policy::FrozenSandboxes(frozen_sandboxes)); + return Ok(response); } let next_version = latest.map_or(1, |r| r.version + 1); @@ -4474,13 +4585,17 @@ async fn handle_update_config_inner( crate::config_delivery::publish_all_connected(state); } - return Ok(update_config_response( + let mut response = update_config_response( u32::try_from(next_version).unwrap_or(0), hash, global_settings.revision, false, HashMap::new(), - )); + ); + response + .extensions_mut() + .insert(super::frozen_policy::FrozenSandboxes(frozen_sandboxes)); + return Ok(response); } // Global setting mutation. @@ -4535,13 +4650,17 @@ async fn handle_update_config_inner( } } - return Ok(update_config_response( + let mut response = update_config_response( 0, String::new(), global_settings.revision, req.delete_setting && changed, HashMap::new(), - )); + ); + response + .extensions_mut() + .insert(super::frozen_policy::FrozenSandboxes(frozen_sandboxes)); + return Ok(response); } let sandbox = sandbox.expect("non-global config update resolves a sandbox"); @@ -4620,6 +4739,17 @@ async fn handle_update_config_inner( .as_ref() .ok_or_else(|| Status::invalid_argument("setting_value is required"))?; let stored = proto_setting_to_stored(key, setting)?; + // Frozen delivery forces this setting off from creation. Accepting + // `true` would report success for a value that never takes effect. + if key == settings::AGENT_POLICY_PROPOSALS_ENABLED_KEY + && matches!(setting.value, Some(setting_value::Value::BoolValue(true))) + && frozen::requested(state.store.as_ref(), &sandbox).await? + { + return Err(Status::failed_precondition(format!( + "sandbox '{}' is frozen; agent policy proposals stay off for its lifetime", + sandbox.object_name() + ))); + } let mut sandbox_settings = load_sandbox_settings(state.store.as_ref(), &workspace, sandbox.object_name()).await?; @@ -4662,6 +4792,7 @@ async fn handle_update_config_inner( .map_err(|error| { super::persistence_error_to_status(error, "acquire policy mutation lock") })?; + frozen::ensure_mutable_by_id(state.store.as_ref(), &sandbox_id).await?; if has_merge_ops { let global_settings = load_global_settings(state.store.as_ref()).await?; if global_settings.settings.contains_key(POLICY_SETTING_KEY) { @@ -5113,6 +5244,8 @@ fn bounded_configuration_diagnostic(message: &str) -> String { .collect() } +const CONFIGURATION_NOT_ACTIVATED: &str = "Effective configuration could not be activated; replace the policy or repair attached providers"; + fn configuration_failure_diagnostic(error: &Status) -> &'static str { let message = error.message(); if error.code() == Code::Unimplemented && message == CEDAR_SUPPORT_REQUIRED { @@ -5126,6 +5259,21 @@ fn configuration_failure_diagnostic(error: &Status) -> &'static str { } } +/// The same categories for a captured policy. Its policy and providers cannot +/// be replaced, so the ordinary advice would send the operator nowhere. +fn frozen_configuration_failure_diagnostic(error: &Status) -> &'static str { + let message = error.message(); + if error.code() == Code::Unimplemented && message == CEDAR_SUPPORT_REQUIRED { + "Frozen policy is a Cedar policy, which this supervisor cannot enforce; run the sandbox with a supervisor built with Cedar support, or delete and recreate the sandbox" + } else if message.contains("middleware") { + "Frozen middleware configuration is invalid; repair the registered middleware services, or delete and recreate the sandbox" + } else if message.contains("credential") || message.contains("provider") { + "Frozen provider configuration is invalid; restore the providers the sandbox captured, or delete and recreate the sandbox" + } else { + "Frozen policy failed structure or safety validation and cannot be replaced; delete and recreate the sandbox" + } +} + fn configuration_generation_matches( admission: &openshell_core::proto::SandboxConfigurationAdmission, config: &GetSandboxConfigResponse, @@ -5214,23 +5362,37 @@ pub(super) async fn handle_report_sandbox_configuration( "supervisor configuration instance has changed", )); } + let mut frozen_policy = None; if reported == ConfigurationAdmissionState::Accepted { - let mut config_request = Request::new(GetSandboxConfigRequest { - supported_capabilities: vec![ - openshell_core::extension_protocol::POLICY_CEDAR_V1.to_string(), - ], - name: sandbox_name.clone(), - workspace_scope: Some(openshell_core::proto::workspace_selector(workspace.clone())), - }); - *config_request.extensions_mut() = request.extensions().clone(); - let config = handle_get_sandbox_config(state, config_request) - .await? - .into_inner(); + const NOT_ADMITTED: &str = + "configuration changed or is not admitted; fetch and validate again"; + // A stored configuration that no longer builds is not admitted. The + // supervisor fetches again and reports the rejection instead of exiting. + let not_admitted = |error: Status| { + if is_configuration_rejection(&error) { + Status::aborted(NOT_ADMITTED) + } else { + error + } + }; + let inputs = load_sandbox_config_inputs(state, sandbox.clone()) + .await + .map_err(not_admitted)?; + let config = sandbox_config_response( + build_sandbox_config_snapshot_from_inputs(state, &inputs) + .await + .map_err(not_admitted)?, + ); if !config.configuration_admitted || !configuration_generation_matches(&admission, &config) { - return Err(Status::aborted( - "configuration changed or is not admitted; fetch and validate again", - )); + return Err(Status::aborted(NOT_ADMITTED)); + } + if inputs + .frozen + .as_ref() + .is_some_and(|state| state.policy.is_none()) + { + frozen_policy = Some(frozen::capture(&config, &inputs, current_time_ms())?); } admission.error.clear(); } else if reported == ConfigurationAdmissionState::Rejected { @@ -5244,12 +5406,34 @@ pub(super) async fn handle_report_sandbox_configuration( name: sandbox_name, }); *config_request.extensions_mut() = request.extensions().clone(); - admission.error = match handle_get_sandbox_config(state, config_request).await { - Ok(config) if !configuration_generation_matches(&admission, config.get_ref()) => { - return Err(Status::aborted("rejected configuration generation has changed")); + admission.error = match handle_get_sandbox_config_with_frozen(state, config_request).await { + Ok((config, _, _)) + if !configuration_generation_matches(&admission, config.get_ref()) => + { + return Err(Status::aborted( + "rejected configuration generation has changed", + )); + } + Ok((config, _, _)) if !config.get_ref().configuration_error.is_empty() => { + config.into_inner().configuration_error + } + // The configuration builds, so the runtime refused it. Name the + // repair a frozen sandbox still allows. + Ok((config, captured, requested)) => { + frozen::rejection_diagnostic(captured, requested, config.get_ref().policy_source()) + .unwrap_or(CONFIGURATION_NOT_ACTIVATED) + .to_string() + } + // The configuration could not be read back. A captured policy + // still cannot be replaced, whatever its source was. + Err(_) => { + let captured = frozen::snapshot(state.store.as_ref(), &sandbox) + .await? + .is_some(); + frozen::rejection_diagnostic(captured, captured, PolicySource::Unspecified) + .unwrap_or(CONFIGURATION_NOT_ACTIVATED) + .to_string() } - Ok(config) if !config.get_ref().configuration_error.is_empty() => config.into_inner().configuration_error, - _ => "Effective configuration could not be activated; replace the policy or repair attached providers".to_string(), }; if let Some(current) = current && current.state == i32::from(ConfigurationAdmissionState::Accepted) @@ -5300,31 +5484,57 @@ pub(super) async fn handle_report_sandbox_configuration( .map_err(Status::internal)?; } } - let updated = state - .store - .update_message_cas::(&sandbox_id, expected_version, |sandbox| { - sandbox - .status - .get_or_insert_with(Default::default) - .provisioning - .clone_from(&provisioning); + let update = |sandbox: &mut Sandbox| { + sandbox + .status + .get_or_insert_with(Default::default) + .provisioning + .clone_from(&provisioning); + sandbox + .status + .get_or_insert_with(Default::default) + .configuration_admission = Some(admission.clone()); + if reported == ConfigurationAdmissionState::Accepted { sandbox .status - .get_or_insert_with(Default::default) - .configuration_admission = Some(admission.clone()); - if reported == ConfigurationAdmissionState::Accepted { - sandbox - .status - .as_mut() - .expect("status initialized") - .configuration_activated = Some(true); - } - crate::compute::apply_configuration_readiness(sandbox); - }) - .await - .map_err(|error| { - super::persistence_error_to_status(error, "report configuration admission") - })?; + .as_mut() + .expect("status initialized") + .configuration_activated = Some(true); + } + crate::compute::apply_configuration_readiness(sandbox); + }; + let updated = if let Some(policy) = frozen_policy { + update(&mut sandbox); + let (version, hash, providers) = ( + policy.version, + policy.policy_hash.clone(), + policy.providers.len(), + ); + let accepted = state + .store + .accept_frozen_sandbox_configuration(sandbox, policy) + .await; + if let Ok(sandbox) = &accepted { + // No user request causes the capture, so the API audit trail has + // no record of it. This is the one line that says when it froze. + info!( + sandbox_id = %sandbox_id, + sandbox = %sandbox.object_name(), + workspace = %sandbox.object_workspace(), + policy_version = version, + policy_hash = %hash, + providers, + "sandbox policy frozen at first accepted configuration" + ); + } + accepted + } else { + state + .store + .update_message_cas::(&sandbox_id, expected_version, update) + .await + } + .map_err(|error| super::persistence_error_to_status(error, "report configuration admission"))?; state.sandbox_index.update_from_sandbox(&updated); state.sandbox_watch_bus.notify(&sandbox_id); Ok(Response::new( @@ -5772,6 +5982,17 @@ pub(super) async fn handle_submit_policy_analysis( })); } + // Network activity remains observable, but a frozen sandbox does not + // generate proposals or enter an automatic approval path. + if frozen::requested(state.store.as_ref(), &sandbox).await? { + return Ok(Response::new(SubmitPolicyAnalysisResponse { + accepted_chunks: 0, + rejected_chunks: u32::try_from(req.proposed_chunks.len()).unwrap_or(u32::MAX), + rejection_reasons: vec![frozen::refusal(&sandbox)], + accepted_chunk_ids: Vec::new(), + })); + } + // `current_policy` is captured ONCE at the top of the batch and frozen // for every chunk's delta computation, even if an earlier chunk in the // batch auto-approves and merges. This is intentional v1 behavior: @@ -6269,6 +6490,7 @@ async fn handle_approve_draft_chunk_inner( return Err(Status::invalid_argument("chunk_id is required")); } + frozen::ensure_mutable(state.store.as_ref(), &sandbox).await?; require_no_global_policy(state).await?; let sandbox_id = sandbox.object_id().to_string(); @@ -6413,6 +6635,7 @@ async fn handle_reject_draft_chunk_inner( ) .await?; let workspace = sandbox.object_workspace().to_string(); + frozen::ensure_mutable(state.store.as_ref(), &sandbox).await?; if req.chunk_id.is_empty() { return Err(Status::invalid_argument("chunk_id is required")); } @@ -6520,6 +6743,7 @@ async fn handle_approve_all_draft_chunks_inner( .await?; let workspace = sandbox.object_workspace().to_string(); + frozen::ensure_mutable(state.store.as_ref(), &sandbox).await?; require_no_global_policy(state).await?; let sandbox_id = sandbox.object_id().to_string(); @@ -6823,6 +7047,7 @@ pub(super) async fn handle_edit_draft_chunk( ) .await?; let workspace = sandbox.object_workspace().to_string(); + frozen::ensure_mutable(state.store.as_ref(), &sandbox).await?; if req.chunk_id.is_empty() { return Err(Status::invalid_argument("chunk_id is required")); } @@ -6899,6 +7124,7 @@ async fn handle_undo_draft_chunk_inner( ) .await?; let workspace = sandbox.object_workspace().to_string(); + frozen::ensure_mutable(state.store.as_ref(), &sandbox).await?; if req.chunk_id.is_empty() { return Err(Status::invalid_argument("chunk_id is required")); } @@ -7872,6 +8098,7 @@ async fn apply_merge_operations_with_retry( ) -> Result<(i64, String, Option), Status> { let provider_layers = validation_context.provider_layers; for attempt in 1..=MERGE_RETRY_LIMIT { + frozen::ensure_mutable_by_id(store, sandbox_id).await?; let latest = store .get_latest_policy(sandbox_id) .await @@ -8476,6 +8703,7 @@ fn materialize_global_settings( #[cfg(test)] mod tests { + include!("policy/frozen_tests.rs"); use super::*; use crate::auth::audit::test_support::assert_boundary_finding; use crate::auth::identity::{Identity, IdentityProvider}; @@ -10644,6 +10872,15 @@ mod tests { for (case, legacy_policy) in defaulted_mcp_policy_cases() { let sandbox_id = format!("identity-merge-default-{case}"); + store + .put_message(&test_sandbox( + &sandbox_id, + &sandbox_id, + legacy_policy.clone(), + vec![], + )) + .await + .unwrap(); store .put_policy_revision( &format!("policy-identity-merge-default-{case}"), @@ -12575,7 +12812,7 @@ mod tests { id: "sb-no-policy".to_string(), name: "no-policy-sandbox".to_string(), created_time: openshell_core::time::timestamp_from_millis(1_000_000).ok(), - labels: std::collections::HashMap::new(), + labels: HashMap::new(), resource_version: 0, annotations: HashMap::new(), workspace: "default".to_string(), @@ -14386,6 +14623,16 @@ mod tests { .map(|(rule_name, rule)| PolicyMergeOp::AddRule { rule_name, rule }) .collect::>(); + state + .store + .put_message(&test_sandbox( + "sb-ambiguous-merge", + "ambiguous-merge", + openshell_policy::restrictive_default_policy(), + vec![], + )) + .await + .unwrap(); let error = apply_merge_operations_with_retry( state.store.as_ref(), "sb-ambiguous-merge", @@ -16965,7 +17212,7 @@ mod tests { id: "sb-backfill".to_string(), name: "backfill-sandbox".to_string(), created_time: openshell_core::time::timestamp_from_millis(1_000_000).ok(), - labels: std::collections::HashMap::new(), + labels: HashMap::new(), resource_version: 0, annotations: HashMap::new(), workspace: "default".to_string(), @@ -17952,7 +18199,7 @@ mod tests { id: "sb-draft-flow".to_string(), name: "draft-flow".to_string(), created_time: openshell_core::time::timestamp_from_millis(1_000_000).ok(), - labels: std::collections::HashMap::new(), + labels: HashMap::new(), resource_version: 0, annotations: HashMap::new(), workspace: "default".to_string(), @@ -18211,7 +18458,7 @@ mod tests { id: "sb-feedback".to_string(), name: sandbox_name.clone(), created_time: openshell_core::time::timestamp_from_millis(1_000_000).ok(), - labels: std::collections::HashMap::new(), + labels: HashMap::new(), resource_version: 0, annotations: HashMap::new(), workspace: "default".to_string(), @@ -18317,7 +18564,7 @@ mod tests { id: "sb-agent-l7-verdict".to_string(), name: sandbox_name.clone(), created_time: openshell_core::time::timestamp_from_millis(1_000_000).ok(), - labels: std::collections::HashMap::new(), + labels: HashMap::new(), resource_version: 0, annotations: HashMap::new(), workspace: "default".to_string(), @@ -18438,7 +18685,7 @@ mod tests { id: "sb-supersede-flow".to_string(), name: sandbox_name.clone(), created_time: openshell_core::time::timestamp_from_millis(1_000_000).ok(), - labels: std::collections::HashMap::new(), + labels: HashMap::new(), resource_version: 0, annotations: HashMap::new(), workspace: "default".to_string(), @@ -18651,7 +18898,7 @@ mod tests { id: "sb-mechanistic-clean".to_string(), name: sandbox_name.clone(), created_time: openshell_core::time::timestamp_from_millis(1_000_000).ok(), - labels: std::collections::HashMap::new(), + labels: HashMap::new(), resource_version: 0, annotations: HashMap::new(), workspace: "default".to_string(), @@ -19906,7 +20153,7 @@ mod tests { id: "sb-l7-full-with-cred".to_string(), name: sandbox_name.clone(), created_time: openshell_core::time::timestamp_from_millis(1_000_000).ok(), - labels: std::collections::HashMap::new(), + labels: HashMap::new(), resource_version: 0, annotations: HashMap::new(), workspace: "default".to_string(), @@ -20017,7 +20264,7 @@ mod tests { id: "sb-default-manual-mode".to_string(), name: sandbox_name.clone(), created_time: openshell_core::time::timestamp_from_millis(1_000_000).ok(), - labels: std::collections::HashMap::new(), + labels: HashMap::new(), resource_version: 0, annotations: HashMap::new(), workspace: "default".to_string(), @@ -20116,7 +20363,7 @@ mod tests { id: "sb-unknown-mode".to_string(), name: sandbox_name.clone(), created_time: openshell_core::time::timestamp_from_millis(1_000_000).ok(), - labels: std::collections::HashMap::new(), + labels: HashMap::new(), resource_version: 0, annotations: HashMap::new(), workspace: "default".to_string(), @@ -20207,7 +20454,7 @@ mod tests { id: "sb-explicit-manual-mode".to_string(), name: sandbox_name.clone(), created_time: openshell_core::time::timestamp_from_millis(1_000_000).ok(), - labels: std::collections::HashMap::new(), + labels: HashMap::new(), resource_version: 0, annotations: HashMap::new(), workspace: "default".to_string(), @@ -20300,7 +20547,7 @@ mod tests { id: "sb-gateway-auto-mode".to_string(), name: sandbox_name.clone(), created_time: openshell_core::time::timestamp_from_millis(1_000_000).ok(), - labels: std::collections::HashMap::new(), + labels: HashMap::new(), resource_version: 0, annotations: HashMap::new(), workspace: "default".to_string(), @@ -20393,7 +20640,7 @@ mod tests { id: "sb-gateway-pinned-manual".to_string(), name: sandbox_name.clone(), created_time: openshell_core::time::timestamp_from_millis(1_000_000).ok(), - labels: std::collections::HashMap::new(), + labels: HashMap::new(), resource_version: 0, annotations: HashMap::new(), workspace: "default".to_string(), @@ -20491,7 +20738,7 @@ mod tests { id: "sb-reject-provider-prefix".to_string(), name: sandbox_name.clone(), created_time: openshell_core::time::timestamp_from_millis(1_000_000).ok(), - labels: std::collections::HashMap::new(), + labels: HashMap::new(), resource_version: 0, annotations: HashMap::new(), workspace: "default".to_string(), @@ -20761,7 +21008,7 @@ mod tests { id: "sb-agent-l4-with-cred".to_string(), name: sandbox_name.clone(), created_time: openshell_core::time::timestamp_from_millis(1_000_000).ok(), - labels: std::collections::HashMap::new(), + labels: HashMap::new(), resource_version: 0, annotations: HashMap::new(), workspace: "default".to_string(), @@ -20864,7 +21111,7 @@ mod tests { id: "sb-agent-l4-no-cred".to_string(), name: sandbox_name.clone(), created_time: openshell_core::time::timestamp_from_millis(1_000_000).ok(), - labels: std::collections::HashMap::new(), + labels: HashMap::new(), resource_version: 0, annotations: HashMap::new(), workspace: "default".to_string(), @@ -20955,7 +21202,7 @@ mod tests { id: "sb-agent-link-local".to_string(), name: sandbox_name.clone(), created_time: openshell_core::time::timestamp_from_millis(1_000_000).ok(), - labels: std::collections::HashMap::new(), + labels: HashMap::new(), resource_version: 0, annotations: HashMap::new(), workspace: "default".to_string(), @@ -21342,7 +21589,7 @@ mod tests { id: "sb-full-loop-v2".to_string(), name: sandbox_name.clone(), created_time: openshell_core::time::timestamp_from_millis(1_000_000).ok(), - labels: std::collections::HashMap::new(), + labels: HashMap::new(), resource_version: 0, annotations: HashMap::new(), workspace: "default".to_string(), @@ -21534,7 +21781,7 @@ mod tests { id: "sb-redraft".to_string(), name: sandbox_name.clone(), created_time: openshell_core::time::timestamp_from_millis(1_000_000).ok(), - labels: std::collections::HashMap::new(), + labels: HashMap::new(), resource_version: 0, annotations: HashMap::new(), workspace: "default".to_string(), @@ -21658,7 +21905,7 @@ mod tests { id: "sb-mech-dedup".to_string(), name: sandbox_name.clone(), created_time: openshell_core::time::timestamp_from_millis(1_000_000).ok(), - labels: std::collections::HashMap::new(), + labels: HashMap::new(), resource_version: 0, annotations: HashMap::new(), workspace: "default".to_string(), @@ -21768,9 +22015,9 @@ mod tests { id: sandbox_id.to_string(), name: sandbox_name.clone(), created_time: openshell_core::time::timestamp_from_millis(1_000_000).ok(), - labels: std::collections::HashMap::new(), + labels: HashMap::new(), resource_version: 0, - annotations: std::collections::HashMap::new(), + annotations: HashMap::new(), workspace: "default".to_string(), deletion_time: None, }), @@ -22046,7 +22293,7 @@ mod tests { id: "sb-undo-clears".to_string(), name: sandbox_name.clone(), created_time: openshell_core::time::timestamp_from_millis(1_000_000).ok(), - labels: std::collections::HashMap::new(), + labels: HashMap::new(), resource_version: 0, annotations: HashMap::new(), workspace: "default".to_string(), @@ -22189,7 +22436,7 @@ mod tests { id: "sb-draft-owner".to_string(), name: "draft-owner".to_string(), created_time: openshell_core::time::timestamp_from_millis(1_000_000).ok(), - labels: std::collections::HashMap::new(), + labels: HashMap::new(), resource_version: 0, annotations: HashMap::new(), workspace: "default".to_string(), @@ -22208,7 +22455,7 @@ mod tests { id: "sb-draft-other".to_string(), name: "draft-other".to_string(), created_time: openshell_core::time::timestamp_from_millis(1_000_001).ok(), - labels: std::collections::HashMap::new(), + labels: HashMap::new(), resource_version: 0, annotations: HashMap::new(), workspace: "default".to_string(), @@ -22496,7 +22743,7 @@ mod tests { id: format!("sb-{name}"), name: name.to_string(), created_time: openshell_core::time::timestamp_from_millis(1_000_000).ok(), - labels: std::collections::HashMap::new(), + labels: HashMap::new(), resource_version: 0, annotations: HashMap::new(), workspace: "default".to_string(), @@ -22807,6 +23054,16 @@ mod tests { ..Default::default() }; + store + .put_message(&test_sandbox( + &chunk.sandbox_id, + &chunk.sandbox_id, + openshell_policy::restrictive_default_policy(), + vec![], + )) + .await + .unwrap(); + let (version, _) = merge_chunk_into_policy(&store, &chunk.sandbox_id, "default", &chunk, &[]) .await @@ -22857,6 +23114,16 @@ mod tests { .collect(), ..Default::default() }; + store + .put_message(&test_sandbox( + sandbox_id, + sandbox_id, + openshell_policy::restrictive_default_policy(), + vec![], + )) + .await + .unwrap(); + store .put_policy_revision( "p-seed", @@ -22958,6 +23225,16 @@ mod tests { .collect(), ..Default::default() }; + store + .put_message(&test_sandbox( + sandbox_id, + sandbox_id, + openshell_policy::restrictive_default_policy(), + vec![], + )) + .await + .unwrap(); + store .put_policy_revision( "p-seed", @@ -23046,6 +23323,16 @@ mod tests { .collect(), ..Default::default() }; + store + .put_message(&test_sandbox( + sandbox_id, + sandbox_id, + openshell_policy::restrictive_default_policy(), + vec![], + )) + .await + .unwrap(); + store .put_policy_revision( "p-seed", diff --git a/crates/openshell-server/src/grpc/policy/config_inputs.rs b/crates/openshell-server/src/grpc/policy/config_inputs.rs index f8905bc992..abf4693b1d 100644 --- a/crates/openshell-server/src/grpc/policy/config_inputs.rs +++ b/crates/openshell-server/src/grpc/policy/config_inputs.rs @@ -10,14 +10,19 @@ //! independent, not one database transaction, and credential values are //! resolved later by the provider builder alone. +use std::collections::BTreeSet; + use openshell_core::proto::Sandbox; use tonic::Status; use super::super::StoredSettings; use super::super::provider::{ProviderEnvironmentRecord, load_provider_environment_records}; -use super::load_global_settings; +use super::{ + GLOBAL_POLICY_SANDBOX_ID, decode_policy_from_global_settings, frozen, load_global_settings, + load_sandbox_settings, +}; use crate::ServerState; -use crate::persistence::{ObjectId, ObjectWorkspace, PolicyRecord}; +use crate::persistence::{ObjectId, ObjectName, ObjectWorkspace, PolicyRecord}; use crate::policy_store::PolicyStoreExt as _; use crate::provider_profile_sources::EffectiveProviderProfileCatalog; @@ -31,9 +36,15 @@ pub struct SandboxConfigInputs { /// Records in `spec.providers` order, which the provider revision hashes. pub(super) provider_records: Vec, pub(super) global_settings: StoredSettings, + pub(super) sandbox_settings: Result, + pub(super) global_policy_version: u32, /// Observed for its version metadata even under a global policy, whose /// dormant sandbox payload is never decoded. pub(super) latest_policy: Option, + /// Frozen providers whose current authorization no longer matches the + /// captured one. Always empty for live sandboxes. + pub(super) withheld_providers: BTreeSet, + pub(super) frozen: Option, } impl SandboxConfigInputs { @@ -47,15 +58,72 @@ impl SandboxConfigInputs { pub async fn load_sandbox_config_inputs( state: &ServerState, sandbox: Sandbox, +) -> Result { + // Keep the captured-input resolver's state machine off every caller's + // stack; configuration, readiness and credential RPCs share this boundary. + Box::pin(async move { + let store = state.store.as_ref(); + let frozen = store + .get_sandbox_frozen_policy(sandbox.object_id()) + .await + .map_err(|error| Status::internal(format!("fetch frozen policy failed: {error}")))?; + let pending = frozen.as_ref().is_some_and(|state| state.policy.is_none()); + let inputs = load_inputs(state, sandbox.clone(), frozen).await; + // Capture is the only allowed mode transition. Recheck after every live + // authorization/composition read, including errors from now-obsolete inputs. + if pending + && let Some(captured) = store + .get_sandbox_frozen_policy(sandbox.object_id()) + .await + .map_err(|error| Status::internal(format!("fetch frozen policy failed: {error}")))? + && captured.policy.is_some() + { + return load_inputs(state, sandbox, Some(captured)).await; + } + inputs + }) + .await +} + +async fn load_inputs( + state: &ServerState, + sandbox: Sandbox, + frozen: Option, ) -> Result { let store = state.store.as_ref(); + if let Some(captured) = frozen.as_ref().and_then(|state| state.policy.as_ref()) { + // A frozen sandbox reads its captured catalog and provider identities, + // and never the live policy history. + let (context, global_settings, sandbox_settings) = tokio::try_join!( + frozen::provider_context_from_snapshot(state, &sandbox, captured), + load_global_settings(store), + async { + Ok::<_, Status>( + load_sandbox_settings(store, sandbox.object_workspace(), sandbox.object_name()) + .await, + ) + }, + )?; + let global_policy_version = captured.global_policy_version; + return Ok(SandboxConfigInputs { + sandbox, + catalog: context.catalog, + provider_records: context.records, + global_settings, + sandbox_settings, + global_policy_version, + latest_policy: None, + withheld_providers: context.withheld_providers, + frozen, + }); + } let workspace = sandbox.object_workspace(); let provider_names = sandbox .spec .as_ref() .map(|spec| spec.providers.as_slice()) .unwrap_or_default(); - let (catalog, provider_records, global_settings, latest_policy) = tokio::try_join!( + let (catalog, provider_records, global_settings, latest_policy, sandbox_settings) = tokio::try_join!( state .provider_profile_sources .snapshot_catalog(store, workspace), @@ -67,12 +135,29 @@ pub async fn load_sandbox_config_inputs( .await .map_err(|e| Status::internal(format!("fetch policy history failed: {e}"))) }, + async { + Ok::<_, Status>(load_sandbox_settings(store, workspace, sandbox.object_name()).await) + }, )?; + let global_policy_version = if decode_policy_from_global_settings(&global_settings)?.is_some() { + store + .get_latest_policy(GLOBAL_POLICY_SANDBOX_ID) + .await + .ok() + .flatten() + .map_or(0, |record| u32::try_from(record.version).unwrap_or(0)) + } else { + 0 + }; Ok(SandboxConfigInputs { sandbox, catalog, provider_records, global_settings, + sandbox_settings, + global_policy_version, latest_policy, + withheld_providers: BTreeSet::new(), + frozen, }) } diff --git a/crates/openshell-server/src/grpc/policy/discovery_inputs.rs b/crates/openshell-server/src/grpc/policy/discovery_inputs.rs index cef0f0315a..6f19a86c22 100644 --- a/crates/openshell-server/src/grpc/policy/discovery_inputs.rs +++ b/crates/openshell-server/src/grpc/policy/discovery_inputs.rs @@ -12,7 +12,9 @@ use tonic::Status; use super::super::StoredSettings; use super::super::provider::load_provider_environment_records; -use super::{build_sandbox_config_snapshot_with_sources, load_global_settings}; +use super::{ + build_sandbox_config_snapshot_with_sources, load_global_settings, load_sandbox_config_inputs, +}; use crate::ServerState; use crate::persistence::{ObjectListQuery, ObjectType}; use crate::policy_store::PolicyStoreExt as _; @@ -146,25 +148,6 @@ impl DiscoveryConfigInputs { if sandbox.object_workspace() != self.workspace { return Err(Status::internal("installation workspace mismatch")); } - let providers = sandbox - .spec - .as_ref() - .map_or(&[][..], |spec| spec.providers.as_slice()); - let (records, latest) = tokio::try_join!( - load_provider_environment_records( - &state.store, - &state.refresh, - &self.workspace, - providers - ), - async { - state - .store - .get_latest_policy(sandbox.object_id()) - .await - .map_err(|_| Status::unavailable("sandbox policy unavailable")) - }, - )?; let routes = if let Some(declarations) = &self.declarations { let endpoints = declarations .by_sandbox @@ -185,6 +168,47 @@ impl DiscoveryConfigInputs { } else { None }; + // Frozen mode is fixed at creation. Pending captures must use the + // shared loader's recheck; they cannot use collection-local live sources. + if state + .store + .get_sandbox_frozen_policy(sandbox.object_id()) + .await + .map_err(|error| Status::internal(format!("fetch frozen policy failed: {error}")))? + .is_some() + { + let inputs = load_sandbox_config_inputs(state, sandbox.clone()).await?; + return build_sandbox_config_snapshot_with_sources( + state, + &inputs.sandbox, + &inputs.catalog, + &inputs.provider_records, + &inputs.global_settings, + inputs.latest_policy.as_ref(), + routes, + Some(&inputs), + ) + .await; + } + let providers = sandbox + .spec + .as_ref() + .map_or(&[][..], |spec| spec.providers.as_slice()); + let (records, latest) = tokio::try_join!( + load_provider_environment_records( + &state.store, + &state.refresh, + &self.workspace, + providers + ), + async { + state + .store + .get_latest_policy(sandbox.object_id()) + .await + .map_err(|_| Status::unavailable("sandbox policy unavailable")) + }, + )?; build_sandbox_config_snapshot_with_sources( state, sandbox, @@ -193,6 +217,7 @@ impl DiscoveryConfigInputs { &self.global_settings, latest.as_ref(), routes, + None, ) .await } diff --git a/crates/openshell-server/src/grpc/policy/endpoint_status.rs b/crates/openshell-server/src/grpc/policy/endpoint_status.rs index 0a093c2e8c..5aa609c247 100644 --- a/crates/openshell-server/src/grpc/policy/endpoint_status.rs +++ b/crates/openshell-server/src/grpc/policy/endpoint_status.rs @@ -257,20 +257,30 @@ async fn current_endpoint_context( state: &ServerState, sandbox: &Sandbox, ) -> Result { - let workspace = sandbox.object_workspace(); - let catalog = state - .provider_profile_sources - .snapshot_catalog(state.store.as_ref(), workspace) + if let Some(snapshot) = super::frozen::snapshot(state.store.as_ref(), sandbox).await? { + return frozen_endpoint_context(state, sandbox, &snapshot).await; + } + let live = async { + let workspace = sandbox.object_workspace(); + let catalog = state + .provider_profile_sources + .snapshot_catalog(state.store.as_ref(), workspace) + .await?; + let policy = current_effective_policy_for_sandbox( + state, + &catalog, + workspace, + sandbox, + sandbox.object_id(), + ) .await?; - let policy = current_effective_policy_for_sandbox( - state, - &catalog, - workspace, - sandbox, - sandbox.object_id(), - ) - .await?; - derive_endpoint_context(state, sandbox, &catalog, policy).await + derive_endpoint_context(state, sandbox, &catalog, policy).await + } + .await; + if let Some(snapshot) = super::frozen::snapshot(state.store.as_ref(), sandbox).await? { + return frozen_endpoint_context(state, sandbox, &snapshot).await; + } + live } async fn active_endpoint_context( @@ -297,21 +307,51 @@ async fn endpoint_context_for_loaded_policy( sandbox: &Sandbox, version: i64, ) -> Result { - let workspace = sandbox.object_workspace(); - let catalog = state - .provider_profile_sources - .snapshot_catalog(state.store.as_ref(), workspace) - .await?; - let global_settings = load_global_settings(state.store.as_ref()).await?; - let global_policy = decode_policy_from_global_settings(&global_settings)?; - endpoint_context_for_loaded_policy_with_inputs( - state, - sandbox, - version, - &catalog, - global_policy.as_ref(), - ) - .await + if let Some(snapshot) = super::frozen::snapshot(state.store.as_ref(), sandbox).await? { + return frozen_endpoint_context(state, sandbox, &snapshot).await; + } + let live = async { + let workspace = sandbox.object_workspace(); + let catalog = state + .provider_profile_sources + .snapshot_catalog(state.store.as_ref(), workspace) + .await?; + let global_settings = load_global_settings(state.store.as_ref()).await?; + let global_policy = decode_policy_from_global_settings(&global_settings)?; + endpoint_context_for_loaded_policy_with_inputs( + state, + sandbox, + version, + &catalog, + global_policy.as_ref(), + ) + .await + } + .await; + if let Some(snapshot) = super::frozen::snapshot(state.store.as_ref(), sandbox).await? { + return frozen_endpoint_context(state, sandbox, &snapshot).await; + } + live +} + +async fn frozen_endpoint_context( + state: &ServerState, + sandbox: &Sandbox, + snapshot: &openshell_core::proto::FrozenSandboxPolicy, +) -> Result { + let policy = super::frozen::policy(snapshot)?; + let providers = super::frozen::provider_context_from_snapshot(state, sandbox, snapshot).await?; + let bindings = policy_static_credential_endpoint_bindings(Some(&policy))?; + let provider_env_revision = providers.revision( + &bindings, + super::frozen::uses_global_policy(Some(snapshot), super::frozen::source(snapshot)?) + .then_some(&policy), + )?; + Ok(EndpointContext { + policy_hash: snapshot.policy_hash.clone(), + provider_env_revision, + endpoints: expected_endpoint_statuses(&policy), + }) } async fn endpoint_context_for_loaded_policy_with_inputs( @@ -995,6 +1035,16 @@ pub(super) async fn endpoint_status_reset_for_loaded_policy( sandbox: &Sandbox, version: i64, ) -> Result>, Status> { + let current_version = i64::from(sandbox.current_policy_version()); + if let Some(snapshot) = super::frozen::snapshot(state.store.as_ref(), sandbox).await? { + // Every acknowledged revision of an initialized frozen sandbox resolves + // to the captured authorization. Never consult today's profile source + // or global override when replacing its supervisor. + let context = frozen_endpoint_context(state, sandbox, &snapshot).await?; + let same_configuration = + current_version != 0 || endpoint_cursor_matches_context(state, sandbox, &context); + return Ok((!same_configuration).then(|| unknown_endpoint_reports(&context.endpoints))); + } // Both policy versions must use one provider/profile and global-policy view; // an external catalog can change between independent snapshot requests. let catalog = state @@ -1011,7 +1061,6 @@ pub(super) async fn endpoint_status_reset_for_loaded_policy( global_policy.as_ref(), ) .await?; - let current_version = i64::from(sandbox.current_policy_version()); let same_configuration = if current_version == version { // An acknowledgement can be retried after endpoint reports have already // committed. Repeating activation must not erase their accepted evidence. @@ -1033,22 +1082,30 @@ pub(super) async fn endpoint_status_reset_for_loaded_policy( // The first endpoint report and load acknowledgement travel independently. // Only the current session's accepted report proves which configuration // produced evidence before any loaded policy version has been recorded. - state - .supervisor_sessions - .current_session_id(sandbox.object_id()) - .and_then(|session_id| { - state - .supervisor_sessions - .endpoint_report_cursor(sandbox.object_id(), &session_id) - }) - .is_some_and(|cursor| { - cursor.policy_hash == context.policy_hash - && cursor.provider_env_revision == context.provider_env_revision - }) + endpoint_cursor_matches_context(state, sandbox, &context) }; Ok((!same_configuration).then(|| unknown_endpoint_reports(&context.endpoints))) } +fn endpoint_cursor_matches_context( + state: &ServerState, + sandbox: &Sandbox, + context: &EndpointContext, +) -> bool { + state + .supervisor_sessions + .current_session_id(sandbox.object_id()) + .and_then(|session_id| { + state + .supervisor_sessions + .endpoint_report_cursor(sandbox.object_id(), &session_id) + }) + .is_some_and(|cursor| { + cursor.policy_hash == context.policy_hash + && cursor.provider_env_revision == context.provider_env_revision + }) +} + /// Clear all supervised network evidence without changing lifecycle state. pub(super) fn reset_endpoint_statuses( sandbox: &mut Sandbox, diff --git a/crates/openshell-server/src/grpc/policy/frozen.rs b/crates/openshell-server/src/grpc/policy/frozen.rs new file mode 100644 index 0000000000..874babc4cf --- /dev/null +++ b/crates/openshell-server/src/grpc/policy/frozen.rs @@ -0,0 +1,424 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Durable, non-secret authorization captured with first configuration acceptance. + +use super::{ + Digest, EffectiveProviderProfileCatalog, EffectiveSetting, GetSandboxConfigResponse, HashMap, + ObjectId, ObjectName, ObjectWorkspace, PolicySource, ProtoSandboxPolicy, Provider, Sandbox, + SandboxConfigInputs, ServerState, SettingScope, SettingValue, Sha256, + StaticCredentialEndpointBinding, Status, Store, StoredProviderCredentialRefreshState, + compute_provider_env_revision_from_records_and_policy_bindings, deterministic_policy_hash, + setting_value, settings, validate_and_canonicalize_policy, validate_policy_safety, +}; +use openshell_core::GetResourceVersion; +use openshell_core::proto::{ + FrozenProviderChange, FrozenSandboxPolicy, FrozenSandboxProvider, + FrozenSandboxWithheldProvider, ProviderProfile, +}; +use openshell_credential_issuer::refresh::CredentialRefresh; +use std::collections::BTreeSet; + +pub(in crate::grpc) struct ProviderContext { + pub catalog: EffectiveProviderProfileCatalog, + pub records: Vec, + pub withheld_providers: BTreeSet, +} + +impl ProviderContext { + pub(super) fn revision( + &self, + bindings: &HashMap>, + global_policy: Option<&ProtoSandboxPolicy>, + ) -> Result { + provider_env_revision( + &self.catalog, + &self.records, + &self.withheld_providers, + bindings, + global_policy, + ) + } +} + +pub(super) fn provider_env_revision( + catalog: &EffectiveProviderProfileCatalog, + records: &[super::super::provider::ProviderEnvironmentRecord], + withheld_providers: &BTreeSet, + bindings: &HashMap>, + global_policy: Option<&ProtoSandboxPolicy>, +) -> Result { + let revision = compute_provider_env_revision_from_records_and_policy_bindings( + catalog, + records, + bindings, + global_policy, + )?; + if withheld_providers.is_empty() { + return Ok(revision); + } + // A replacement can have the same resource version and no static keys. + // Polling must still revoke its previously installed dynamic grants. + let mut hasher = Sha256::new(); + hasher.update(b"openshell-frozen-withheld-providers-v1"); + hasher.update(revision.to_le_bytes()); + for name in withheld_providers { + hasher.update(name.len().to_le_bytes()); + hasher.update(name.as_bytes()); + } + let digest = hasher.finalize(); + Ok(u64::from_le_bytes(digest[..8].try_into().map_err( + |_| Status::internal("provider env revision digest too short"), + )?)) +} + +pub(in crate::grpc) async fn snapshot( + store: &Store, + sandbox: &Sandbox, +) -> Result, Status> { + Ok(store + .get_sandbox_frozen_policy(sandbox.object_id()) + .await + .map_err(|error| Status::internal(format!("fetch frozen policy failed: {error}")))? + .and_then(|state| state.policy)) +} + +pub(super) async fn requested(store: &Store, sandbox: &Sandbox) -> Result { + Ok(store + .get_sandbox_frozen_policy(sandbox.object_id()) + .await + .map_err(|error| Status::internal(format!("fetch frozen policy failed: {error}")))? + .is_some()) +} + +/// The one refusal every changed-access request to a frozen sandbox gets. +pub(super) fn refusal(sandbox: &Sandbox) -> String { + format!( + "sandbox '{}' is frozen; delete and recreate it to change its policy or providers", + sandbox.object_name() + ) +} + +pub(in crate::grpc) async fn ensure_mutable( + store: &Store, + sandbox: &Sandbox, +) -> Result<(), Status> { + if snapshot(store, sandbox).await?.is_some() { + return Err(Status::failed_precondition(refusal(sandbox))); + } + Ok(()) +} + +/// What an operator can do when a frozen sandbox's configuration is rejected. +/// +/// A captured policy and its providers cannot be repaired in place, and a +/// pending freeze under a global policy can only be repaired there. `None` +/// keeps the ordinary diagnostic: a pending sandbox policy is still editable. +pub(super) fn rejection_diagnostic( + captured: bool, + requested: bool, + source: PolicySource, +) -> Option<&'static str> { + if captured { + Some( + "Frozen configuration could not be activated and cannot be changed; check the sandbox logs for the cause, then delete and recreate the sandbox", + ) + } else if requested && source == PolicySource::Global { + Some( + "Configuration could not be frozen under the global policy; check the sandbox logs for the cause, then ask a platform admin to repair the global policy", + ) + } else { + None + } +} + +pub(in crate::grpc) async fn ensure_mutable_by_id(store: &Store, id: &str) -> Result<(), Status> { + let sandbox = store + .get_message::(id) + .await + .map_err(|error| Status::internal(format!("fetch sandbox failed: {error}")))? + .ok_or_else(|| Status::not_found("sandbox not found"))?; + ensure_mutable(store, &sandbox).await +} + +/// Workspace-qualified names of the sandboxes that hold a captured policy. +/// +/// The caller holds the fleet-wide mutation lock, so this reads the freeze +/// records and then only the sandboxes they name, never every sandbox. +pub(super) async fn names(state: &ServerState) -> Result, Status> { + let failed = |error| Status::internal(format!("list frozen sandboxes failed: {error}")); + let ids = state + .store + .captured_frozen_sandbox_ids() + .await + .map_err(failed)?; + let mut names = Vec::with_capacity(ids.len()); + for id in ids { + // Deletion removes a record with its sandbox, so a miss is a sandbox + // deleted since the records were listed. + if let Some(sandbox) = state + .store + .get_message::(&id) + .await + .map_err(failed)? + { + names.push(format!( + "{}/{}", + sandbox.object_workspace(), + sandbox.object_name() + )); + } + } + names.sort(); + Ok(names) +} + +pub(super) fn source(snapshot: &FrozenSandboxPolicy) -> Result { + match PolicySource::try_from(snapshot.policy_source) { + Ok(source @ (PolicySource::Sandbox | PolicySource::Global)) => Ok(source), + _ => Err(Status::failed_precondition( + "frozen policy has an invalid original source", + )), + } +} + +pub(super) fn policy(snapshot: &FrozenSandboxPolicy) -> Result { + let policy = snapshot + .policy + .as_ref() + .ok_or_else(|| Status::failed_precondition("frozen policy snapshot is missing"))?; + let canonical = validate_and_canonicalize_policy(policy.clone())?; + if deterministic_policy_hash(&canonical) != snapshot.policy_hash { + return Err(Status::failed_precondition( + "frozen policy is incompatible or its identity changed; recreate the sandbox", + )); + } + validate_policy_safety(&canonical)?; + Ok(canonical) +} + +pub(in crate::grpc) async fn provider_context_from_snapshot( + state: &ServerState, + sandbox: &Sandbox, + frozen: &FrozenSandboxPolicy, +) -> Result { + let workspace = sandbox.object_workspace(); + // The captured catalog, rather than today's live source, defines how both + // fresh credential values and the frozen endpoint authority are interpreted. + let profiles: Vec = frozen + .providers + .iter() + .filter_map(|provider| provider.profile.clone()) + .collect(); + let catalog = EffectiveProviderProfileCatalog::from_frozen_profiles(&profiles)?; + let mut records = Vec::with_capacity(frozen.providers.len()); + let mut withheld_providers = BTreeSet::new(); + for captured in &frozen.providers { + let CurrentProvider { + mut provider, + resource_version, + mut refresh_states, + change, + } = current_provider(state, workspace, captured).await?; + // Match the live loader: an output that a GitHub App grant superseded + // is never delivered, frozen or not. + super::super::provider::withhold_stale_github_app_outputs( + &mut provider, + resource_version, + &refresh_states, + ); + if let Some(change) = change { + // This runs on every configuration poll, so it stays at debug. + // `GetPolicy` reports the same provider and change to operators. + tracing::debug!( + sandbox_id = %sandbox.object_id(), + sandbox = %sandbox.object_name(), + workspace = %workspace, + provider = %captured.provider, + change = change.as_str_name(), + "withholding provider credentials from frozen sandbox: provider changed after capture" + ); + // Keep the captured interpretation, but deliver no credential under + // a replaced provider or a different authorization. Clearing values + // also revokes already-installed credentials on the next snapshot. + provider.credentials.clear(); + provider.credential_handles.clear(); + provider.credential_expiration_times.clear(); + refresh_states.clear(); + withheld_providers.insert(captured.provider.clone()); + provider.r#type.clone_from(&captured.r#type); + provider + .profile_workspace + .clone_from(&captured.profile_workspace); + provider.config.clone_from(&captured.config); + } + let metadata = provider.metadata.get_or_insert_with(Default::default); + metadata.name.clone_from(&captured.provider); + metadata.id.clone_from(&captured.provider_id); + metadata.workspace = workspace.to_string(); + records.push(super::super::provider::ProviderEnvironmentRecord { + name: captured.provider.clone(), + object_id: captured.provider_id.clone(), + resource_version, + provider, + refresh_states, + }); + } + Ok(ProviderContext { + catalog, + records, + withheld_providers, + }) +} + +/// A captured provider as it is now, and how it differs from the capture. +struct CurrentProvider { + provider: Provider, + resource_version: u64, + refresh_states: Vec, + /// `None` while the provider still matches the captured authorization. + change: Option, +} + +async fn current_provider( + state: &ServerState, + workspace: &str, + captured: &FrozenSandboxProvider, +) -> Result { + let provider = state + .store + .get_message_by_name::(workspace, &captured.provider) + .await + .map_err(|error| Status::internal(format!("fetch frozen provider failed: {error}")))? + .unwrap_or_default(); + let same_identity = provider.object_id() == captured.provider_id; + let resource_version = provider.get_resource_version(); + let refresh_states = if same_identity { + state + .refresh + .list(Some(provider.object_id())) + .await? + .iter() + .map(Into::into) + .collect::>() + } else { + Vec::new() + }; + let change = if !same_identity { + Some(FrozenProviderChange::Replaced) + } else if provider.r#type != captured.r#type { + Some(FrozenProviderChange::Type) + } else if provider.profile_workspace != captured.profile_workspace { + Some(FrozenProviderChange::ProfileScope) + } else if provider.config != captured.config { + Some(FrozenProviderChange::Config) + } else if authorization_epochs(&refresh_states)? != captured.refresh_authorization_epochs { + Some(FrozenProviderChange::Authorization) + } else { + None + }; + Ok(CurrentProvider { + provider, + resource_version, + refresh_states, + change, + }) +} + +/// The captured providers whose credentials are withheld now, for reads. +/// +/// Uses the comparison that delivery uses, without building the captured +/// profile catalog, so a read still answers when that catalog no longer loads. +pub(in crate::grpc) async fn withheld_providers( + state: &ServerState, + sandbox: &Sandbox, + frozen: &FrozenSandboxPolicy, +) -> Result, Status> { + let mut withheld = Vec::new(); + for captured in &frozen.providers { + if let Some(change) = current_provider(state, sandbox.object_workspace(), captured) + .await? + .change + { + withheld.push(FrozenSandboxWithheldProvider { + provider: captured.provider.clone(), + change: change.into(), + }); + } + } + Ok(withheld) +} + +fn authorization_epochs( + states: &[StoredProviderCredentialRefreshState], +) -> Result, Status> { + let mut epochs = HashMap::new(); + for state in states { + if state + .metadata + .as_ref() + .is_some_and(|meta| meta.deletion_time.is_some()) + { + continue; + } + epochs.insert( + state.credential_key.clone(), + crate::provider_refresh::effective_authorization_epoch(state)?.to_string(), + ); + } + Ok(epochs) +} + +pub(super) fn capture( + config: &GetSandboxConfigResponse, + inputs: &SandboxConfigInputs, + now_ms: i64, +) -> Result { + let mut providers = Vec::with_capacity(inputs.provider_records.len()); + for record in &inputs.provider_records { + let provider = &record.provider; + providers.push(FrozenSandboxProvider { + provider: record.name.clone(), + provider_id: record.object_id.clone(), + r#type: provider.r#type.clone(), + profile_workspace: provider.profile_workspace.clone(), + config: provider.config.clone(), + profile: inputs + .catalog + .get_profile_for_scope(&provider.r#type, &provider.profile_workspace), + refresh_authorization_epochs: authorization_epochs(&record.refresh_states)?, + }); + } + Ok(FrozenSandboxPolicy { + policy: config.policy.clone(), + version: config.version, + policy_hash: config.policy_hash.clone(), + frozen_time: openshell_core::time::timestamp_from_millis(now_ms).ok(), + policy_source: config.policy_source, + global_policy_version: config.global_policy_version, + providers, + }) +} + +pub(super) fn uses_global_policy( + snapshot: Option<&FrozenSandboxPolicy>, + source: PolicySource, +) -> bool { + snapshot.map_or(source == PolicySource::Global, |snapshot| { + snapshot.policy_source == i32::from(PolicySource::Global) + }) +} + +pub(super) fn disable_proposals(requested: bool, settings: &mut HashMap) { + if requested { + settings.insert( + settings::AGENT_POLICY_PROPOSALS_ENABLED_KEY.to_string(), + EffectiveSetting { + value: Some(SettingValue { + value: Some(setting_value::Value::BoolValue(false)), + }), + scope: i32::from(SettingScope::Sandbox), + }, + ); + } +} diff --git a/crates/openshell-server/src/grpc/policy/frozen_tests.rs b/crates/openshell-server/src/grpc/policy/frozen_tests.rs new file mode 100644 index 0000000000..ddb142a57c --- /dev/null +++ b/crates/openshell-server/src/grpc/policy/frozen_tests.rs @@ -0,0 +1,1391 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +mod frozen_policy_tests { + use super::*; + use crate::persistence::PersistenceError; + use openshell_core::proto::{ + AttachSandboxProviderRequest, ConfigurationAdmissionState, DetachSandboxProviderRequest, + ProviderProfile, ProviderProfileCredential, ReportSandboxConfigurationRequest, + SandboxConfigurationAdmission, UpdateProviderRequest, + }; + + const ID: &str = "sb-frozen-policy"; + const NAME: &str = "frozen-policy"; + const PROVIDER: &str = "frozen-provider"; + const PROFILE: &str = "frozen-profile"; + const TOKEN: &str = "FROZEN_TOKEN"; + + fn profile(host: &str) -> ProviderProfile { + ProviderProfile { + id: PROFILE.to_string(), + display_name: "Frozen policy test".to_string(), + credentials: vec![ProviderProfileCredential { + name: "access_token".to_string(), + env_vars: vec![TOKEN.to_string()], + auth_style: "bearer".to_string(), + header_name: "Authorization".to_string(), + ..Default::default() + }], + endpoints: vec![NetworkEndpoint { + host: host.to_string(), + port: 443, + protocol: "rest".to_string(), + access: openshell_core::proto::NetworkAccessPreset::Full.into(), + ..Default::default() + }], + ..Default::default() + } + } + + async fn seed(state: &Arc, frozen: bool) -> Provider { + state + .store + .put_message(&crate::provider_profile_sources::stored_provider_profile( + profile("api.original.example"), + )) + .await + .unwrap(); + let mut provider = test_provider(PROVIDER, PROFILE); + provider.profile_workspace.clear(); + provider.credentials = HashMap::from([(TOKEN.to_string(), "original-token".to_string())]); + state.store.put_message(&provider).await.unwrap(); + let sandbox = test_sandbox( + ID, + NAME, + openshell_policy::restrictive_default_policy(), + vec![PROVIDER.to_string()], + ); + if frozen { + state.store.create_frozen_sandbox(&sandbox).await.unwrap(); + } else { + state.store.put_message(&sandbox).await.unwrap(); + } + // Creation persists the baseline revision that supervisors acknowledge. + let policy = + validate_and_canonicalize_policy(openshell_policy::restrictive_default_policy()) + .unwrap(); + state + .store + .put_policy_revision( + "frozen-policy-1", + ID, + sandbox.object_workspace(), + 1, + &policy.encode_to_vec(), + &deterministic_policy_hash(&policy), + ) + .await + .unwrap(); + provider + } + + async fn config(state: &Arc) -> GetSandboxConfigResponse { + handle_get_sandbox_config( + state, + with_sandbox( + Request::new(GetSandboxConfigRequest { + name: NAME.to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), + supported_capabilities: Vec::new(), + }), + ID, + ), + ) + .await + .unwrap() + .into_inner() + } + + async fn environment(state: &Arc) -> GetSandboxProviderEnvironmentResponse { + handle_get_sandbox_provider_environment( + state, + with_sandbox( + Request::new(GetSandboxProviderEnvironmentRequest { + sandbox_id: ID.to_string(), + supports_static_credential_bindings: true, + supports_stable_placeholder_environment_keys: true, + }), + ID, + ), + ) + .await + .unwrap() + .into_inner() + } + + async fn register(state: &Arc, instance: &str, previous: &str) { + handle_report_sandbox_configuration( + state, + with_sandbox( + Request::new(ReportSandboxConfigurationRequest { + sandbox_id: ID.to_string(), + admission: Some(SandboxConfigurationAdmission { + instance_id: instance.to_string(), + state: ConfigurationAdmissionState::Pending.into(), + ..Default::default() + }), + expected_instance_id: previous.to_string(), + }), + ID, + ), + ) + .await + .unwrap(); + } + + async fn accept( + state: &Arc, + instance: &str, + config: &GetSandboxConfigResponse, + ) -> Result, Status> { + handle_report_sandbox_configuration( + state, + with_sandbox( + Request::new(ReportSandboxConfigurationRequest { + sandbox_id: ID.to_string(), + admission: Some(SandboxConfigurationAdmission { + instance_id: instance.to_string(), + state: ConfigurationAdmissionState::Accepted.into(), + policy_version: config.version, + policy_hash: config.policy_hash.clone(), + config_revision: config.config_revision, + provider_env_revision: config.provider_env_revision, + ..Default::default() + }), + ..Default::default() + }), + ID, + ), + ) + .await + } + + async fn initialize(state: &Arc) -> (GetSandboxConfigResponse, String) { + let instance = uuid::Uuid::new_v4().to_string(); + register(state, &instance, "").await; + let config = config(state).await; + assert!( + config.configuration_admitted, + "{}", + config.configuration_error + ); + assert!( + frozen::snapshot(state.store.as_ref(), &stored_sandbox(state).await) + .await + .unwrap() + .is_none() + ); + accept(state, &instance, &config).await.unwrap(); + (config, instance) + } + + async fn stored_sandbox(state: &Arc) -> Sandbox { + state + .store + .get_message::(ID) + .await + .unwrap() + .unwrap() + } + + async fn update_global(state: &Arc, host: &str) { + let mut policy = openshell_policy::restrictive_default_policy(); + let mut endpoint = profile(host).endpoints.remove(0); + endpoint.provider_credentialed = false; + policy.network_policies.insert( + "global_access".to_string(), + NetworkPolicyRule { + name: "global_access".to_string(), + endpoints: vec![endpoint], + ..Default::default() + }, + ); + handle_update_config( + state, + with_user(Request::new(UpdateConfigRequest { + policy: Some(policy), + global: true, + ..Default::default() + })), + ) + .await + .unwrap(); + } + + #[tokio::test] + async fn frozen_policy_service_delivers_mode_with_matching_config_and_workspace_authz() { + use openshell_core::proto::frozen_sandbox_policies_server::FrozenSandboxPolicies; + use openshell_core::proto::{GetFrozenSandboxConfigRequest, GetFrozenSandboxPolicyRequest}; + let state = test_server_state().await; + seed(&state, true).await; + let service = crate::grpc::OpenShellService::new(Arc::clone(&state)); + let pending = FrozenSandboxPolicies::get_config( + &service, + with_sandbox( + Request::new(GetFrozenSandboxConfigRequest { + name: NAME.into(), + workspace_scope: None, + supported_capabilities: Vec::new(), + }), + ID, + ), + ) + .await + .unwrap() + .into_inner(); + assert!(!pending.frozen); + assert!(pending.frozen_requested); + let (accepted, _) = initialize(&state).await; + let captured = FrozenSandboxPolicies::get_config( + &service, + with_sandbox( + Request::new(GetFrozenSandboxConfigRequest { + name: NAME.into(), + workspace_scope: None, + supported_capabilities: Vec::new(), + }), + ID, + ), + ) + .await + .unwrap() + .into_inner(); + assert!(captured.frozen); + assert!(captured.frozen_requested); + assert_eq!(captured.config.unwrap().policy_hash, accepted.policy_hash); + let policy = FrozenSandboxPolicies::get_policy( + &service, + with_user(Request::new(GetFrozenSandboxPolicyRequest { + name: NAME.into(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), + })), + ) + .await + .unwrap() + .into_inner(); + assert!(policy.requested); + assert_eq!(policy.policy.unwrap().policy_hash, accepted.policy_hash); + drop(service); + let mut restricted = Arc::try_unwrap(state).ok().unwrap(); + restricted.admin_role = "required-platform-admin".into(); + let state = Arc::new(restricted); + let mut foreign = stored_sandbox(&state).await; + let metadata = foreign.metadata.as_mut().unwrap(); + metadata.id = "foreign-frozen-id".into(); + metadata.workspace = "foreign".into(); + state.store.create_frozen_sandbox(&foreign).await.unwrap(); + let service = crate::grpc::OpenShellService::new(Arc::clone(&state)); + let error = FrozenSandboxPolicies::get_policy( + &service, + with_user(Request::new(GetFrozenSandboxPolicyRequest { + name: NAME.into(), + workspace_scope: Some(openshell_core::proto::workspace_selector("foreign")), + })), + ) + .await + .unwrap_err(); + assert_eq!(error.code(), Code::NotFound); + let error = FrozenSandboxPolicies::get_config( + &service, + with_sandbox( + Request::new(GetFrozenSandboxConfigRequest { + name: "other-sandbox".into(), + workspace_scope: None, + supported_capabilities: Vec::new(), + }), + ID, + ), + ) + .await + .unwrap_err(); + assert_eq!(error.code(), Code::PermissionDenied); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn frozen_policy_capture_during_live_reads_rebuilds_from_captured_authority() { + use openshell_core::proto::GetFrozenSandboxConfigRequest; + use openshell_core::proto::frozen_sandbox_policies_server::FrozenSandboxPolicies; + for entry in ["unary", "combined"] { + let state = test_server_state().await; + seed(&state, true).await; + update_global(&state, "api.original.example").await; + let original = config(&state).await; + let sandbox = stored_sandbox(&state).await; + let inputs = load_sandbox_config_inputs(&state, sandbox.clone()) + .await + .unwrap(); + let captured = frozen::capture(&original, &inputs, current_time_ms()).unwrap(); + let (sources, gate) = + ProviderProfileSources::from_test_profiles_blocked(vec![profile( + "api.changed.example", + )]); + let mut server = Arc::try_unwrap(state).ok().unwrap(); + server.provider_profile_sources = sources; + let state = Arc::new(server); + let reader = Arc::clone(&state); + let pending = sandbox.clone(); + let read = tokio::spawn(async move { + match entry { + "unary" => { + let service = crate::grpc::OpenShellService::new(Arc::clone(&reader)); + let response = FrozenSandboxPolicies::get_config( + &service, + with_sandbox( + Request::new(GetFrozenSandboxConfigRequest { + name: NAME.into(), + workspace_scope: None, + supported_capabilities: Vec::new(), + }), + ID, + ), + ) + .await + .unwrap() + .into_inner(); + assert!(response.frozen && response.frozen_requested); + let config = response.config.unwrap(); + (config.policy_hash, config.global_policy_version) + } + "combined" => { + // These same shared builders feed pushed configuration + // and session bootstrap from one input selection. + let inputs = load_sandbox_config_inputs(&reader, pending).await.unwrap(); + let (config, environment) = tokio::try_join!( + build_sandbox_config_snapshot_from_inputs(&reader, &inputs), + build_provider_environment_snapshot_from_inputs( + &reader, &inputs, true, true + ), + ) + .unwrap(); + assert!(inputs.frozen.unwrap().policy.is_some()); + assert_eq!(config.policy_hash, environment.policy_hash); + (config.policy_hash, config.global_policy_version) + } + _ => unreachable!(), + } + }); + // The blocked source pauses the first poll before later SQL reads + // in try_join, making capture-before-new-global-read deterministic. + gate.entered().await; + state + .store + .accept_frozen_sandbox_configuration(sandbox, captured.clone()) + .await + .unwrap(); + update_global(&state, "api.changed.example").await; + gate.release(); + let (hash, global_version) = read.await.unwrap(); + assert_eq!(hash, original.policy_hash, "{entry}"); + assert_eq!(global_version, captured.global_policy_version, "{entry}"); + } + } + + /// An accepted report against a stored configuration that no longer + /// builds tells the supervisor to fetch again. It is not a fatal error, + /// for frozen and ordinary sandboxes alike. + #[tokio::test] + async fn accepted_report_of_a_configuration_that_no_longer_builds_is_aborted() { + for frozen in [false, true] { + let state = test_server_state().await; + seed(&state, frozen).await; + let instance = uuid::Uuid::new_v4().to_string(); + register(&state, &instance, "").await; + let admitted = config(&state).await; + assert!(admitted.configuration_admitted); + + // A later revision the gateway refuses to serve. + let mut unsafe_policy = openshell_policy::restrictive_default_policy(); + unsafe_policy + .process + .get_or_insert_with(Default::default) + .run_as_user = "root".to_string(); + state + .store + .put_policy_revision( + "frozen-policy-2", + ID, + stored_sandbox(&state).await.object_workspace(), + 2, + &unsafe_policy.encode_to_vec(), + &deterministic_policy_hash(&unsafe_policy), + ) + .await + .unwrap(); + assert!(!config(&state).await.configuration_admitted); + + let error = accept(&state, &instance, &admitted).await.unwrap_err(); + assert_eq!(error.code(), Code::Aborted, "frozen={frozen}: {error:?}"); + } + } + + /// A profile update applies to live sandboxes and names the frozen + /// sandbox that keeps its captured profile. + #[tokio::test] + async fn frozen_policy_profile_update_reports_the_frozen_sandbox() { + use openshell_core::proto::{ProviderProfileImportItem, UpdateProviderProfilesRequest}; + let state = test_server_state().await; + seed(&state, true).await; + initialize(&state).await; + + // The seeded profile is platform-scoped, so the update names no workspace. + let stored: StoredProviderProfile = state + .store + .get_message_by_name("", PROFILE) + .await + .unwrap() + .unwrap(); + let mut updated = profile("api.changed.example"); + updated.resource_version = stored.metadata.as_ref().unwrap().resource_version; + let response = crate::grpc::provider::handle_update_provider_profiles( + &state, + authed_request(UpdateProviderProfilesRequest { + request_id: String::new(), + profile: Some(ProviderProfileImportItem { + profile: Some(updated), + source: "frozen-profile.yaml".to_string(), + }), + expected_resource_version: 0, + id: PROFILE.to_string(), + workspace_scope: None, + }), + ) + .await + .unwrap() + .into_inner(); + + assert!(response.updated, "{:?}", response.diagnostics); + assert!( + response.diagnostics.iter().any(|diagnostic| { + diagnostic.severity == "warning" + && diagnostic.message.contains("default/frozen-policy") + && diagnostic.message.contains("is frozen") + }), + "{:?}", + response.diagnostics + ); + } + + #[tokio::test] + async fn frozen_policy_session_acceptance_requires_first_unary_capture() { + let state = test_server_state().await; + seed(&state, true).await; + let instance = uuid::Uuid::new_v4().to_string(); + register(&state, &instance, "").await; + let config = config(&state).await; + let admission = SandboxConfigurationAdmission { + instance_id: instance.clone(), + state: ConfigurationAdmissionState::Accepted.into(), + policy_version: config.version, + policy_hash: config.policy_hash.clone(), + config_revision: config.config_revision, + provider_env_revision: config.provider_env_revision, + ..Default::default() + }; + let error = state + .compute + .supervisor_session_admission(ID, "session-first", "supervisor-first", &admission) + .await + .unwrap_err(); + assert!(error.contains("ReportSandboxConfiguration")); + let pending = stored_sandbox(&state).await; + assert_eq!( + pending + .status + .unwrap() + .configuration_admission + .unwrap() + .state, + i32::from(ConfigurationAdmissionState::Pending) + ); + assert!( + state + .store + .get_sandbox_frozen_policy(ID) + .await + .unwrap() + .unwrap() + .policy + .is_none() + ); + accept(&state, &instance, &config).await.unwrap(); + let captured = state + .store + .get_sandbox_frozen_policy(ID) + .await + .unwrap() + .unwrap(); + state + .compute + .supervisor_session_admission(ID, "session-first", "supervisor-first", &admission) + .await + .unwrap(); + assert_eq!( + state + .store + .get_sandbox_frozen_policy(ID) + .await + .unwrap() + .unwrap(), + captured + ); + } + + #[tokio::test] + async fn frozen_policy_admission_captures_once_and_survives_restart() { + for (frozen_requested, global) in [(false, false), (true, false), (true, true)] { + let state = test_server_state().await; + let mut provider = seed(&state, frozen_requested).await; + let mut state = Arc::try_unwrap(state).ok().unwrap(); + state.provider_profile_sources = ProviderProfileSources::from_test_snapshot_sequence( + vec![( + "original".to_string(), + vec![profile("api.original.example")], + )], + Arc::new(AtomicUsize::new(0)), + ); + let state = Arc::new(state); + config(&state).await; + if global { + update_global(&state, "api.original.example").await; + } + let instance = uuid::Uuid::new_v4().to_string(); + register(&state, &instance, "").await; + let outdated = config(&state).await; + assert!( + outdated.configuration_admitted, + "{}", + outdated.configuration_error + ); + provider + .credentials + .insert(TOKEN.to_string(), "rotated-token".to_string()); + crate::grpc::provider::handle_update_provider( + &state, + with_user(Request::new(UpdateProviderRequest { + provider: Some(provider), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), + ..Default::default() + })), + ) + .await + .unwrap(); + assert_eq!( + accept(&state, &instance, &outdated) + .await + .unwrap_err() + .code(), + Code::Aborted + ); + assert!( + frozen::snapshot(state.store.as_ref(), &stored_sandbox(&state).await) + .await + .unwrap() + .is_none() + ); + let accepted = config(&state).await; + accept(&state, &instance, &accepted).await.unwrap(); + let sandbox = stored_sandbox(&state).await; + assert_eq!( + frozen::snapshot(state.store.as_ref(), &sandbox) + .await + .unwrap() + .is_some(), + frozen_requested + ); + if !frozen_requested { + update_global(&state, "api.changed.example").await; + let changed = config(&state).await; + assert_ne!(changed.policy_hash, accepted.policy_hash); + assert_eq!(changed.policy_source, i32::from(PolicySource::Global)); + continue; + } + let captured = frozen::snapshot(state.store.as_ref(), &sandbox) + .await + .unwrap() + .unwrap() + .clone(); + assert_eq!(captured.policy, accepted.policy); + assert_eq!(captured.policy_hash, accepted.policy_hash); + assert!(captured.frozen_time.is_some()); + assert_eq!( + captured.policy_source, + i32::from(if global { + PolicySource::Global + } else { + PolicySource::Sandbox + }) + ); + assert_eq!(captured.global_policy_version, u32::from(global)); + assert_eq!( + captured.providers[0].profile.as_ref().unwrap().endpoints[0].host, + "api.original.example" + ); + + // Any live source read would now supply different authorization. + let fetches = Arc::new(AtomicUsize::new(0)); + let mut state = Arc::try_unwrap(state).ok().unwrap(); + state.provider_profile_sources = ProviderProfileSources::from_test_snapshot_sequence( + vec![("changed".to_string(), vec![profile("api.changed.example")])], + Arc::clone(&fetches), + ); + let state = Arc::new(state); + update_global(&state, "api.changed.example").await; + let delivered = config(&state).await; + let credentials = environment(&state).await; + assert_eq!(delivered.policy_source, captured.policy_source); + assert_eq!(delivered.policy, accepted.policy); + assert_eq!(delivered.policy_hash, accepted.policy_hash); + assert_eq!(delivered.version, accepted.version); + assert_eq!(credentials.policy_hash, accepted.policy_hash); + assert_eq!(credentials.environment[TOKEN], "rotated-token"); + + let replacement = uuid::Uuid::new_v4().to_string(); + register(&state, &replacement, &instance).await; + let replacement_config = config(&state).await; + assert_eq!(replacement_config.policy, accepted.policy); + assert_eq!(replacement_config.policy_hash, accepted.policy_hash); + assert_eq!( + replacement_config.global_policy_version, + captured.global_policy_version + ); + accept(&state, &replacement, &replacement_config) + .await + .unwrap(); + assert_eq!( + frozen::snapshot(state.store.as_ref(), &stored_sandbox(&state).await) + .await + .unwrap(), + Some(captured.clone()) + ); + assert_eq!(fetches.load(Ordering::SeqCst), 0); + + let discovery = DiscoveryConfigInputs::load(&state, "default").await.unwrap(); + let collection_fetches = fetches.load(Ordering::SeqCst); + let discovered = discovery.build(&state, &sandbox).await.unwrap(); + assert_eq!(discovered.policy, accepted.policy); + assert_eq!(discovered.policy_hash, accepted.policy_hash); + assert_eq!(discovered.global_policy_version, captured.global_policy_version); + assert_eq!(fetches.load(Ordering::SeqCst), collection_fetches, + "a frozen sandbox must not reload live catalog inputs per sandbox"); + + let directory = tempfile::tempdir().unwrap(); + let database_url = format!("sqlite://{}", directory.path().join("frozen.db").display()); + let store = Store::connect(&database_url).await.unwrap(); + let sandbox = stored_sandbox(&state).await; + let bytes = sandbox.encode_to_vec(); + for secret in ["original-token", "rotated-token"] { + assert!(!String::from_utf8_lossy(&bytes).contains(secret)); + } + store.create_frozen_sandbox(&sandbox).await.unwrap(); + let persisted = store.get_message::(ID).await.unwrap().unwrap(); + store + .accept_frozen_sandbox_configuration(persisted, captured.clone()) + .await + .unwrap(); + let private = store + .get_sandbox_frozen_policy(ID) + .await + .unwrap() + .unwrap() + .encode_to_vec(); + for secret in ["original-token", "rotated-token"] { + assert!(!String::from_utf8_lossy(&private).contains(secret)); + } + drop(store); + let reopened = Store::connect(&database_url).await.unwrap(); + let restored = reopened.get_message::(ID).await.unwrap().unwrap(); + assert_eq!( + frozen::snapshot(&reopened, &restored).await.unwrap(), + Some(captured) + ); + } + } + + #[tokio::test] + async fn frozen_policy_rejects_mutation_handlers_for_user_and_sandbox() { + let state = test_server_state().await; + seed(&state, true).await; + let (accepted, _) = initialize(&state).await; + for sandbox_caller in [false, true] { + for merge in [false, true] { + let request = Request::new(UpdateConfigRequest { + sandbox: NAME.to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), + policy: (!merge).then(openshell_policy::restrictive_default_policy), + merge_operations: if merge { + vec![PolicyMergeOperation { + operation: Some(policy_merge_operation::Operation::RemoveRule( + openshell_core::proto::RemoveNetworkRule { + rule_name: "unused".to_string(), + }, + )), + }] + } else { + Vec::new() + }, + ..Default::default() + }); + let request = if sandbox_caller { + with_sandbox(request, ID) + } else { + with_user(request) + }; + let error = handle_update_config(&state, request).await.unwrap_err(); + if sandbox_caller && merge { + assert_eq!(error.code(), Code::PermissionDenied); + } else { + assert_eq!(error.code(), Code::FailedPrecondition); + assert!(error.message().contains("frozen")); + } + } + } + for sandbox_caller in [false, true] { + let attach = Request::new(AttachSandboxProviderRequest { + sandbox: NAME.to_string(), + provider: PROVIDER.to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), + ..Default::default() + }); + let detach = Request::new(DetachSandboxProviderRequest { + sandbox: NAME.to_string(), + provider: PROVIDER.to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), + ..Default::default() + }); + let attach = if sandbox_caller { + with_sandbox(attach, ID) + } else { + with_user(attach) + }; + let detach = if sandbox_caller { + with_sandbox(detach, ID) + } else { + with_user(detach) + }; + let attach_error = crate::grpc::sandbox::handle_attach_sandbox_provider(&state, attach) + .await + .unwrap_err(); + let detach_error = crate::grpc::sandbox::handle_detach_sandbox_provider(&state, detach) + .await + .unwrap_err(); + for error in [attach_error, detach_error] { + assert_eq!(error.code(), Code::FailedPrecondition); + assert!(error.message().contains("frozen")); + } + } + + let rule = test_policy_with_rule("new_access", "proposal.example") + .network_policies + .remove("new_access") + .unwrap(); + let mut chunk = pending_draft_chunk("before-freeze", ID); + chunk.rule_name.clone_from(&rule.name); + chunk.proposed_rule = rule.encode_to_vec(); + chunk.host = "proposal.example".to_string(); + chunk.port = 443; + state + .store + .put_draft_chunk(&chunk, None, "default") + .await + .unwrap(); + let error = handle_approve_draft_chunk( + &state, + with_user(Request::new(ApproveDraftChunkRequest { + sandbox: NAME.to_string(), + chunk_id: chunk.id.clone(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), + ..Default::default() + })), + ) + .await + .unwrap_err(); + assert_eq!(error.code(), Code::FailedPrecondition); + assert!(error.message().contains("frozen")); + let error = handle_approve_all_draft_chunks( + &state, + with_user(Request::new(ApproveAllDraftChunksRequest { + sandbox: NAME.to_string(), + include_security_flagged: true, + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), + ..Default::default() + })), + ) + .await + .unwrap_err(); + assert_eq!(error.code(), Code::FailedPrecondition); + assert!(error.message().contains("frozen")); + let proposed = handle_submit_policy_analysis( + &state, + with_sandbox( + Request::new(SubmitPolicyAnalysisRequest { + name: NAME.to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), + proposed_chunks: vec![PolicyChunk { + rule_name: rule.name.clone(), + proposed_rule: Some(rule), + ..Default::default() + }], + ..Default::default() + }), + ID, + ), + ) + .await + .unwrap() + .into_inner(); + assert_eq!(proposed.accepted_chunks, 0); + assert_eq!(proposed.rejected_chunks, 1); + assert_eq!( + state + .store + .get_draft_chunk(&chunk.id) + .await + .unwrap() + .unwrap() + .status, + "pending" + ); + assert_eq!(config(&state).await.policy_hash, accepted.policy_hash); + + // A writer that read before first acceptance cannot bypass the RPC + // guard by reaching the atomic persistence boundary afterward. + let changed = test_policy_with_rule("raced", "raced.example"); + let error = state + .store + .put_policy_revision_atomic(&AtomicPolicyRevisionWrite { + id: "raced-policy".to_string(), + sandbox_id: ID.to_string(), + workspace: "default".to_string(), + version: i64::from(accepted.version) + 1, + policy_payload: changed.encode_to_vec(), + policy_hash: deterministic_policy_hash(&changed), + provenance: HashMap::new(), + expected_resource_version: 0, + annotations: HashMap::new(), + backfill_policy: None, + }) + .await + .unwrap_err(); + assert!(matches!(error, PersistenceError::Conflict { .. })); + assert_eq!(config(&state).await.policy_hash, accepted.policy_hash); + } + + #[tokio::test] + async fn frozen_policy_rotates_credentials_and_withholds_incompatible_providers() { + use openshell_core::proto::{ + ProviderCredentialTokenGrant, ProviderCredentialTokenGrantType, + }; + + for dynamic in [false, true] { + let state = test_server_state().await; + let mut provider = seed(&state, true).await; + if dynamic { + // No static keys: a same-RV replacement must still revoke the grant. + provider.credentials.clear(); + state.store.put_message(&provider).await.unwrap(); + let mut dynamic_profile = profile("api.original.example"); + dynamic_profile.credentials[0].env_vars.clear(); + dynamic_profile.credentials[0].token_grant = Some(ProviderCredentialTokenGrant { + grant_type: ProviderCredentialTokenGrantType::ClientCredentials.into(), + token_endpoint: "https://issuer.example/token".to_string(), + jwt_svid_audience: "https://issuer.example".to_string(), + audience: "api://original".to_string(), + ..Default::default() + }); + state + .store + .put_message(&crate::provider_profile_sources::stored_provider_profile( + dynamic_profile, + )) + .await + .unwrap(); + } + let mut other_profile = profile("api.other.example"); + other_profile.id = "other-profile".to_string(); + other_profile.credentials[0].env_vars = vec!["OTHER_TOKEN".to_string()]; + state + .store + .put_message(&crate::provider_profile_sources::stored_provider_profile( + other_profile, + )) + .await + .unwrap(); + let mut other = test_provider("other-provider", "other-profile"); + other.profile_workspace.clear(); + other.credentials = + HashMap::from([("OTHER_TOKEN".to_string(), "other-token".to_string())]); + state.store.put_message(&other).await.unwrap(); + let mut sandbox = stored_sandbox(&state).await; + sandbox + .spec + .as_mut() + .unwrap() + .providers + .push("other-provider".to_string()); + state.store.put_message(&sandbox).await.unwrap(); + let (accepted, _) = initialize(&state).await; + let before = environment(&state).await; + assert_eq!( + before + .dynamic_credentials + .values() + .filter(|credential| credential.token_grant.is_some()) + .count(), + usize::from(dynamic) + ); + if dynamic { + let mut rotated = provider.clone(); + rotated + .credentials + .insert(TOKEN.to_string(), "rotated-token".to_string()); + state.store.put_message(&rotated).await.unwrap(); + assert_eq!( + environment(&state) + .await + .dynamic_credentials + .values() + .filter(|credential| credential.token_grant.is_some()) + .count(), + 1 + ); + state.store.put_message(&provider).await.unwrap(); + } else { + provider + .credentials + .insert(TOKEN.to_string(), "rotated-token".to_string()); + crate::grpc::provider::handle_update_provider( + &state, + with_user(Request::new(UpdateProviderRequest { + provider: Some(provider), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), + ..Default::default() + })), + ) + .await + .unwrap(); + provider = state + .store + .get_message_by_name::("default", PROVIDER) + .await + .unwrap() + .unwrap(); + let rotated = environment(&state).await; + assert_eq!(rotated.environment[TOKEN], "rotated-token"); + assert_ne!(rotated.provider_env_revision, before.provider_env_revision); + assert_eq!( + rotated.static_credential_bindings, + before.static_credential_bindings + ); + assert_eq!(rotated.policy_hash, accepted.policy_hash); + } + for change in ["deleted", "identity", "config", "refresh authorization"] { + state + .store + .delete(Provider::object_type(), provider.object_id()) + .await + .unwrap(); + let mut changed = provider.clone(); + match change { + "identity" => { + changed.metadata.as_mut().unwrap().id = "replacement-provider".to_string(); + } + "config" => { + changed + .config + .insert("region".to_string(), "changed".to_string()); + } + "refresh authorization" => { + crate::provider_refresh::put_refresh_state( + state.store.as_ref(), + &StoredProviderCredentialRefreshState { + metadata: Some(openshell_core::proto::datamodel::v1::ObjectMeta { + id: "new-refresh-authorization".to_string(), + name: crate::provider_refresh::refresh_state_name( + provider.object_id(), + TOKEN, + ), + workspace: "default".to_string(), + ..Default::default() + }), + provider_id: provider.object_id().to_string(), + provider_name: PROVIDER.to_string(), + credential_key: TOKEN.to_string(), + authorization_epoch: "new-authorization".to_string(), + ..Default::default() + }, + ) + .await + .unwrap(); + } + _ => {} + } + if change != "deleted" { + state.store.put_message(&changed).await.unwrap(); + } + let withheld = environment(&state).await; + assert!( + !withheld.environment.contains_key(TOKEN), + "{dynamic}/{change}" + ); + assert!( + withheld + .dynamic_credentials + .values() + .all(|credential| credential.token_grant.is_none()), + "{dynamic}/{change}" + ); + assert_ne!( + withheld.provider_env_revision, before.provider_env_revision, + "{dynamic}/{change}" + ); + let delivered = config(&state).await; + assert_eq!( + withheld.provider_env_revision, + delivered.provider_env_revision + ); + assert_eq!(delivered.policy_hash, accepted.policy_hash); + assert_eq!(withheld.environment["OTHER_TOKEN"], "other-token"); + assert_eq!( + withheld.readiness_reason, + i32::from(ProviderReadinessReason::CredentialsWithheld) + ); + if change == "identity" { + state + .store + .delete(Provider::object_type(), changed.object_id()) + .await + .unwrap(); + } + state.store.put_message(&provider).await.unwrap(); + } + } + } + + #[tokio::test] + async fn frozen_policy_endpoint_reports_survive_source_removal_and_reconnect() { + use openshell_core::proto::{ + EndpointObservation, EndpointResult, ReportEndpointStatusRequest, + ReportPolicyStatusRequest, + }; + + for global in [false, true] { + let state = test_server_state().await; + seed(&state, true).await; + config(&state).await; // Persist the sandbox baseline before a global override. + let mut policy = mcp_policy_with_versions(&["2025-11-25"]); + policy.network_policies.get_mut("mcp").unwrap().endpoints[0].host = + "tools.original.example".to_string(); + handle_update_config( + &state, + with_user(Request::new(UpdateConfigRequest { + sandbox: if global { + String::new() + } else { + NAME.to_string() + }, + workspace_scope: (!global) + .then(|| openshell_core::proto::workspace_selector("default")), + policy: Some(policy), + global, + ..Default::default() + })), + ) + .await + .unwrap(); + let (accepted, _) = initialize(&state).await; + let stored_profile = state + .store + .get_message_by_name::("", PROFILE) + .await + .unwrap() + .unwrap(); + state + .store + .delete( + StoredProviderProfile::object_type(), + stored_profile.object_id(), + ) + .await + .unwrap(); + // A newly configured source supplies no captured profile. Every + // endpoint path must bypass it, including before the first load ack. + let fetches = Arc::new(AtomicUsize::new(0)); + let mut state = Arc::try_unwrap(state).ok().unwrap(); + state.provider_profile_sources = ProviderProfileSources::from_test_snapshot_sequence( + vec![("unavailable".to_string(), Vec::new())], + Arc::clone(&fetches), + ); + let state = Arc::new(state); + update_global(&state, "global.changed.example").await; + let delivered = config(&state).await; + for (index, session) in ["session-one", "session-two"].into_iter().enumerate() { + let (sender, _receiver) = tokio::sync::mpsc::channel(1); + let (shutdown, _shutdown_receiver) = tokio::sync::oneshot::channel(); + state.supervisor_sessions.register( + ID.to_string(), + session.to_string(), + sender, + shutdown, + ); + reset_endpoint_status_for_supervisor_session(&state, ID, session) + .await + .unwrap(); + assert!( + state + .supervisor_sessions + .initialize_endpoint_status_authority(ID, session) + ); + let sandbox = stored_sandbox(&state).await; + let endpoints = &sandbox.status.as_ref().unwrap().endpoint_statuses; + assert_eq!(endpoints.len(), 1); + assert_eq!(endpoints[0].host, "tools.original.example"); + let endpoint_id = endpoints[0].endpoint_id.clone(); + handle_report_endpoint_status( + &state, + with_sandbox( + Request::new(ReportEndpointStatusRequest { + sandbox_id: ID.to_string(), + policy_hash: accepted.policy_hash.clone(), + provider_env_revision: delivered.provider_env_revision, + supervisor_session_id: session.to_string(), + report_sequence: 1, + observations: vec![EndpointObservation { + endpoint_id: endpoint_id.clone(), + result: EndpointResult::HttpResponseReceived.into(), + ..Default::default() + }], + observed_endpoint_ids: vec![endpoint_id], + ..Default::default() + }), + ID, + ), + ) + .await + .unwrap(); + handle_report_policy_status( + &state, + with_sandbox( + Request::new(ReportPolicyStatusRequest { + sandbox_id: ID.to_string(), + version: accepted.version, + status: PolicyStatus::Loaded.into(), + ..Default::default() + }), + ID, + ), + ) + .await + .unwrap(); + assert_eq!( + stored_sandbox(&state) + .await + .status + .unwrap() + .endpoint_statuses[0] + .last_result, + i32::from(EndpointResult::HttpResponseReceived), + "session {index}" + ); + } + assert_eq!(fetches.load(Ordering::SeqCst), 0); + } + } + /// Operators read what changed on a withheld provider and list frozen + /// sandboxes without fetching each captured policy. + #[tokio::test] + async fn frozen_policy_reads_name_withheld_providers_and_list_freeze_state() { + use openshell_core::proto::frozen_sandbox_policies_server::FrozenSandboxPolicies; + use openshell_core::proto::{ + FrozenProviderChange, GetFrozenSandboxPolicyRequest, ListFrozenSandboxesRequest, + }; + let state = test_server_state().await; + let mut provider = seed(&state, true).await; + state + .store + .put_message(&test_sandbox( + "sb-live", + "live", + openshell_policy::restrictive_default_policy(), + Vec::new(), + )) + .await + .unwrap(); + let service = crate::grpc::OpenShellService::new(Arc::clone(&state)); + let list = || async { + FrozenSandboxPolicies::list_sandboxes( + &service, + with_user(Request::new(ListFrozenSandboxesRequest { + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), + ..Default::default() + })), + ) + .await + .unwrap() + .into_inner() + }; + let withheld = || async { + FrozenSandboxPolicies::get_policy( + &service, + with_user(Request::new(GetFrozenSandboxPolicyRequest { + name: NAME.into(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), + })), + ) + .await + .unwrap() + .into_inner() + .withheld_providers + }; + + // Pending: listed without a hash. The live sandbox has no entry. + let pending = list().await; + assert_eq!(pending.sandboxes.len(), 2); + assert!(pending.next_page_token.is_empty()); + assert_eq!(pending.frozen_sandboxes.len(), 1); + assert_eq!(pending.frozen_sandboxes[0].workspace, "default"); + assert_eq!(pending.frozen_sandboxes[0].sandbox, NAME); + assert!(pending.frozen_sandboxes[0].policy_hash.is_none()); + assert!(pending.frozen_sandboxes[0].frozen_time.is_none()); + + let (accepted, _) = initialize(&state).await; + let captured = list().await.frozen_sandboxes; + assert_eq!(captured.len(), 1); + assert_eq!( + captured[0].policy_hash.as_deref(), + Some(accepted.policy_hash.as_str()) + ); + assert!(captured[0].frozen_time.is_some()); + assert!(withheld().await.is_empty()); + + // A configuration change withholds, and reverting it restores delivery. + let original = provider.clone(); + provider + .config + .insert("region".to_string(), "changed".to_string()); + state.store.put_message(&provider).await.unwrap(); + let changed = withheld().await; + assert_eq!(changed.len(), 1); + assert_eq!(changed[0].provider, PROVIDER); + assert_eq!(changed[0].change(), FrozenProviderChange::Config); + state.store.put_message(&original).await.unwrap(); + assert!(withheld().await.is_empty()); + } + + /// Frozen delivery forces proposals off from creation, so turning them on + /// must not report success. + #[tokio::test] + async fn frozen_sandbox_refuses_enabling_agent_policy_proposals() { + let state = test_server_state().await; + seed(&state, true).await; + let set = |key: &str, value: bool| { + handle_update_config( + &state, + with_user(Request::new(UpdateConfigRequest { + sandbox: NAME.to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), + setting_key: key.to_string(), + setting_value: Some(SettingValue { + value: Some(setting_value::Value::BoolValue(value)), + }), + ..Default::default() + })), + ) + }; + // Refused while the freeze is still pending. + let error = set(settings::AGENT_POLICY_PROPOSALS_ENABLED_KEY, true) + .await + .unwrap_err(); + assert_eq!(error.code(), Code::FailedPrecondition); + assert!(error.message().contains("frozen"), "{}", error.message()); + set(settings::AGENT_POLICY_PROPOSALS_ENABLED_KEY, false) + .await + .unwrap(); + // Other settings are not part of the freeze. + set("ocsf_json_enabled", true).await.unwrap(); + } + + /// The public diagnostic of a rejected frozen configuration names a repair + /// the sandbox still allows. A captured policy cannot be replaced. + #[tokio::test] + async fn frozen_policy_rejection_names_a_repair_that_still_works() { + let reject = |state: Arc, + instance: String, + config: GetSandboxConfigResponse| async move { + handle_report_sandbox_configuration( + &state, + with_sandbox( + Request::new(ReportSandboxConfigurationRequest { + sandbox_id: ID.to_string(), + admission: Some(SandboxConfigurationAdmission { + instance_id: instance, + state: ConfigurationAdmissionState::Rejected.into(), + policy_version: config.version, + policy_hash: config.policy_hash.clone(), + config_revision: config.config_revision, + provider_env_revision: config.provider_env_revision, + ..Default::default() + }), + ..Default::default() + }), + ID, + ), + ) + .await + .unwrap(); + stored_sandbox(&state) + .await + .status + .unwrap() + .configuration_admission + .unwrap() + .error + }; + + // Captured: the runtime refuses a policy that nobody can replace. + let state = test_server_state().await; + seed(&state, true).await; + let (_, instance) = initialize(&state).await; + let current = config(&state).await; + let error = reject(Arc::clone(&state), instance, current).await; + assert_eq!( + Some(error.as_str()), + frozen::rejection_diagnostic(true, true, PolicySource::Sandbox) + ); + assert!(error.contains("delete and recreate"), "{error}"); + assert!(!error.contains("replace the policy"), "{error}"); + + // Pending under a global policy: only that policy can be repaired. + let state = test_server_state().await; + seed(&state, true).await; + update_global(&state, "api.original.example").await; + let instance = uuid::Uuid::new_v4().to_string(); + register(&state, &instance, "").await; + let pending = config(&state).await; + assert!(pending.configuration_admitted, "{}", pending.configuration_error); + let error = reject(Arc::clone(&state), instance, pending).await; + assert!(error.contains("global policy"), "{error}"); + + // Pending with its own policy: it is still editable, so the ordinary + // advice stands. + let state = test_server_state().await; + seed(&state, true).await; + let instance = uuid::Uuid::new_v4().to_string(); + register(&state, &instance, "").await; + let pending = config(&state).await; + let error = reject(Arc::clone(&state), instance, pending).await; + assert_eq!(error, CONFIGURATION_NOT_ACTIVATED); + + // A captured policy that no longer builds keeps its failure category. + assert!( + frozen_configuration_failure_diagnostic(&Status::failed_precondition("invalid policy")) + .contains("delete and recreate") + ); + assert!( + frozen_configuration_failure_diagnostic(&Status::failed_precondition( + "provider is missing" + )) + .starts_with("Frozen provider configuration") + ); + } +} diff --git a/crates/openshell-server/src/grpc/provider.rs b/crates/openshell-server/src/grpc/provider.rs index e14424bc9c..b6f68ea12f 100644 --- a/crates/openshell-server/src/grpc/provider.rs +++ b/crates/openshell-server/src/grpc/provider.rs @@ -2282,6 +2282,14 @@ pub async fn validate_provider_update_against_attached_sandboxes_with_catalog( ) -> Result<(), Status> { let provider_name = provider.object_name().to_string(); for sandbox in sandboxes_using_provider_records(store, workspace, &provider_name).await? { + if super::policy::frozen::snapshot(store, &sandbox) + .await? + .is_some() + { + // Frozen readers use their captured catalog and withhold credentials + // when this provider no longer matches their authorization. + continue; + } let sandbox_name = sandbox.object_name().to_string(); let Some(spec) = sandbox.spec.as_ref() else { continue; @@ -3413,7 +3421,8 @@ pub(super) async fn handle_update_provider_profiles( publish_provider_profile_change(state, &workspace); Ok(Response::new(UpdateProviderProfilesResponse { - diagnostics: Vec::new(), + // Warnings only: a frozen sandbox that keeps its captured profile. + diagnostics: diagnostics.into_iter().map(proto_diagnostic).collect(), profile: Some(profile), updated: true, })) @@ -4370,6 +4379,29 @@ async fn profile_attached_sandbox_diagnostics( if super::policy::skip_sandbox_with_unsupported_cedar_policy(&sandbox) { continue; } + if let Some(frozen) = super::policy::frozen::snapshot(store, &sandbox).await? { + for provider in &frozen.providers { + let same_scope = if is_platform_scope { + provider.profile_workspace.is_empty() + } else { + provider.profile_workspace == workspace + }; + if same_scope && let Some((source, _)) = candidate_profiles.get(&provider.r#type) { + diagnostics.push(ProfileValidationDiagnostic { + source: source.clone(), + profile_id: provider.r#type.clone(), + field: "sandbox".to_string(), + message: format!( + "sandbox '{}/{}' is frozen and retains its initialized provider policy", + sandbox.object_workspace(), + sandbox.object_name() + ), + severity: "warning".to_string(), + }); + } + } + continue; + } let sandbox_name = sandbox.object_name().to_string(); let sandbox_workspace = sandbox.object_workspace().to_string(); let spec = sandbox.spec.as_ref().expect("filtered by scan_sandboxes"); @@ -4752,6 +4784,17 @@ fn token_grant_configuration_status(code: tonic::Code) -> Status { .to_status_with_code(code) } +/// A frozen sandbox's provider changed after the sandbox captured it. +/// Authorizing the provider again cannot restore the grant, so this is a +/// configuration failure: revert the provider change or recreate the sandbox. +fn token_grant_frozen_provider_changed_status() -> Status { + TokenGrantFailure::new( + TokenGrantFailureKind::Configuration, + TokenGrantStage::GatewayRpc, + ) + .to_status_with_code(tonic::Code::FailedPrecondition) +} + fn token_grant_store_status() -> Status { TokenGrantFailure::new( TokenGrantFailureKind::Unavailable, @@ -4802,6 +4845,65 @@ fn token_grant_dependency_status(status: Status) -> Status { TokenGrantFailure::new(kind, TokenGrantStage::GatewayRpc).to_status_with_code(status.code()) } +async fn load_provider_subject_token_context( + state: &ServerState, + sandbox: &Sandbox, + provider_name: &str, +) -> Result<(Provider, ProviderProfile), Status> { + let mut captured = super::policy::frozen::snapshot(state.store.as_ref(), sandbox).await?; + for _ in 0..2 { + let (provider, catalog) = if let Some(snapshot) = captured.as_ref() { + let context = + super::policy::frozen::provider_context_from_snapshot(state, sandbox, snapshot) + .await + .map_err(token_grant_dependency_status)?; + if context.withheld_providers.contains(provider_name) { + return Err(token_grant_frozen_provider_changed_status()); + } + let provider = context + .records + .into_iter() + .find(|record| record.name == provider_name) + .ok_or_else(|| token_grant_configuration_status(tonic::Code::PermissionDenied))? + .provider; + (provider, context.catalog) + } else { + let live = async { + let workspace = sandbox.object_workspace(); + let provider = state + .store + .get_message_by_name::(workspace, provider_name) + .await + .map_err(|_| token_grant_store_status())? + .ok_or_else(|| token_grant_configuration_status(tonic::Code::NotFound))?; + let catalog = state + .provider_profile_sources + .snapshot_catalog(state.store.as_ref(), workspace) + .await + .map_err(token_grant_dependency_status)?; + Ok::<_, Status>((provider, catalog)) + } + .await; + if let Some(snapshot) = + super::policy::frozen::snapshot(state.store.as_ref(), sandbox).await? + { + captured = Some(snapshot); + continue; + } + live? + }; + let profile = get_provider_type_profile_for_scope( + &catalog, + &provider.r#type, + &provider.profile_workspace, + ) + .ok_or_else(|| token_grant_configuration_status(tonic::Code::FailedPrecondition))? + .to_proto(); + return Ok((provider, profile)); + } + unreachable!("a captured frozen policy cannot transition again") +} + async fn exchange_provider_subject_token_inner( state: &Arc, request: Request, @@ -4845,7 +4947,6 @@ async fn exchange_provider_subject_token_inner( .await .map_err(|_| token_grant_store_status())? .ok_or_else(|| token_grant_configuration_status(tonic::Code::NotFound))?; - let workspace = sandbox.object_workspace().to_string(); let spec = sandbox .spec .as_ref() @@ -4860,24 +4961,8 @@ async fn exchange_provider_subject_token_inner( )); } - let provider = state - .store - .get_message_by_name::(&workspace, &req.provider) - .await - .map_err(|_| token_grant_store_status())? - .ok_or_else(|| token_grant_configuration_status(tonic::Code::NotFound))?; - let catalog = state - .provider_profile_sources - .snapshot_catalog(state.store.as_ref(), &workspace) - .await - .map_err(token_grant_dependency_status)?; - let profile = get_provider_type_profile_for_scope( - &catalog, - &provider.r#type, - &provider.profile_workspace, - ) - .ok_or_else(|| token_grant_configuration_status(tonic::Code::FailedPrecondition))?; - let profile_proto = profile.to_proto(); + let (provider, profile_proto) = + load_provider_subject_token_context(state, &sandbox, &req.provider).await?; let credential = profile_proto .credentials .iter() @@ -6653,6 +6738,502 @@ pub(super) mod tests { ); } + fn frozen_exchange_profile(endpoint: &str, subject: &str) -> ProviderProfile { + let mut profile = custom_profile("frozen-exchange"); + profile.credentials = vec![ + ProviderProfileCredential { + name: subject.to_string(), + ..Default::default() + }, + ProviderProfileCredential { + name: "access_token".to_string(), + auth_style: "bearer".to_string(), + header_name: "Authorization".to_string(), + token_grant: Some(ProviderCredentialTokenGrant { + grant_type: ProviderCredentialTokenGrantType::TokenExchange.into(), + token_endpoint: endpoint.to_string(), + subject_token: Some(ProviderCredentialTokenGrantSubjectToken { + source: "provider_credential".to_string(), + credential: subject.to_string(), + ..Default::default() + }), + ..Default::default() + }), + ..Default::default() + }, + ]; + profile + } + + async fn frozen_exchange_state( + next_profiles: Vec, + ) -> ( + Arc, + Sandbox, + Provider, + Arc, + ) { + frozen_exchange_state_with( + frozen_exchange_profile("https://original.example/token", "subject_token"), + next_profiles, + ) + .await + } + + async fn frozen_exchange_state_with( + original: ProviderProfile, + next_profiles: Vec, + ) -> ( + Arc, + Sandbox, + Provider, + Arc, + ) { + use openshell_core::proto::{FrozenSandboxPolicy, FrozenSandboxProvider}; + let fetches = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let mut state = test_server_state_without_provider_profiles().await; + Arc::get_mut(&mut state).unwrap().provider_profile_sources = + ProviderProfileSources::from_test_snapshot_sequence( + vec![ + ("original".to_string(), vec![original]), + ("replacement".to_string(), next_profiles), + ], + Arc::clone(&fetches), + ); + let mut provider = provider_with_values("frozen-exchange-provider", "frozen-exchange"); + provider.metadata.as_mut().unwrap().id = "frozen-exchange-provider-id".to_string(); + provider.credentials = HashMap::from([ + ("subject_token".to_string(), "original-subject".to_string()), + ("live_subject".to_string(), "live-subject".to_string()), + ]); + state.store.put_message(&provider).await.unwrap(); + let catalog = state + .provider_profile_sources + .snapshot_catalog(state.store.as_ref(), "default") + .await + .unwrap(); + let captured_profile = catalog + .get_profile_for_scope(&provider.r#type, &provider.profile_workspace) + .unwrap(); + let sandbox = Sandbox { + metadata: Some(openshell_core::proto::datamodel::v1::ObjectMeta { + id: "frozen-exchange-sandbox".to_string(), + name: "frozen-exchange-sandbox".to_string(), + workspace: "default".to_string(), + ..Default::default() + }), + spec: Some(SandboxSpec { + providers: vec![provider.object_name().to_string()], + ..Default::default() + }), + ..Default::default() + }; + state.store.create_frozen_sandbox(&sandbox).await.unwrap(); + let stored = state + .store + .get_message::(sandbox.object_id()) + .await + .unwrap() + .unwrap(); + state + .store + .accept_frozen_sandbox_configuration( + stored, + FrozenSandboxPolicy { + providers: vec![FrozenSandboxProvider { + provider: provider.object_name().to_string(), + provider_id: provider.object_id().to_string(), + r#type: provider.r#type.clone(), + config: provider.config.clone(), + profile_workspace: provider.profile_workspace.clone(), + profile: Some(captured_profile), + ..Default::default() + }], + ..Default::default() + }, + ) + .await + .unwrap(); + (state, sandbox, provider, fetches) + } + + fn frozen_exchange_request( + sandbox: &Sandbox, + provider: &Provider, + ) -> Request { + let mut request = Request::new(ExchangeProviderSubjectTokenRequest { + sandbox_id: sandbox.object_id().to_string(), + provider: provider.object_name().to_string(), + credential_key: "access_token".to_string(), + supervisor_jwt_svid: "unused-before-subject-authorization".to_string(), + }); + request + .extensions_mut() + .insert(Principal::Sandbox(SandboxPrincipal { + sandbox_id: sandbox.object_id().to_string(), + source: SandboxIdentitySource::BootstrapJwt { + issuer: "test".to_string(), + auth_epoch: None, + }, + trust_domain: None, + })); + request + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn frozen_exchange_capture_during_live_lookup_uses_captured_profile() { + use crate::persistence::frozen_policy::{FROZEN_POLICY_OBJECT_TYPE, frozen_policy_id}; + let (state, sandbox, provider, _) = frozen_exchange_state(Vec::new()).await; + let snapshot = state + .store + .get_sandbox_frozen_policy(sandbox.object_id()) + .await + .unwrap() + .unwrap() + .policy + .unwrap(); + // Build the pending fixture from the same captured inputs; the + // production operation below performs the only transition under test. + let pending = crate::storage_proto::StoredFrozenSandboxPolicy { + sandbox_id: sandbox.object_id().into(), + policy: None, + }; + let private_id = frozen_policy_id(sandbox.object_id()); + let private = state + .store + .get(FROZEN_POLICY_OBJECT_TYPE, &private_id) + .await + .unwrap() + .unwrap(); + state + .store + .write_atomically(&[crate::persistence::AtomicWrite::Update { + object_type: FROZEN_POLICY_OBJECT_TYPE.into(), + id: private_id, + payload: pending.encode_to_vec(), + expected_version: private.resource_version, + }]) + .await + .unwrap(); + let (sources, gate) = + ProviderProfileSources::from_test_profiles_blocked(vec![frozen_exchange_profile( + "https://changed.example/token", + "live_subject", + )]); + let mut server = Arc::try_unwrap(state).ok().unwrap(); + server.provider_profile_sources = sources; + let state = Arc::new(server); + let reader = Arc::clone(&state); + let requested_sandbox = sandbox.clone(); + let name = provider.object_name().to_string(); + let read = tokio::spawn(async move { + load_provider_subject_token_context(&reader, &requested_sandbox, &name) + .await + .unwrap() + }); + gate.entered().await; + let current = state + .store + .get_message::(sandbox.object_id()) + .await + .unwrap() + .unwrap(); + state + .store + .accept_frozen_sandbox_configuration(current, snapshot) + .await + .unwrap(); + gate.release(); + let (_, profile) = read.await.unwrap(); + let grant = profile + .credentials + .iter() + .find(|credential| credential.name == "access_token") + .unwrap() + .token_grant + .as_ref() + .unwrap(); + assert_eq!(grant.token_endpoint, "https://original.example/token"); + assert_eq!( + grant.subject_token.as_ref().unwrap().credential, + "subject_token" + ); + } + + #[tokio::test] + async fn frozen_exchange_uses_captured_profile_and_rotated_subject_without_live_sources() { + use std::sync::atomic::Ordering; + for next_profiles in [ + vec![frozen_exchange_profile( + "https://changed.example/token", + "live_subject", + )], + Vec::new(), + ] { + let (state, sandbox, mut provider, fetches) = + frozen_exchange_state(next_profiles).await; + provider + .credentials + .insert("subject_token".to_string(), "rotated-subject".to_string()); + state.store.put_message(&provider).await.unwrap(); + let (selected_provider, selected_profile) = + load_provider_subject_token_context(&state, &sandbox, provider.object_name()) + .await + .unwrap(); + let grant = selected_profile + .credentials + .iter() + .find(|credential| credential.name == "access_token") + .unwrap() + .token_grant + .as_ref() + .unwrap(); + assert_eq!(grant.token_endpoint, "https://original.example/token"); + assert_eq!( + grant.subject_token.as_ref().unwrap().credential, + "subject_token" + ); + assert_eq!( + resolve_subject_token_credential( + &state.credentials, + &selected_provider, + "subject_token" + ) + .await + .unwrap(), + "rotated-subject" + ); + assert_eq!(selected_provider.object_id(), provider.object_id()); + assert_eq!(selected_provider.config, provider.config); + + // The actual RPC selects the captured, now-expired subject; + // it must stop before SPIFFE acquisition or an HTTP exchange. + provider + .credential_expiration_times + .insert("subject_token".to_string(), ts(0)); + state.store.put_message(&provider).await.unwrap(); + let error = handle_exchange_provider_subject_token( + &state, + frozen_exchange_request(&sandbox, &provider), + ) + .await + .unwrap_err(); + assert_eq!( + assert_generic(&error, Code::FailedPrecondition).kind(), + TokenGrantFailureKind::ProviderAuthorizationRequired + ); + assert_eq!( + fetches.load(Ordering::SeqCst), + 1, + "frozen exchange must never fetch the live source" + ); + } + } + + #[tokio::test] + async fn frozen_exchange_rejects_changed_authorization_before_subject_lookup() { + use std::sync::atomic::Ordering; + for change in ["configuration", "identity", "refresh authorization"] { + let (state, sandbox, mut provider, fetches) = + frozen_exchange_state(Vec::new()).await; + provider.credentials.clear(); + provider.credential_handles.insert( + "subject_token".to_string(), + CredentialHandle { + driver: "unconfigured-driver-must-not-be-called".to_string(), + handle: "unresolved-subject".to_string(), + ..Default::default() + }, + ); + match change { + "configuration" => { + provider + .config + .insert("region".to_string(), "changed".to_string()); + } + "identity" => { + state + .store + .delete(Provider::object_type(), provider.object_id()) + .await + .unwrap(); + provider.metadata.as_mut().unwrap().id = "replacement-provider".to_string(); + } + _ => { + crate::provider_refresh::put_refresh_state( + state.store.as_ref(), + &StoredProviderCredentialRefreshState { + metadata: Some(openshell_core::proto::datamodel::v1::ObjectMeta { + id: "new-refresh-authorization".to_string(), + name: crate::provider_refresh::refresh_state_name( + provider.object_id(), + "subject_token", + ), + workspace: "default".to_string(), + ..Default::default() + }), + provider_id: provider.object_id().to_string(), + provider_name: provider.object_name().to_string(), + credential_key: "subject_token".to_string(), + authorization_epoch: "new-authorization".to_string(), + ..Default::default() + }, + ) + .await + .unwrap(); + } + } + state.store.put_message(&provider).await.unwrap(); + let error = handle_exchange_provider_subject_token( + &state, + frozen_exchange_request(&sandbox, &provider), + ) + .await + .unwrap_err(); + // Reauthorizing cannot restore a frozen grant, so the failure + // must not carry the reauthorize recovery. + assert_eq!( + assert_generic(&error, Code::FailedPrecondition).kind(), + TokenGrantFailureKind::Configuration, + "{change}" + ); + assert_eq!(fetches.load(Ordering::SeqCst), 1, "{change}"); + } + } + + /// The brokered access-token RPC resolves a frozen sandbox's grant from + /// its snapshot, as the subject-token exchange does. + #[tokio::test] + async fn frozen_access_token_grant_uses_captured_profile_and_withholds_changes() { + use std::sync::atomic::Ordering; + // The live profile keeps the endpoint, so the credential key still + // matches, and widens only the grant. + let profile = |scope: &str| { + let mut profile = + frozen_exchange_profile("https://original.example/token", "subject_token"); + profile.endpoints.push(NetworkEndpoint { + host: "api.example.com".to_string(), + port: 443, + protocol: "rest".to_string(), + access: openshell_core::proto::NetworkAccessPreset::ReadWrite as i32, + ..Default::default() + }); + profile.credentials[1].token_grant.as_mut().unwrap().scopes = + vec![scope.to_string()]; + profile + }; + let (state, sandbox, mut provider, fetches) = + frozen_exchange_state_with(profile("read"), vec![profile("admin")]).await; + let captured = state + .store + .get_sandbox_frozen_policy(sandbox.object_id()) + .await + .unwrap() + .unwrap() + .policy + .unwrap(); + let catalog = EffectiveProviderProfileCatalog::from_frozen_profiles(&[captured + .providers[0] + .profile + .clone() + .unwrap()]) + .unwrap(); + let mut configured = HashMap::new(); + insert_dynamic_credentials_for_profile( + &mut configured, + &get_provider_type_profile_for_scope( + &catalog, + &provider.r#type, + &provider.profile_workspace, + ) + .unwrap(), + provider.object_name(), + provider.object_id(), + ) + .unwrap(); + let key = configured.into_keys().next().unwrap(); + + let grant = access_token::grant_configuration(&state, sandbox.object_id(), &key) + .await + .unwrap() + .grant; + assert_eq!(grant.scopes, ["read"]); + assert_eq!(fetches.load(Ordering::SeqCst), 1); + + provider + .config + .insert("region".to_string(), "changed".to_string()); + state.store.put_message(&provider).await.unwrap(); + let error = access_token::grant_configuration(&state, sandbox.object_id(), &key) + .await + .err() + .unwrap(); + assert_eq!( + assert_generic(&error, Code::FailedPrecondition).kind(), + TokenGrantFailureKind::Configuration + ); + assert_eq!(fetches.load(Ordering::SeqCst), 1); + } + + /// The frozen loader applies the live loader's guard: a static value + /// that a GitHub App grant superseded is not delivered before its + /// first mint. + #[tokio::test] + async fn frozen_provider_context_withholds_a_superseded_github_app_output() { + let (state, sandbox, provider, _) = frozen_exchange_state(Vec::new()).await; + let mut grant = StoredProviderCredentialRefreshState { + metadata: Some(openshell_core::proto::datamodel::v1::ObjectMeta { + id: "github-app-grant".to_string(), + name: crate::provider_refresh::refresh_state_name( + provider.object_id(), + "subject_token", + ), + workspace: "default".to_string(), + ..Default::default() + }), + provider_id: provider.object_id().to_string(), + provider_name: provider.object_name().to_string(), + credential_key: "subject_token".to_string(), + authorization_epoch: "app-epoch".to_string(), + strategy: ProviderCredentialRefreshStrategy::GithubAppInstallation as i32, + ..Default::default() + }; + crate::provider_refresh::put_refresh_state(state.store.as_ref(), &grant) + .await + .unwrap(); + let mut snapshot = state + .store + .get_sandbox_frozen_policy(sandbox.object_id()) + .await + .unwrap() + .unwrap() + .policy + .unwrap(); + // The grant existed at capture, so its epoch is part of the snapshot. + snapshot.providers[0].refresh_authorization_epochs = + HashMap::from([("subject_token".to_string(), "app-epoch".to_string())]); + let delivered = || async { + let context = crate::grpc::policy::frozen::provider_context_from_snapshot( + &state, &sandbox, &snapshot, + ) + .await + .unwrap(); + assert!(context.withheld_providers.is_empty()); + context.records[0].provider.credentials.clone() + }; + + let pending = delivered().await; + assert!(!pending.contains_key("subject_token")); + assert!(pending.contains_key("live_subject")); + + // After the first mint under this provider revision, it is delivered. + grant.first_mint_provider_version = 1; + crate::provider_refresh::put_refresh_state(state.store.as_ref(), &grant) + .await + .unwrap(); + assert!(delivered().await.contains_key("subject_token")); + } + #[test] fn invalid_grant_configuration_fails_before_acquisition() { let valid = token_grant_credential("access_token").token_grant.unwrap(); diff --git a/crates/openshell-server/src/grpc/provider/access_token.rs b/crates/openshell-server/src/grpc/provider/access_token.rs index 2936803b0a..9c68cea4e5 100644 --- a/crates/openshell-server/src/grpc/provider/access_token.rs +++ b/crates/openshell-server/src/grpc/provider/access_token.rs @@ -12,7 +12,8 @@ use super::{ log_token_grant_failure, oauth, perform_intermediate_token_exchange, provider_credential_expiration_ms, resolve_subject_token_credential, sanitize_token_grant_status, token_exchange_http_client, token_grant_configuration_status, - token_grant_dependency_status, token_grant_identity_rejected, token_grant_store_status, + token_grant_dependency_status, token_grant_frozen_provider_changed_status, + token_grant_identity_rejected, token_grant_store_status, }; use openshell_core::jwt::AuthenticatedSandboxSession; use openshell_core::proto::{ @@ -84,9 +85,9 @@ async fn authorize( } /// One configured credential of an attached provider. -struct ConfiguredGrant { +pub(super) struct ConfiguredGrant { provider: Provider, - grant: ProviderCredentialTokenGrant, + pub(super) grant: ProviderCredentialTokenGrant, /// The gateway's exact key for the credential, including its endpoint owner. key: String, } @@ -96,7 +97,7 @@ struct ConfiguredGrant { /// /// The caller's key must name a configured key exactly, apart from the /// generation a supervisor adds; a different or missing owner matches nothing. -async fn grant_configuration( +pub(super) async fn grant_configuration( state: &ServerState, sandbox_id: &str, key: &str, @@ -117,23 +118,52 @@ async fn grant_configuration( if !spec.providers.iter().any(|name| name == provider_name) { return Err(invalid()); } - let provider = state - .store - .get_message_by_name::(sandbox.object_workspace(), provider_name) + let frozen = super::super::policy::frozen::snapshot(state.store.as_ref(), &sandbox) .await - .map_err(|_| token_grant_store_status())? + .map_err(|_| token_grant_store_status())?; + let (provider, profile) = if let Some(snapshot) = frozen.as_ref() { + // A frozen sandbox mints under its captured provider authorization and + // profile. A later provider or profile change never moves the grant. + let context = + super::super::policy::frozen::provider_context_from_snapshot(state, &sandbox, snapshot) + .await + .map_err(token_grant_dependency_status)?; + if context.withheld_providers.contains(provider_name) { + return Err(token_grant_frozen_provider_changed_status()); + } + let provider = context + .records + .into_iter() + .find(|record| record.name == provider_name) + .ok_or_else(invalid)? + .provider; + let profile = get_provider_type_profile_for_scope( + &context.catalog, + &provider.r#type, + &provider.profile_workspace, + ) .ok_or_else(invalid)?; - let catalog = state - .provider_profile_sources - .profile_catalog(&state.store, sandbox.object_workspace(), &provider.r#type) - .await - .map_err(token_grant_dependency_status)?; - let profile = get_provider_type_profile_for_scope( - &catalog, - &provider.r#type, - &provider.profile_workspace, - ) - .ok_or_else(invalid)?; + (provider, profile) + } else { + let provider = state + .store + .get_message_by_name::(sandbox.object_workspace(), provider_name) + .await + .map_err(|_| token_grant_store_status())? + .ok_or_else(invalid)?; + let catalog = state + .provider_profile_sources + .profile_catalog(&state.store, sandbox.object_workspace(), &provider.r#type) + .await + .map_err(token_grant_dependency_status)?; + let profile = get_provider_type_profile_for_scope( + &catalog, + &provider.r#type, + &provider.profile_workspace, + ) + .ok_or_else(invalid)?; + (provider, profile) + }; let mut configured = HashMap::new(); insert_dynamic_credentials_for_profile( &mut configured, diff --git a/crates/openshell-server/src/grpc/sandbox.rs b/crates/openshell-server/src/grpc/sandbox.rs index 8e5762a33b..d3021dc832 100644 --- a/crates/openshell-server/src/grpc/sandbox.rs +++ b/crates/openshell-server/src/grpc/sandbox.rs @@ -302,11 +302,19 @@ fn generate_routable_name() -> String { pub(super) async fn handle_create_sandbox( state: &Arc, request: Request, +) -> Result, Status> { + handle_create_sandbox_with_mode(state, request, false).await +} + +pub(super) async fn handle_create_sandbox_with_mode( + state: &Arc, + request: Request, + frozen: bool, ) -> Result, Status> { let create_request = request.get_ref().clone(); // Sandbox creation retains large configuration values across awaits. // Box the inner future to keep this wrapper small for every caller. - let result = Box::pin(handle_create_sandbox_inner(state, request)).await; + let result = Box::pin(handle_create_sandbox_inner(state, request, frozen)).await; let created_sandbox = result .as_ref() .ok() @@ -563,6 +571,7 @@ fn sandbox_create_telemetry_attrs( async fn handle_create_sandbox_inner( state: &Arc, request: Request, + frozen: bool, ) -> Result, Status> { let principal = super::extract_principal(&request)?; let request = request.into_inner(); @@ -779,6 +788,7 @@ async fn handle_create_sandbox_inner( // their revisions cannot change before the sandbox's launch is committed. let mut runtime_inputs = super::policy::resolve_sandbox_create_runtime_inputs(state.as_ref(), &sandbox).await?; + runtime_inputs.freeze_policy = frozen; state .compute @@ -1563,6 +1573,7 @@ pub(super) async fn handle_attach_sandbox_provider( err } })?; + super::policy::frozen::ensure_mutable_by_id(state.store.as_ref(), sandbox.object_id()).await?; let sandbox_name = sandbox.object_name().to_string(); let sandbox_id = sandbox .metadata @@ -1738,6 +1749,7 @@ pub(super) async fn handle_detach_sandbox_provider( .await .map_err(|err| super::persistence_error_to_status(err, "acquire sandbox mutation lock"))?; let sandbox_name = sandbox.object_name().to_string(); + super::policy::frozen::ensure_mutable_by_id(state.store.as_ref(), sandbox.object_id()).await?; let sandbox_id = sandbox .metadata .as_ref() diff --git a/crates/openshell-server/src/lib.rs b/crates/openshell-server/src/lib.rs index fe12441f89..070803319d 100644 --- a/crates/openshell-server/src/lib.rs +++ b/crates/openshell-server/src/lib.rs @@ -3549,9 +3549,10 @@ mod tests { .map(|service| service.name.as_str()) .collect::>(), [ + "openshell.v1.FrozenSandboxPolicies", "openshell.v1.OpenShell", "openshell.v1.SandboxUpdates", - "openshell.v1.ServiceDiscovery" + "openshell.v1.ServiceDiscovery", ] ); diff --git a/crates/openshell-server/src/multiplex.rs b/crates/openshell-server/src/multiplex.rs index 6b8a4d1406..d48f508aa9 100644 --- a/crates/openshell-server/src/multiplex.rs +++ b/crates/openshell-server/src/multiplex.rs @@ -17,6 +17,7 @@ use hyper_util::{ service::TowerToHyperService, }; use metrics::{counter, histogram}; +use openshell_core::proto::frozen_sandbox_policies_server::FrozenSandboxPoliciesServer; use openshell_core::proto::open_shell_server::OpenShellServer; use openshell_core::proto::sandbox_updates_server::SandboxUpdatesServer; use openshell_core::proto::service_discovery_server::ServiceDiscoveryServer; @@ -328,12 +329,21 @@ impl MultiplexService { self.state.gateway_interceptors.clone(), Some(self.state.clone()), ); + let frozen_policies = + FrozenSandboxPoliciesServer::new(OpenShellService::new(self.state.clone())) + .max_decoding_message_size(MAX_GRPC_DECODE_SIZE); + let frozen_policies = GatewayInterceptorGrpcService::new( + frozen_policies, + self.state.gateway_interceptors.clone(), + Some(self.state.clone()), + ); let authz_policy = self.state.config.oidc.as_ref().map(AuthzPolicy::from); let authenticator_chain = build_authenticator_chain(&self.state); let grpc_service = AuthGrpcRouter::with_peer_identity( GrpcRouter::new(openshell, reflection) .with_sandbox_updates(sandbox_updates) - .with_discovery(discovery), + .with_discovery(discovery) + .with_frozen_policies(frozen_policies), authenticator_chain, authz_policy, self.state @@ -505,6 +515,16 @@ where }; let path = req.uri().path().to_string(); + // A frozen-policy RPC carries an ordinary mutation under another + // name. It must not skip an interceptor that gates that mutation. + if let Some(gated) = interceptors.skipped_gate(&path) { + let rpc = path.trim_start_matches('/'); + warn!(%rpc, %gated, "refused an RPC that would skip a gateway interceptor"); + return Ok(tonic::Status::failed_precondition(format!( + "gateway interceptors gate {gated}; bind an interceptor to {rpc} before using it" + )) + .into_http()); + } if !interceptors.should_intercept_path(&path) { return inner.ready().await?.call(req).await; } @@ -1021,11 +1041,12 @@ where /// Combined gRPC service for public gateway services and reflection. #[derive(Clone)] -pub struct GrpcRouter { +pub struct GrpcRouter { openshell: N, reflection: R, sandbox_updates: Option, discovery: Option, + frozen_policies: Option, } impl GrpcRouter { @@ -1035,6 +1056,7 @@ impl GrpcRouter { reflection, sandbox_updates: None, discovery: None, + frozen_policies: None, } } @@ -1044,24 +1066,36 @@ impl GrpcRouter { reflection: self.reflection, sandbox_updates: Some(sandbox_updates), discovery: self.discovery, + frozen_policies: self.frozen_policies, } } } -impl GrpcRouter { - fn with_discovery(self, discovery: T) -> GrpcRouter { +impl GrpcRouter { + fn with_discovery(self, discovery: T) -> GrpcRouter { GrpcRouter { openshell: self.openshell, reflection: self.reflection, sandbox_updates: self.sandbox_updates, discovery: Some(discovery), + frozen_policies: self.frozen_policies, + } + } + + fn with_frozen_policies(self, frozen_policies: T) -> GrpcRouter { + GrpcRouter { + openshell: self.openshell, + reflection: self.reflection, + sandbox_updates: self.sandbox_updates, + discovery: self.discovery, + frozen_policies: Some(frozen_policies), } } } pub const REFLECTION_PATH_PREFIX: &str = "/grpc.reflection.v1."; -impl tower::Service> for GrpcRouter +impl tower::Service> for GrpcRouter where N: tower::Service> + Clone + Send + 'static, N::Response: Send, @@ -1082,6 +1116,11 @@ where + Send + 'static, D::Future: Send, + F: tower::Service, Response = N::Response, Error = N::Error> + + Clone + + Send + + 'static, + F::Future: Send, B: Send + 'static, { type Response = N::Response; @@ -1110,6 +1149,13 @@ where && let Some(mut svc) = self.discovery.clone() { Box::pin(async move { svc.ready().await?.call(req).await }) + } else if req + .uri() + .path() + .starts_with("/openshell.v1.FrozenSandboxPolicies/") + && let Some(mut svc) = self.frozen_policies.clone() + { + Box::pin(async move { svc.ready().await?.call(req).await }) } else { let mut svc = self.openshell.clone(); Box::pin(async move { svc.ready().await?.call(req).await }) @@ -2095,6 +2141,177 @@ mod tests { interceptor_task.abort(); } + /// Validates every RPC it is bound to and counts the calls. + #[derive(Clone)] + struct GateTestInterceptor { + rpcs: &'static [&'static str], + validations: Arc, + } + + #[tonic::async_trait] + impl GatewayInterceptor for GateTestInterceptor { + async fn describe( + &self, + request: tonic::Request, + ) -> Result, tonic::Status> { + let mut manifest = PostCommitTestInterceptor(CREATE_SANDBOX_RPC) + .describe(request) + .await? + .into_inner(); + manifest.bindings = self + .rpcs + .iter() + .enumerate() + .map(|(index, rpc)| InterceptorBinding { + id: format!("gate-{index}"), + selector: Some(InterceptorSelector { + rpc: (*rpc).to_string(), + service: String::new(), + method: String::new(), + }), + phases: vec![GatewayInterceptorPhase::Validate.into()], + failure_policy: "fail_closed".into(), + }) + .collect(); + Ok(tonic::Response::new(manifest)) + } + + async fn evaluate( + &self, + _request: tonic::Request, + ) -> Result, tonic::Status> { + self.validations.fetch_add(1, Ordering::SeqCst); + Ok(tonic::Response::new(InterceptorResult { + allowed: true, + ..InterceptorResult::default() + })) + } + + async fn snapshot_provider_profiles( + &self, + _request: tonic::Request, + ) -> Result, tonic::Status> { + Err(tonic::Status::unimplemented("not a profile source")) + } + } + + /// Send `body` to `path` through the interceptor wrapper. Returns the gRPC + /// status and message, how often the interceptor validated, and how often + /// the request reached the gateway service. + async fn call_through_gate( + rpcs: &'static [&'static str], + path: &'static str, + body: Vec, + ) -> (String, String, usize, usize) { + let validations = Arc::new(AtomicUsize::new(0)); + let interceptor = GateTestInterceptor { + rpcs, + validations: validations.clone(), + }; + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let task = tokio::spawn(async move { + tonic::transport::Server::builder() + .add_service(GatewayInterceptorServer::new(interceptor)) + .serve_with_incoming(TcpListenerStream::new(listener)) + .await + .unwrap(); + }); + let runtime = openshell_gateway_interceptors::initialize(vec![GatewayInterceptorConfig { + name: "post-commit-test".into(), + grpc_endpoint: format!("http://{address}"), + ..Default::default() + }]) + .await + .unwrap(); + let reached = Arc::new(AtomicUsize::new(0)); + let reached_for_service = reached.clone(); + let inner = tower::service_fn(move |_request: Request| { + let reached = reached_for_service.clone(); + async move { + reached.fetch_add(1, Ordering::SeqCst); + let mut trailers = http::HeaderMap::new(); + trailers.insert("grpc-status", HeaderValue::from_static("0")); + Ok::<_, Infallible>(Response::new(tonic_body_from_bytes_and_trailers( + Bytes::new(), + Some(trailers), + ))) + } + }); + let mut service = GatewayInterceptorGrpcService::new(inner, runtime, None); + let request = Request::builder() + .uri(path) + .body(boxed_body_from_bytes(grpc_frame(&body))) + .unwrap(); + let response = service.ready().await.unwrap().call(request).await.unwrap(); + task.abort(); + let message = response + .headers() + .get("grpc-message") + .and_then(|value| value.to_str().ok()) + .unwrap_or_default() + .to_string(); + ( + grpc_status_from_response(&response), + message, + validations.load(Ordering::SeqCst), + reached.load(Ordering::SeqCst), + ) + } + + #[tokio::test] + async fn frozen_policy_rpc_cannot_skip_a_gate_on_its_ordinary_twin() { + use openshell_core::proto::{CreateFrozenSandboxRequest, UpdateFrozenGlobalConfigRequest}; + const FAILED_PRECONDITION: &str = "9"; + let frozen_create = CreateFrozenSandboxRequest::default().encode_to_vec(); + let frozen_update = UpdateFrozenGlobalConfigRequest::default().encode_to_vec(); + + // Gated only on the ordinary RPC: the twin is refused before any + // interceptor or handler runs. + for (gate, path, body, ordinary) in [ + ( + &[CREATE_SANDBOX_RPC][..], + "/openshell.v1.FrozenSandboxPolicies/CreateSandbox", + frozen_create.clone(), + CREATE_SANDBOX_RPC, + ), + ( + &["openshell.v1.OpenShell/UpdateConfig"][..], + "/openshell.v1.FrozenSandboxPolicies/UpdateGlobalConfig", + frozen_update, + "openshell.v1.OpenShell/UpdateConfig", + ), + ] { + let (status, message, validations, reached) = call_through_gate(gate, path, body).await; + assert_eq!(status, FAILED_PRECONDITION, "{path}: {message}"); + assert!(message.contains(ordinary), "{message}"); + assert_eq!((validations, reached), (0, 0), "{path}"); + } + + // Bound as well: the twin is validated and reaches the handler. + let (status, message, validations, reached) = call_through_gate( + &[ + CREATE_SANDBOX_RPC, + "openshell.v1.FrozenSandboxPolicies/CreateSandbox", + ], + "/openshell.v1.FrozenSandboxPolicies/CreateSandbox", + frozen_create.clone(), + ) + .await; + assert_eq!(status, "0", "{message}"); + assert_eq!((validations, reached), (1, 1)); + + // No gate on the ordinary RPC: the twin passes through untouched. + let (status, message, validations, reached) = call_through_gate( + &["openshell.v1.OpenShell/DeleteSandbox"], + "/openshell.v1.FrozenSandboxPolicies/CreateSandbox", + frozen_create, + ) + .await; + assert_eq!(status, "0", "{message}"); + assert_eq!((validations, reached), (0, 1)); + } + #[derive(Clone, Default)] struct ReplayTestInterceptor { modifications: Arc, @@ -3121,13 +3338,15 @@ mod tests { }; let mut router = GrpcRouter::new(service("openshell"), service("reflection")) .with_sandbox_updates(service("sandbox_updates")) - .with_discovery(service("discovery")); + .with_discovery(service("discovery")) + .with_frozen_policies(service("frozen_policies")); for path in [ "/openshell.v1.OpenShell/Health", "/openshell.v1.SandboxUpdates/UpdateSandbox", "/openshell.v1.ServiceDiscovery/GetServiceRouteSnapshot", "/openshell.v1.ServiceDiscovery/WatchServiceRoutes", + "/openshell.v1.FrozenSandboxPolicies/GetConfig", "/grpc.reflection.v1.ServerReflection/ServerReflectionInfo", ] { router @@ -3148,6 +3367,7 @@ mod tests { "sandbox_updates", "discovery", "discovery", + "frozen_policies", "reflection" ] ); @@ -3249,6 +3469,7 @@ mod tests { assert_eq!( names, vec![ + "openshell.v1.FrozenSandboxPolicies", "openshell.v1.OpenShell", "openshell.v1.SandboxUpdates", "openshell.v1.ServiceDiscovery" diff --git a/crates/openshell-server/src/persistence/frozen_policy.rs b/crates/openshell-server/src/persistence/frozen_policy.rs new file mode 100644 index 0000000000..fc209c5e5b --- /dev/null +++ b/crates/openshell-server/src/persistence/frozen_policy.rs @@ -0,0 +1,389 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Creation-only mode and first-accepted policy, separate from public sandbox rows. + +use super::{ + AtomicWrite, ObjectListQuery, PersistenceError, PersistenceResult, Store, WriteResult, + current_time_ms, map_db_error, +}; +use crate::storage_proto::StoredFrozenSandboxPolicy; +use openshell_core::proto::{FrozenSandboxPolicy, Sandbox}; +use openshell_core::{ + GetResourceVersion, ObjectId, ObjectLabels, ObjectName, ObjectWorkspace, SetResourceVersion, +}; +use prost::Message; + +pub const FROZEN_POLICY_OBJECT_TYPE: &str = "sandbox_frozen_policy"; + +pub fn frozen_policy_id(sandbox_id: &str) -> String { + format!("sandbox-frozen-policy:{sandbox_id}") +} + +pub fn decode_frozen_policy( + sandbox_id: &str, + payload: &[u8], +) -> PersistenceResult { + let state = StoredFrozenSandboxPolicy::decode(payload) + .map_err(|error| PersistenceError::Decode(error.to_string()))?; + if state.sandbox_id != sandbox_id { + return Err(PersistenceError::Decode( + "invalid frozen sandbox policy identity".into(), + )); + } + Ok(state) +} + +impl Store { + pub(crate) async fn get_sandbox_frozen_policy( + &self, + sandbox_id: &str, + ) -> PersistenceResult> { + self.get(FROZEN_POLICY_OBJECT_TYPE, &frozen_policy_id(sandbox_id)) + .await? + .map(|record| decode_frozen_policy(sandbox_id, &record.payload)) + .transpose() + } + + /// IDs of the sandboxes that hold a captured policy. + /// + /// Reads the freeze records alone, so a caller holding the fleet-wide + /// mutation lock does not read every sandbox. + pub(crate) async fn captured_frozen_sandbox_ids(&self) -> PersistenceResult> { + self.collect_records(FROZEN_POLICY_OBJECT_TYPE, ObjectListQuery::AllWorkspaces) + .await? + .into_iter() + .filter_map(|record| { + match StoredFrozenSandboxPolicy::decode(record.payload.as_slice()) { + Ok(state) => state.policy.is_some().then_some(Ok(state.sandbox_id)), + Err(error) => Some(Err(PersistenceError::Decode(error.to_string()))), + } + }) + .collect() + } + + /// Commit the immutable mode with the public identity before any driver dispatch. + pub(crate) async fn create_frozen_sandbox( + &self, + sandbox: &Sandbox, + ) -> PersistenceResult { + let sandbox_id = sandbox.object_id(); + if sandbox_id.is_empty() || sandbox.object_workspace().is_empty() { + return Err(PersistenceError::Encode( + "frozen sandbox requires an immutable id and workspace".into(), + )); + } + let private_id = frozen_policy_id(sandbox_id); + let payload = sandbox.encode_to_vec(); + let private_payload = StoredFrozenSandboxPolicy { + sandbox_id: sandbox_id.into(), + policy: None, + } + .encode_to_vec(); + let labels = serde_json::to_value(sandbox.object_labels().unwrap_or_default()) + .map_err(|error| PersistenceError::Encode(error.to_string()))?; + let now_ms = current_time_ms(); + match self { + Self::Sqlite(store) => { + let mut tx = store + .pool + .begin_with("BEGIN IMMEDIATE") + .await + .map_err(|error| map_db_error(&error))?; + sqlx::query("INSERT INTO objects (object_type, id, name, workspace, payload, labels, created_at_ms, updated_at_ms, resource_version) VALUES ('sandbox', ?1, ?2, ?3, ?4, ?5, ?6, ?6, 1)") + .bind(sandbox_id).bind(sandbox.object_name()).bind(sandbox.object_workspace()) + .bind(&payload).bind(labels.to_string()).bind(now_ms) + .execute(&mut *tx).await.map_err(|error| map_db_error(&error))?; + sqlx::query("INSERT INTO objects (object_type, id, name, workspace, scope, payload, created_at_ms, updated_at_ms, resource_version) VALUES (?1, ?2, NULL, '', ?3, ?4, ?5, ?5, 1)") + .bind(FROZEN_POLICY_OBJECT_TYPE).bind(&private_id).bind(sandbox_id).bind(&private_payload).bind(now_ms) + .execute(&mut *tx).await.map_err(|error| map_db_error(&error))?; + tx.commit().await.map_err(|error| map_db_error(&error))?; + } + Self::Postgres(store) => { + let mut tx = store + .pool + .begin() + .await + .map_err(|error| map_db_error(&error))?; + sqlx::query("INSERT INTO objects (object_type, id, name, workspace, payload, labels, created_at_ms, updated_at_ms, resource_version) VALUES ('sandbox', $1, $2, $3, $4, $5, $6, $6, 1)") + .bind(sandbox_id).bind(sandbox.object_name()).bind(sandbox.object_workspace()) + .bind(&payload).bind(&labels).bind(now_ms) + .execute(&mut *tx).await.map_err(|error| map_db_error(&error))?; + sqlx::query("INSERT INTO objects (object_type, id, name, workspace, scope, payload, created_at_ms, updated_at_ms, resource_version) VALUES ($1, $2, NULL, '', $3, $4, $5, $5, 1)") + .bind(FROZEN_POLICY_OBJECT_TYPE).bind(&private_id).bind(sandbox_id).bind(&private_payload).bind(now_ms) + .execute(&mut *tx).await.map_err(|error| map_db_error(&error))?; + tx.commit().await.map_err(|error| map_db_error(&error))?; + } + } + Ok(WriteResult { + resource_version: 1, + created_at_ms: now_ms, + updated_at_ms: now_ms, + }) + } + + /// The sandbox CAS fences every writer that read before first acceptance. + pub(crate) async fn accept_frozen_sandbox_configuration( + &self, + mut sandbox: Sandbox, + policy: FrozenSandboxPolicy, + ) -> PersistenceResult { + let sandbox_id = sandbox.object_id().to_string(); + let private_id = frozen_policy_id(&sandbox_id); + let record = self + .get(FROZEN_POLICY_OBJECT_TYPE, &private_id) + .await? + .ok_or_else(|| PersistenceError::Decode("frozen sandbox mode is missing".into()))?; + let mut state = decode_frozen_policy(&sandbox_id, &record.payload)?; + if state.policy.is_some() { + return Err(PersistenceError::Conflict { + current_resource_version: Some(sandbox.get_resource_version()), + }); + } + state.policy = Some(policy); + let results = self + .write_atomically(&[ + AtomicWrite::Update { + object_type: "sandbox".into(), + id: sandbox_id, + payload: sandbox.encode_to_vec(), + expected_version: sandbox.get_resource_version(), + }, + AtomicWrite::Update { + object_type: FROZEN_POLICY_OBJECT_TYPE.into(), + id: private_id, + payload: state.encode_to_vec(), + expected_version: record.resource_version, + }, + ]) + .await?; + sandbox.set_resource_version( + results[0] + .as_ref() + .expect("sandbox update result") + .resource_version, + ); + Ok(sandbox) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::policy_store::{AtomicPolicyRevisionWrite, PolicyStoreExt}; + use openshell_core::proto::datamodel::v1::ObjectMeta; + use openshell_core::proto::{PolicySource, SandboxPhase, SandboxSpec, SandboxStatus}; + use std::collections::HashMap; + + fn sandbox(id: &str, name: &str) -> Sandbox { + Sandbox { + metadata: Some(ObjectMeta { + id: id.into(), + name: name.into(), + workspace: "default".into(), + labels: HashMap::from([("team".into(), "frozen-test".into())]), + ..Default::default() + }), + spec: Some(SandboxSpec::default()), + status: Some(SandboxStatus::default()), + ..Default::default() + } + } + + async fn exercise_frozen_policy_persistence(store: &Store) { + Box::pin(async move { + let original = sandbox("frozen-id", "frozen-name"); + store.create_frozen_sandbox(&original).await.unwrap(); + let stale = store + .get_message::("frozen-id") + .await + .unwrap() + .unwrap(); + assert_eq!( + store + .get_sandbox_frozen_policy("frozen-id") + .await + .unwrap() + .unwrap() + .policy, + None + ); + let record = store.get("sandbox", "frozen-id").await.unwrap().unwrap(); + assert!(record.labels.unwrap().contains("frozen-test")); + + // Name contention cannot leave an orphan mode for an uncreated identity. + assert!( + store + .create_frozen_sandbox(&sandbox("other-id", "frozen-name")) + .await + .is_err() + ); + assert!( + store + .get_message::("other-id") + .await + .unwrap() + .is_none() + ); + assert!( + store + .get_sandbox_frozen_policy("other-id") + .await + .unwrap() + .is_none() + ); + + let current = store + .update_message_cas::( + "frozen-id", + stale.get_resource_version(), + |sandbox| { + sandbox.status.as_mut().unwrap().phase = SandboxPhase::Ready.into(); + }, + ) + .await + .unwrap(); + let policy = openshell_policy::restrictive_default_policy(); + let snapshot = FrozenSandboxPolicy { + policy: Some(policy.clone()), + policy_hash: openshell_core::policy_identity::deterministic_policy_hash(&policy), + policy_source: PolicySource::Sandbox.into(), + version: 1, + ..Default::default() + }; + assert!(matches!( + store + .accept_frozen_sandbox_configuration(stale, snapshot.clone()) + .await, + Err(PersistenceError::Conflict { .. }) + )); + assert!( + store + .get_sandbox_frozen_policy("frozen-id") + .await + .unwrap() + .unwrap() + .policy + .is_none() + ); + let accepted = store + .accept_frozen_sandbox_configuration(current, snapshot.clone()) + .await + .unwrap(); + // Even a policy writer without an expected sandbox version is fenced in + // the same transaction that would insert its revision. + let write = AtomicPolicyRevisionWrite { + id: "forbidden-revision".into(), + sandbox_id: "frozen-id".into(), + workspace: "default".into(), + version: 2, + policy_payload: policy.encode_to_vec(), + policy_hash: snapshot.policy_hash.clone(), + provenance: HashMap::new(), + expected_resource_version: 0, + annotations: HashMap::new(), + backfill_policy: None, + }; + assert!(matches!( + store.put_policy_revision_atomic(&write).await, + Err(PersistenceError::Conflict { .. }) + )); + assert!( + store + .get_latest_policy("frozen-id") + .await + .unwrap() + .is_none() + ); + assert!(matches!( + store + .accept_frozen_sandbox_configuration(accepted.clone(), snapshot.clone()) + .await, + Err(PersistenceError::Conflict { .. }) + )); + + // A public status rewrite cannot clear the gateway-private snapshot. + let updated = store + .update_message_cas::( + "frozen-id", + accepted.get_resource_version(), + |sandbox| { + sandbox.status = Some(SandboxStatus::default()); + }, + ) + .await + .unwrap(); + assert_eq!( + store + .get_sandbox_frozen_policy("frozen-id") + .await + .unwrap() + .unwrap() + .policy, + Some(snapshot) + ); + assert!(matches!( + store + .delete_sandbox_with_image_state_if( + "frozen-id", + accepted.get_resource_version() + ) + .await, + Err(PersistenceError::Conflict { .. }) + )); + assert!( + store + .get_sandbox_frozen_policy("frozen-id") + .await + .unwrap() + .is_some() + ); + assert!( + store + .delete_sandbox_with_image_state_if("frozen-id", updated.get_resource_version()) + .await + .unwrap() + ); + assert!( + store + .get_sandbox_frozen_policy("frozen-id") + .await + .unwrap() + .is_none() + ); + let replacement = sandbox("replacement-id", "frozen-name"); + store.put_message(&replacement).await.unwrap(); + assert!( + store + .get_sandbox_frozen_policy("replacement-id") + .await + .unwrap() + .is_none() + ); + }) + .await; + } + + #[tokio::test] + async fn frozen_policy_persistence_is_atomic_and_identity_scoped() { + exercise_frozen_policy_persistence(&super::super::test_store().await).await; + } + + #[tokio::test] + #[ignore = "requires a disposable PostgreSQL database"] + async fn frozen_policy_persistence_postgres() { + let schema = super::super::test_postgres::TestSchema::create("frozen_policy").await; + exercise_frozen_policy_persistence(&schema.connect_store().await).await; + schema.drop_schema().await; + } + + #[test] + fn frozen_policy_rejects_mismatched_private_identity() { + let payload = StoredFrozenSandboxPolicy { + sandbox_id: "other".into(), + policy: None, + } + .encode_to_vec(); + assert!(decode_frozen_policy("expected", &payload).is_err()); + } +} diff --git a/crates/openshell-server/src/persistence/mod.rs b/crates/openshell-server/src/persistence/mod.rs index cb8ee48173..7ac333d833 100644 --- a/crates/openshell-server/src/persistence/mod.rs +++ b/crates/openshell-server/src/persistence/mod.rs @@ -4,6 +4,7 @@ //! Persistence layer for `OpenShell` Server. mod azure_workload_identity; +pub mod frozen_policy; mod image_activation; mod legacy_time_wire; pub mod lock_order; diff --git a/crates/openshell-server/src/persistence/postgres.rs b/crates/openshell-server/src/persistence/postgres.rs index b62144ae0d..b9cff4b57c 100644 --- a/crates/openshell-server/src/persistence/postgres.rs +++ b/crates/openshell-server/src/persistence/postgres.rs @@ -2033,6 +2033,23 @@ FOR UPDATE let sandbox_payload: Vec = row.get("payload"); let current_version: i64 = row.try_get("resource_version").unwrap_or(1); let current_version = current_version.max(1).cast_unsigned(); + // Locking the sandbox first serializes this check with first acceptance. + let frozen_payload: Option> = + sqlx::query_scalar("SELECT payload FROM objects WHERE object_type = $1 AND id = $2") + .bind(super::frozen_policy::FROZEN_POLICY_OBJECT_TYPE) + .bind(super::frozen_policy::frozen_policy_id(&write.sandbox_id)) + .fetch_optional(&mut *tx) + .await + .map_err(|error| map_db_error(&error))?; + if let Some(payload) = frozen_payload + && super::frozen_policy::decode_frozen_policy(&write.sandbox_id, &payload)? + .policy + .is_some() + { + return Err(PersistenceError::Conflict { + current_resource_version: Some(current_version), + }); + } let (mut sandbox, sandbox_changed) = project_policy_revision_onto_sandbox(write, &sandbox_payload, current_version)?; diff --git a/crates/openshell-server/src/persistence/sandbox_image.rs b/crates/openshell-server/src/persistence/sandbox_image.rs index 70877c4d52..233416a91f 100644 --- a/crates/openshell-server/src/persistence/sandbox_image.rs +++ b/crates/openshell-server/src/persistence/sandbox_image.rs @@ -371,9 +371,14 @@ ORDER BY id LIMIT $2", return Err(conflict(Some(resource_version(&sandbox)))); } let image_state_id = state_id(sandbox_id); + let frozen_policy_id = super::frozen_policy::frozen_policy_id(sandbox_id); for (object_type, id) in [ ("sandbox", sandbox_id), (IMAGE_STATE_OBJECT_TYPE, image_state_id.as_str()), + ( + super::frozen_policy::FROZEN_POLICY_OBJECT_TYPE, + frozen_policy_id.as_str(), + ), ] { match &mut tx { ImageTransaction::Sqlite(tx) => { diff --git a/crates/openshell-server/src/persistence/sqlite.rs b/crates/openshell-server/src/persistence/sqlite.rs index b98b65ce3d..6f930656da 100644 --- a/crates/openshell-server/src/persistence/sqlite.rs +++ b/crates/openshell-server/src/persistence/sqlite.rs @@ -1599,6 +1599,23 @@ WHERE "object_type" = 'sandbox' AND "id" = ?1 let sandbox_payload: Vec = row.get("payload"); let current_version: i64 = row.try_get("resource_version").unwrap_or(1); let current_version = current_version.max(1).cast_unsigned(); + // Locking the sandbox first serializes this check with first acceptance. + let frozen_payload: Option> = + sqlx::query_scalar("SELECT payload FROM objects WHERE object_type = ?1 AND id = ?2") + .bind(super::frozen_policy::FROZEN_POLICY_OBJECT_TYPE) + .bind(super::frozen_policy::frozen_policy_id(&write.sandbox_id)) + .fetch_optional(&mut *tx) + .await + .map_err(|error| map_db_error(&error))?; + if let Some(payload) = frozen_payload + && super::frozen_policy::decode_frozen_policy(&write.sandbox_id, &payload)? + .policy + .is_some() + { + return Err(PersistenceError::Conflict { + current_resource_version: Some(current_version), + }); + } let (mut sandbox, sandbox_changed) = project_policy_revision_onto_sandbox(write, &sandbox_payload, current_version)?; diff --git a/crates/openshell-server/src/provider_profile_sources.rs b/crates/openshell-server/src/provider_profile_sources.rs index 7fcf64c4d2..de4f7ab59d 100644 --- a/crates/openshell-server/src/provider_profile_sources.rs +++ b/crates/openshell-server/src/provider_profile_sources.rs @@ -559,6 +559,30 @@ impl ProviderProfileSources { })]) } + #[cfg(test)] + pub(crate) fn from_test_profiles_blocked( + profiles: Vec, + ) -> (Self, Arc) { + let gate = Arc::new(TestSnapshotGate::default()); + let source = BlockingProviderProfileSource { + inner: StaticProviderProfileSource { + snapshot: ProviderProfileSnapshot { + revision: profile_snapshot_revision(&profiles), + profiles: profiles + .into_iter() + .map(|profile| ScopedSnapshotProfile { + scope: ProfileScope::Static, + profile, + }) + .collect(), + }, + }, + first: std::sync::atomic::AtomicBool::new(true), + gate: Arc::clone(&gate), + }; + (Self::uncached(vec![Arc::new(source)]), gate) + } + /// A source-managed catalog composed with the user-managed source. /// /// Models the shape an operator gets from an interceptor-vended catalog: @@ -693,6 +717,82 @@ pub fn spawn_refresh(state: Arc) { } impl EffectiveProviderProfileCatalog { + /// Rebuild the profiles captured for a frozen sandbox without consulting + /// the live profile sources or store. + pub(crate) fn from_frozen_profiles(profiles: &[ProviderProfile]) -> Result { + let mut captured: BTreeMap<(String, String, String), ScopedSnapshotProfile> = + BTreeMap::new(); + for profile in profiles { + let scope = match profile.scope.as_str() { + "" => ProfileScope::Static, + "platform" => ProfileScope::Platform, + "workspace" => ProfileScope::Workspace, + _ => { + return Err(Status::failed_precondition(format!( + "frozen provider profile '{}' has invalid scope '{}'", + profile.id, profile.scope + ))); + } + }; + if profile.source.trim().is_empty() + || profile.source.trim() != profile.source + || (profile.source == USER_SOURCE_ID) == (scope == ProfileScope::Static) + { + return Err(Status::failed_precondition(format!( + "frozen provider profile '{}' has inconsistent source and scope", + profile.id + ))); + } + let id = normalize_profile_id(&profile.id).ok_or_else(|| { + Status::failed_precondition(format!( + "frozen provider profile '{}' has invalid id", + profile.id + )) + })?; + let key = (profile.source.clone(), profile.scope.clone(), id); + if let Some(existing) = captured.get(&key) { + if existing.profile != *profile { + return Err(Status::failed_precondition(format!( + "conflicting frozen provider profile '{}' in scope '{}'", + profile.id, profile.scope + ))); + } + continue; + } + captured.insert( + key, + ScopedSnapshotProfile { + scope, + profile: profile.clone(), + }, + ); + } + + let mut snapshots: BTreeMap = BTreeMap::new(); + for ((source_id, _, _), profile) in captured { + snapshots + .entry(source_id.clone()) + .or_insert_with(|| CollectedProviderProfileSnapshot { + user_managed: source_id == USER_SOURCE_ID, + source_id, + revision: String::new(), + profiles: Vec::new(), + allow_empty: true, + }) + .profiles + .push(profile); + } + for snapshot in snapshots.values_mut() { + let mut hasher = Sha256::new(); + hasher.update(b"openshell-frozen-provider-profile-source-v1"); + for profile in &snapshot.profiles { + hasher.update(canonical_provider_profile_bytes(&profile.profile)); + } + snapshot.revision = format!("sha256:{:x}", hasher.finalize()); + } + build_effective_profiles(snapshots.into_values().collect()) + } + pub(crate) fn revision(&self) -> &str { &self.revision } @@ -745,6 +845,15 @@ impl EffectiveProviderProfileCatalog { .map(|entry| entry.profile.clone()) } + pub(crate) fn get_profile_for_scope( + &self, + id: &str, + profile_workspace: &str, + ) -> Option { + self.scoped_type_profile_for_scope(id, profile_workspace) + .map(|entry| entry.response.clone()) + } + /// Resolve a profile by its exact normalized ID. /// /// Profiles are import-only, so a provider type names a profile the @@ -1141,6 +1250,75 @@ impl ProviderProfileSource for StaticProviderProfileSource { } } +/// Pause the source's first poll before `try_join` polls later database reads. +#[cfg(test)] +#[derive(Debug, Default)] +pub struct TestSnapshotGate { + entered: tokio::sync::Notify, + released: std::sync::Mutex, + wake: std::sync::Condvar, +} + +#[cfg(test)] +impl TestSnapshotGate { + pub(crate) async fn entered(&self) { + self.entered.notified().await; + } + pub(crate) fn release(&self) { + *self.released.lock().unwrap() = true; + self.wake.notify_all(); + } +} + +#[cfg(test)] +#[derive(Debug)] +struct BlockingProviderProfileSource { + inner: StaticProviderProfileSource, + first: std::sync::atomic::AtomicBool, + gate: Arc, +} + +#[cfg(test)] +#[async_trait] +impl ProviderProfileSource for BlockingProviderProfileSource { + fn source_id(&self) -> &'static str { + "blocking-test" + } + fn user_managed(&self) -> bool { + false + } + fn allow_empty(&self) -> bool { + false + } + async fn snapshot( + &self, + store: &Store, + workspace: &str, + ) -> Result { + if self.first.swap(false, std::sync::atomic::Ordering::SeqCst) { + let released = tokio::task::block_in_place(|| { + self.gate.entered.notify_one(); + let (released, _) = self + .gate + .wake + .wait_timeout_while( + self.gate.released.lock().unwrap(), + Duration::from_secs(20), + |released| !*released, + ) + .unwrap(); + *released + }); + if !released { + return Err(Status::deadline_exceeded( + "test profile source was not released", + )); + } + } + self.inner.snapshot(store, workspace).await + } +} + #[cfg(test)] #[derive(Debug)] struct SequencedProviderProfileSource { @@ -1455,6 +1633,92 @@ mod tests { ); } + #[test] + fn frozen_catalog_preserves_scoped_resolution_and_deduplicates_captures() { + let mut workspace_profile = profile("shared"); + workspace_profile.display_name = "Workspace override".to_string(); + let live = build_effective_profiles(vec![ + CollectedProviderProfileSnapshot { + source_id: USER_SOURCE_ID.to_string(), + revision: "user-revision".to_string(), + profiles: vec![ + scoped(ProfileScope::Platform, "shared"), + ScopedSnapshotProfile { + scope: ProfileScope::Workspace, + profile: workspace_profile, + }, + scoped(ProfileScope::Workspace, "workspace-only"), + ], + user_managed: true, + allow_empty: true, + }, + CollectedProviderProfileSnapshot { + source_id: "interceptor/governance".to_string(), + revision: "external-revision".to_string(), + profiles: vec![scoped(ProfileScope::Static, "managed")], + user_managed: false, + allow_empty: false, + }, + ]) + .unwrap(); + let mut captured = vec![ + live.get_profile_for_scope("shared", "").unwrap(), + live.get_profile_for_scope("shared", "default").unwrap(), + live.get_profile_for_scope("workspace-only", "default") + .unwrap(), + live.get_profile_for_scope("managed", "default").unwrap(), + ]; + captured.push(captured[0].clone()); + let frozen = EffectiveProviderProfileCatalog::from_frozen_profiles(&captured).unwrap(); + for (id, workspace) in [ + ("shared", ""), + ("shared", "default"), + ("workspace-only", ""), + ("workspace-only", "default"), + ("managed", ""), + ("managed", "default"), + ] { + assert_eq!( + frozen.get_profile_for_scope(id, workspace), + live.get_profile_for_scope(id, workspace), + "profile {id} in workspace '{workspace}'" + ); + } + captured.reverse(); + let reordered = EffectiveProviderProfileCatalog::from_frozen_profiles(&captured).unwrap(); + assert_eq!(frozen.revision(), reordered.revision()); + } + + #[test] + fn frozen_catalog_rejects_conflicting_or_invalid_captures() { + let mut first = profile("shared"); + first.source = USER_SOURCE_ID.to_string(); + first.scope = "platform".to_string(); + let mut conflicting = first.clone(); + conflicting.endpoints[0].host = "changed.example.com".to_string(); + let error = + EffectiveProviderProfileCatalog::from_frozen_profiles(&[first.clone(), conflicting]) + .unwrap_err(); + assert_eq!(error.code(), tonic::Code::FailedPrecondition); + assert!( + error + .message() + .contains("conflicting frozen provider profile") + ); + + for (source, scope) in [ + ("", "platform"), + (USER_SOURCE_ID, ""), + ("interceptor/governance", "workspace"), + (USER_SOURCE_ID, "unknown"), + ] { + let mut invalid = first.clone(); + invalid.source = source.to_string(); + invalid.scope = scope.to_string(); + assert!(EffectiveProviderProfileCatalog::from_frozen_profiles(&[invalid]).is_err()); + } + } + #[tokio::test] async fn captured_catalog_is_immutable_and_each_source_is_fetched_once() { let mut revision_a = profile("moving-profile"); diff --git a/crates/openshell-server/src/reflection.rs b/crates/openshell-server/src/reflection.rs index 463a937b1d..96d7cdb537 100644 --- a/crates/openshell-server/src/reflection.rs +++ b/crates/openshell-server/src/reflection.rs @@ -29,6 +29,7 @@ use crate::multiplex::GrpcRateLimiter; const REFLECTED_PROTO_ROOTS: &[&str] = &["openshell.proto"]; const ADVERTISED_SERVICES: &[&str] = &[ + "openshell.v1.FrozenSandboxPolicies", "openshell.v1.OpenShell", "openshell.v1.SandboxUpdates", "openshell.v1.ServiceDiscovery", diff --git a/crates/openshell-server/src/storage_proto.rs b/crates/openshell-server/src/storage_proto.rs index 4c452c7cf3..149eabbb0f 100644 --- a/crates/openshell-server/src/storage_proto.rs +++ b/crates/openshell-server/src/storage_proto.rs @@ -36,6 +36,11 @@ mod workspace_secret { } pub(crate) use workspace_secret::{StoredSecretRefreshUse, StoredWorkspaceSecret}; +mod frozen_policy { + include!(concat!(env!("OUT_DIR"), "/openshell.storage.frozen.v1.rs")); +} +pub(crate) use frozen_policy::StoredFrozenSandboxPolicy; + pub(crate) const STORAGE_FILE_DESCRIPTOR_SET: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/storage_descriptor.bin")); @@ -230,6 +235,13 @@ mod tests { // Cedar policies keep their current behavior. // SupervisorHello and GetSandboxConfigRequest negotiate Cedar support with // public-only capability fields; durable schemas remain unchanged. + // Frozen mode and first-accepted policy live in a separate private record; + // existing public SandboxSpec/Status and storage.v1 retain their source shape. + // The private snapshot holds no credential values or handles. The frozen + // create response repeats the two public-only application URL maps. + // Frozen reads add public-only messages: the captured providers whose + // credentials are withheld, with what changed, and a ListSandboxes + // counterpart that reports the freeze state of each listed sandbox. // Supervisor middleware binding policy and selectors are public-only. An // absent policy preserves dynamic discovery; older supervisors ignore both fields. // Suspend/resume adds two public request messages without durable request @@ -252,13 +264,13 @@ mod tests { // The service backend HTTP version is part of both schemas. Legacy // endpoint records omit it and continue to use HTTP/1.1. const PUBLIC_RPC_SCHEMA_SHA256: &str = - "edfc80ad192e77e1a9d1e1d6e3342280e4438f8bf7cb49969f580060df9a056a"; + "16d2845a4e71066b83a12c3789b9be11c009c855cb8fb2eca66c907373f60dc2"; // The storage.v2 refresh root adds retired handles and the first mint's // provider revision. All fields from the prior root retain their wire tags. const DURABLE_SCHEMA_SHA256: &str = - "ca31950286327bc385fae933bbb9e34d3c9191214f9b549c558bba40957fcc65"; + "aac3a31d0a92331f802bcef0ed33a6ec9ebecd72f51313a1491699381c3622dc"; const PUBLIC_DURABLE_OVERLAP_SHA256: &str = - "d0eead2cd403f6f52ecd9b7df73ca7db15e84dd847e11bc9d50469970204e589"; + "448f8d823f123ddf24c7a82e9adb567729bd39b9aa4127687992ba2135d3ea2c"; // Encoded with the schema that omitted stable_placeholder. Keep these // bytes fixed so the current encoder cannot hide a compatibility change. const LEGACY_STATIC_PROFILE: &str = "0a240a116c65676163792d70726f66696c652d6964120d6c65676163792d737461746963280712510a0d6c65676163792d73746174696312184c6567616379207374617469632063726564656e7469616c2a260a076170695f6b65791a1153594e5448455449435f4150495f4b455920012a06626561726572"; @@ -306,6 +318,13 @@ mod tests { const PEER_CONFIG_RPC_SIGNATURES: [&str; 1] = [ "openshell.v1.OpenShell/PeerNotifyConfigUpdate|.openshell.v1.PeerNotifyConfigUpdateRequest|.openshell.v1.PeerNotifyConfigUpdateResponse|false|false", ]; + const FROZEN_POLICY_RPC_SIGNATURES: &[&str] = &[ + "openshell.v1.FrozenSandboxPolicies/CreateSandbox|.openshell.v1.CreateFrozenSandboxRequest|.openshell.v1.FrozenSandboxResponse|false|false", + "openshell.v1.FrozenSandboxPolicies/GetPolicy|.openshell.v1.GetFrozenSandboxPolicyRequest|.openshell.v1.FrozenSandboxPolicyState|false|false", + "openshell.v1.FrozenSandboxPolicies/ListSandboxes|.openshell.v1.ListFrozenSandboxesRequest|.openshell.v1.ListFrozenSandboxesResponse|false|false", + "openshell.v1.FrozenSandboxPolicies/GetConfig|.openshell.v1.GetFrozenSandboxConfigRequest|.openshell.v1.FrozenSandboxConfigResponse|false|false", + "openshell.v1.FrozenSandboxPolicies/UpdateGlobalConfig|.openshell.v1.UpdateFrozenGlobalConfigRequest|.openshell.v1.UpdateFrozenGlobalConfigResponse|false|false", + ]; // Synthetic SandboxSpec bytes with log level, provider, and command fields, // emitted before the gateway-owned attachment epoch field was introduced. const PRE_READINESS_SANDBOX_SPEC: &str = @@ -321,6 +340,7 @@ mod tests { ".openshell.storage.v1.StoredProviderProfile", ".openshell.storage.image.v1.StoredSandboxImageState", ".openshell.storage.secret.v1.StoredWorkspaceSecret", + ".openshell.storage.frozen.v1.StoredFrozenSandboxPolicy", ".openshell.v1.Sandbox", ".openshell.v1.SandboxWorkloadTemplate", ".openshell.v1.ServiceEndpoint", @@ -686,7 +706,10 @@ mod tests { (package, service_name), ( "openshell.v1", - "OpenShell" | "SandboxUpdates" | "ServiceDiscovery" + "OpenShell" + | "SandboxUpdates" + | "ServiceDiscovery" + | "FrozenSandboxPolicies" ) | ("openshell.inference.v1", "Inference") ) { continue; @@ -744,6 +767,12 @@ mod tests { "peer config RPC is missing or changed: {signature}" ); } + for signature in FROZEN_POLICY_RPC_SIGNATURES { + assert!( + methods.iter().any(|method| method == signature), + "frozen policy RPC is missing or changed: {signature}" + ); + } assert_eq!( compiled_method_count, 124 + PROVIDER_READINESS_RPC_SIGNATURES.len() @@ -751,14 +780,16 @@ mod tests { + PEER_CONFIG_RPC_SIGNATURES.len() + isolation_methods.len() + sandbox_protocol_methods.len() - + supervisor_host_methods.len(), + + supervisor_host_methods.len() + + FROZEN_POLICY_RPC_SIGNATURES.len(), "classify every compiled RPC" ); assert_eq!( methods.len(), 91 + PROVIDER_READINESS_RPC_SIGNATURES.len() + PEER_OWNER_RPC_SIGNATURES.len() - + PEER_CONFIG_RPC_SIGNATURES.len(), + + PEER_CONFIG_RPC_SIGNATURES.len() + + FROZEN_POLICY_RPC_SIGNATURES.len(), "inventory every public gateway RPC" ); assert_eq!( @@ -817,9 +848,9 @@ mod tests { overlap_hash.as_str(), ), ( - (369, 32), - (104, 23), - (88, 23), + (391, 33), + (109, 23), + (92, 23), PUBLIC_RPC_SCHEMA_SHA256, DURABLE_SCHEMA_SHA256, PUBLIC_DURABLE_OVERLAP_SHA256 diff --git a/crates/openshell-server/src/test_support.rs b/crates/openshell-server/src/test_support.rs index 969e05928b..0dece18573 100644 --- a/crates/openshell-server/src/test_support.rs +++ b/crates/openshell-server/src/test_support.rs @@ -27,6 +27,13 @@ pub mod grpc { include!(concat!(env!("OUT_DIR"), "/test_grpc/openshell.v1.rs")); } +/// The reflection service a gateway serves, so a test gateway advertises the +/// services clients negotiate against. +pub fn reflection_service() -> crate::reflection::GatewayReflectionServer { + crate::reflection::build_gateway_reflection_service(&Config::new(None)) + .expect("gateway reflection descriptors decode") +} + use crate::ServerState; use crate::auth::identity::{Identity, IdentityProvider}; use crate::auth::principal::{Principal, UserPrincipal}; diff --git a/crates/openshell-supervisor/src/lib.rs b/crates/openshell-supervisor/src/lib.rs index 3ec4035113..9dd6b7d9d1 100644 --- a/crates/openshell-supervisor/src/lib.rs +++ b/crates/openshell-supervisor/src/lib.rs @@ -2376,6 +2376,55 @@ fn enrich_proto_baseline_paths(proto: &mut openshell_core::proto::SandboxPolicy) modified } +fn prepare_startup_baseline_paths( + policy: &mut openshell_core::proto::SandboxPolicy, + snapshot: &openshell_core::grpc_client::FrozenSettingsPollResult, +) -> Result { + // A Cedar-authored policy's Landlock grants come from the Cedar text, not + // `filesystem`, so its baseline paths are added after extraction in + // `prepare_startup_configuration` instead. + if policy.is_cedar() { + return Ok(false); + } + let immutable = snapshot.frozen + || (snapshot.frozen_requested + && snapshot.policy_source == openshell_core::proto::PolicySource::Global); + if !immutable { + return Ok(enrich_proto_baseline_paths(policy)); + } + if policy.network_policies.is_empty() { + return Ok(false); + } + let (read_only, read_write) = proxy_baseline_paths(); + let mut candidate = policy.clone(); + if !enrich_proto_baseline_paths_with(&mut candidate, &read_only, &read_write, |path| { + std::path::Path::new(path).exists() + }) { + return Ok(false); + } + let present = policy.filesystem.as_ref(); + let mut missing = candidate + .filesystem + .iter() + .flat_map(|fs| fs.read_only.iter().chain(&fs.read_write)) + .filter(|path| { + !present.is_some_and(|fs| fs.read_only.contains(path) || fs.read_write.contains(path)) + }) + .cloned() + .collect::>(); + missing.sort(); + missing.dedup(); + let recovery = if snapshot.frozen { + "the captured policy is incompatible with this runtime; delete and recreate the sandbox with an approved policy containing these paths" + } else { + "the global policy must include these paths before frozen initialization can be accepted; repair the global policy and retry" + }; + Err(miette::miette!( + "frozen policy is missing required proxy filesystem paths: {}; {recovery}", + missing.join(", ") + )) +} + fn strip_proto_provider_policy_entries(proto: &mut openshell_core::proto::SandboxPolicy) -> bool { openshell_policy::strip_provider_rule_names(proto) } @@ -2739,7 +2788,7 @@ trait StartupGateway: Send + Sync { fn snapshot( &self, sandbox: &str, - ) -> impl Future> + Send; + ) -> impl Future> + Send; fn provider( &self, id: &str, @@ -2749,7 +2798,7 @@ trait StartupGateway: Send + Sync { sandbox: &str, policy: &openshell_core::proto::SandboxPolicy, workspace: &str, - ) -> impl Future> + Send; + ) -> impl Future> + Send; fn report( &self, id: &str, @@ -2776,8 +2825,8 @@ impl StartupGateway for RemoteStartupGateway { async fn snapshot( &self, sandbox: &str, - ) -> Result { - openshell_core::grpc_client::fetch_settings_snapshot(self.gateway()?, sandbox).await + ) -> Result { + openshell_core::grpc_client::fetch_frozen_settings_snapshot(self.gateway()?, sandbox).await } async fn provider( &self, @@ -2790,8 +2839,8 @@ impl StartupGateway for RemoteStartupGateway { sandbox: &str, policy: &openshell_core::proto::SandboxPolicy, workspace: &str, - ) -> Result { - openshell_core::grpc_client::sync_policy_and_fetch_snapshot( + ) -> Result { + openshell_core::grpc_client::sync_policy_and_fetch_frozen_snapshot( self.gateway()?, sandbox, policy, @@ -3166,13 +3215,31 @@ async fn load_policy_with_gateway( // a sandbox-sourced policy is written back. The gateway refuses // every sandbox policy write while a global policy is active, so a // global policy keeps the added paths in this process only. - // A Cedar-authored policy's Landlock grants come from the Cedar - // text, not `filesystem`, so its baseline paths are added after - // extraction in `prepare_startup_configuration` instead. - let enriched = - !proto_policy.is_cedar() && enrich_proto_baseline_paths(&mut proto_policy); + let enriched = match prepare_startup_baseline_paths(&mut proto_policy, &snapshot) { + Ok(enriched) => enriched, + Err(error) => { + reject_startup_configuration( + gateway, + &mut rejection_log, + id, + &instance_id, + &snapshot, + &error.to_string(), + None, + ) + .await?; + if snapshot.frozen { + return Err(error); + } + reconciliation_attempts = 0; + continue; + } + }; let sync_policy = proto_sync_payload_for_enriched_policy(&proto_policy, enriched) - .filter(|_| snapshot.policy_source == openshell_core::proto::PolicySource::Sandbox); + .filter(|_| { + !snapshot.frozen + && snapshot.policy_source == openshell_core::proto::PolicySource::Sandbox + }); if let Some(sync_policy) = sync_policy { let synced = grpc_retry("Enriched policy synchronization", || { gateway.sync(sandbox, &sync_policy, &snapshot.workspace) @@ -5420,7 +5487,7 @@ network_policies: async fn snapshot( &self, _id: &str, - ) -> Result { + ) -> Result { if self.pending_snapshot { return std::future::pending().await; } @@ -5429,7 +5496,7 @@ network_policies: tonic::Status::new(code, "snapshot unavailable"), )); } - Ok(self.desired.lock().unwrap().clone()) + Ok(self.desired.lock().unwrap().clone().into()) } async fn provider( &self, @@ -5444,7 +5511,7 @@ network_policies: _sandbox: &str, _policy: &openshell_core::proto::SandboxPolicy, _workspace: &str, - ) -> Result { + ) -> Result { self.snapshot("").await } async fn report( @@ -5952,6 +6019,8 @@ network_policies: /// script rejection-report errors to exercise retries and fatal failures. #[derive(Clone)] struct WriteRefusingStartupGateway { + frozen: bool, + frozen_requested: bool, desired: Arc>, refusals: Arc>>, repair_after_refusal: Option, @@ -5963,9 +6032,13 @@ network_policies: async fn snapshot( &self, _sandbox: &str, - ) -> Result { + ) -> Result { self.calls.send(StartupCall::Snapshot).unwrap(); - Ok(self.desired.lock().unwrap().clone()) + Ok(openshell_core::grpc_client::FrozenSettingsPollResult { + snapshot: self.desired.lock().unwrap().clone(), + frozen: self.frozen, + frozen_requested: self.frozen_requested || self.frozen, + }) } async fn provider( &self, @@ -5980,7 +6053,7 @@ network_policies: _sandbox: &str, policy: &openshell_core::proto::SandboxPolicy, _workspace: &str, - ) -> Result { + ) -> Result { self.calls.send(StartupCall::Sync).unwrap(); let mut desired = self.desired.lock().unwrap(); // The gateway checks for a global policy before it validates the @@ -6011,7 +6084,11 @@ network_policies: version, openshell_core::proto::PolicySource::Sandbox, ); - Ok(desired.clone()) + Ok(openshell_core::grpc_client::FrozenSettingsPollResult { + snapshot: desired.clone(), + frozen: self.frozen, + frozen_requested: self.frozen_requested || self.frozen, + }) } async fn report( &self, @@ -6115,6 +6192,8 @@ network_policies: .collect(); let (calls, mut observed) = tokio::sync::mpsc::unbounded_channel(); let gateway = WriteRefusingStartupGateway { + frozen: false, + frozen_requested: false, desired: Arc::new(std::sync::Mutex::new(initial)), refusals: Arc::new(std::sync::Mutex::new(std::collections::VecDeque::from( refusals, @@ -6265,6 +6344,8 @@ network_policies: let diagnostic = format!("Gateway rejected the {write}: {}", refusal.message); let (calls, mut observed) = tokio::sync::mpsc::unbounded_channel(); let gateway = WriteRefusingStartupGateway { + frozen: false, + frozen_requested: false, desired: Arc::new(std::sync::Mutex::new(initial)), refusals: Arc::new(std::sync::Mutex::new(std::collections::VecDeque::from([ refusal, @@ -6377,6 +6458,8 @@ network_policies: let snapshot = unset_policy_snapshot(); let (calls, mut observed) = tokio::sync::mpsc::unbounded_channel(); let gateway = WriteRefusingStartupGateway { + frozen: false, + frozen_requested: false, desired: Arc::new(std::sync::Mutex::new(snapshot.clone())), refusals: Arc::default(), repair_after_refusal: None, @@ -6587,19 +6670,39 @@ network_policies: #[cfg(unix)] #[tokio::test(start_paused = true)] async fn startup_policy_write_refusal_global_policy_skips_baseline_write_back() { + for (source, frozen) in [ + (openshell_core::proto::PolicySource::Global, false), + (openshell_core::proto::PolicySource::Sandbox, true), + ] { + Box::pin(assert_fixed_policy_skips_baseline_write_back( + source, frozen, + )) + .await; + } + } + + async fn assert_fixed_policy_skips_baseline_write_back( + source: openshell_core::proto::PolicySource, + frozen: bool, + ) { use openshell_core::proto::{ConfigurationAdmissionState, PolicySource}; // The gateway serves a global policy that has network rules but lacks // the proxy baseline paths. It refuses every sandbox policy write while // that policy is active, so startup must add the paths locally and // install the policy without writing it back. - let mut global = - settings_poll_result(Some(proto_tcp_policy_fixture()), 1, PolicySource::Global); - global.global_policy_version = 1; + let mut initial = proto_tcp_policy_fixture(); + if frozen { + enrich_proto_baseline_paths(&mut initial); + } + let mut global = settings_poll_result(Some(initial), 1, source); + global.global_policy_version = u32::from(source == PolicySource::Global); let global_generation = report_generation(&global); let mut enriched = proto_tcp_policy_fixture(); assert!(enrich_proto_baseline_paths(&mut enriched)); let (calls, mut observed) = tokio::sync::mpsc::unbounded_channel(); let gateway = WriteRefusingStartupGateway { + frozen, + frozen_requested: frozen, desired: Arc::new(std::sync::Mutex::new(global)), refusals: Arc::default(), repair_after_refusal: None, @@ -6622,10 +6725,10 @@ network_policies: ), ) .await - .expect("startup must not wait for repair under a global policy") + .expect("startup must not wait for repair under a fixed policy") .unwrap_or_else(|error| { panic!( - "startup exited under a global policy: {}", + "startup exited under a fixed policy: {}", startup_error_chain(&error) ) }); @@ -6648,21 +6751,101 @@ network_policies: StartupCall::Snapshot, report(ConfigurationAdmissionState::Accepted), ], - "startup must not write a global policy back as a sandbox policy" + "startup must not write a fixed policy back as a sandbox policy" ); assert_eq!( bundle.proto, Some(enriched), - "startup installs the global policy with the baseline paths added" + "startup installs the fixed policy with the baseline paths added" ); let LoadedPolicyOrigin::Gateway { revision: Some(revision), .. } = bundle.origin else { - panic!("startup must bind the global policy to its gateway revision"); + panic!("startup must bind the fixed policy to its gateway revision"); }; - assert_eq!(revision.policy_source, PolicySource::Global); + assert_eq!(revision.policy_source, source); + } + + #[cfg(unix)] + #[tokio::test(start_paused = true)] + async fn frozen_startup_rejects_implicit_baseline_expansion() { + use openshell_core::proto::{ConfigurationAdmissionState, PolicySource}; + for captured in [false, true] { + let source = if captured { + PolicySource::Sandbox + } else { + PolicySource::Global + }; + let (calls, mut observed) = tokio::sync::mpsc::unbounded_channel(); + let gateway = WriteRefusingStartupGateway { + frozen: captured, + frozen_requested: true, + desired: Arc::new(std::sync::Mutex::new(settings_poll_result( + Some(proto_tcp_policy_fixture()), + 1, + source, + ))), + refusals: Arc::default(), + repair_after_refusal: None, + rejection_report_errors: Arc::default(), + calls, + }; + let extension_credentials = openshell_extension_core::ExtensionCredentialStore::new(); + let mut startup = Box::pin(load_policy_with_gateway( + Some("sandbox-id".into()), + Some("sandbox".into()), + Some(test_gateway()), + None, + None, + &extension_credentials, + LocalPolicyIdentity::Required, + None, + Some(ImagePolicyDiscovery::Missing), + &gateway, + )); + let mut trace = Vec::new(); + loop { + tokio::select! { + biased; + call = observed.recv() => { + let call = call.expect("startup records its rejection"); + let rejected = matches!(&call, StartupCall::Report(report) if report.state == ConfigurationAdmissionState::Rejected); + trace.push(call); + if rejected { break; } + } + result = &mut startup => panic!( + "startup completed before rejecting a frozen expansion: {}", + result.err().map_or_else(|| "accepted".to_string(), |error| error.to_string()) + ), + } + } + assert!(!trace.iter().any(|call| matches!( + call, + StartupCall::Sync + | StartupCall::Report(StartupReport { + state: ConfigurationAdmissionState::Accepted, + .. + }) + ))); + if captured { + let error = startup + .await + .err() + .expect("an incompatible captured policy cannot be repaired in place"); + assert!(error.to_string().contains("delete and recreate")); + } else { + let mut repaired = proto_tcp_policy_fixture(); + enrich_proto_baseline_paths(&mut repaired); + *gateway.desired.lock().unwrap() = + settings_poll_result(Some(repaired.clone()), 2, source); + let result = startup + .await + .expect("a baseline-complete global repair is accepted"); + assert_eq!(result.proto, Some(repaired)); + } + } } #[tokio::test(start_paused = true)] @@ -6693,6 +6876,8 @@ network_policies: ] { let (calls, mut observed) = tokio::sync::mpsc::unbounded_channel(); let gateway = WriteRefusingStartupGateway { + frozen: false, + frozen_requested: false, desired: Arc::new(std::sync::Mutex::new(initial.clone())), refusals: Arc::new(std::sync::Mutex::new(std::collections::VecDeque::from([ SyncRefusal::new(code, "sandbox caller cannot write this policy"), @@ -7520,6 +7705,25 @@ permit (principal, action == Sandbox::Action::"NetworkConnect", ); } + /// A Cedar policy's grants come from its text, so the frozen `filesystem` + /// check does not apply and startup neither rejects nor rewrites it. + #[test] + fn frozen_cedar_policy_skips_the_filesystem_baseline_check() { + let mut policy = cedar_proto_policy(CEDAR_RELOAD_POLICY); + let captured = policy.clone(); + let snapshot = openshell_core::grpc_client::FrozenSettingsPollResult { + snapshot: settings_poll_result( + Some(policy.clone()), + 1, + openshell_core::proto::PolicySource::Sandbox, + ), + frozen: true, + frozen_requested: true, + }; + assert!(!prepare_startup_baseline_paths(&mut policy, &snapshot).unwrap()); + assert_eq!(policy, captured); + } + #[cfg(feature = "experimental")] /// As YAML adds baseline paths only to a policy with network rules, a /// Cedar policy gets them only when it can permit `NetworkConnect`. @@ -8050,7 +8254,7 @@ permit (principal, action == Sandbox::Action::"NetworkConnect", assert_eq!(revision.version, 1); assert_eq!( snapshot.workspace, "beta", - "workspace must survive the snapshot so sync_policy_and_fetch_snapshot receives it" + "workspace must survive the snapshot so sync_policy_and_fetch_frozen_snapshot receives it" ); } #[test] diff --git a/crates/openshell-tui/src/app.rs b/crates/openshell-tui/src/app.rs index 8c18c8ccb4..0e45c9525f 100644 --- a/crates/openshell-tui/src/app.rs +++ b/crates/openshell-tui/src/app.rs @@ -8,6 +8,7 @@ use crossterm::event::{KeyCode, KeyEvent, KeyModifiers}; use indexmap::IndexMap; use openshell_bootstrap::GatewayMetadataSource; use openshell_core::auth::EdgeAuthInterceptor; +use openshell_core::proto::frozen_sandbox_policies_client::FrozenSandboxPoliciesClient; use openshell_core::proto::open_shell_client::OpenShellClient; use openshell_core::proto::setting_value; use openshell_core::settings::{self, SettingValueKind}; @@ -142,6 +143,15 @@ pub struct SettingEditState { pub error: Option, } +/// Freeze state of a sandbox created with `--frozen`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum SandboxFreeze { + /// Policy changes still apply until the sandbox accepts its configuration. + Pending, + /// Policy and provider changes are refused. + Frozen { policy_hash: String }, +} + // --------------------------------------------------------------------------- // Sandbox policy pane tab (Policy vs Settings) // --------------------------------------------------------------------------- @@ -606,6 +616,10 @@ pub struct App { pub endpoint: String, pub gateway_insecure: bool, pub client: OpenShellClient>, + /// The optional frozen-policy service on the same connection. `None` in + /// tests; an older gateway answers its calls with an error. + pub frozen_client: + Option>>, pub status_text: String, // Gateway list @@ -701,6 +715,9 @@ pub struct App { pub sandbox_policy_tab: SandboxPolicyTab, pub sandbox_policy_is_global: bool, pub sandbox_global_policy_version: u32, + /// `None` when the selected sandbox was not created frozen, or when the + /// gateway does not report freeze state. + pub sandbox_freeze: Option, pub sandbox_settings: Vec, pub sandbox_settings_selected: usize, pub sandbox_setting_edit: Option, @@ -999,6 +1016,7 @@ impl App { endpoint, gateway_insecure: false, client, + frozen_client: None, status_text: String::from("connecting..."), gateways: Vec::new(), gateway_selected: 0, @@ -1066,6 +1084,7 @@ impl App { sandbox_policy_tab: SandboxPolicyTab::Policy, sandbox_policy_is_global: false, sandbox_global_policy_version: 0, + sandbox_freeze: None, sandbox_settings: Vec::new(), sandbox_settings_selected: 0, sandbox_setting_edit: None, @@ -3582,6 +3601,7 @@ impl App { self.log_selection_anchor = None; self.confirm_delete = false; self.sandbox_policy = None; + self.sandbox_freeze = None; self.sandbox_providers_list.clear(); self.policy_lines.clear(); self.policy_scroll = 0; diff --git a/crates/openshell-tui/src/lib.rs b/crates/openshell-tui/src/lib.rs index c6464157a9..baad25565e 100644 --- a/crates/openshell-tui/src/lib.rs +++ b/crates/openshell-tui/src/lib.rs @@ -23,6 +23,7 @@ use miette::{IntoDiagnostic, Result}; use openshell_bootstrap::list_gateways_with_source; use openshell_core::auth::EdgeAuthInterceptor; use openshell_core::metadata::{ObjectId, ObjectLabels, ObjectName, ObjectWorkspace}; +use openshell_core::proto::frozen_sandbox_policies_client::FrozenSandboxPoliciesClient; use openshell_core::proto::open_shell_client::OpenShellClient; use openshell_core::proto::{SandboxPhase, SandboxRestartPolicy}; use openshell_core::ssh_handoff::{SshCleanup, SshTarget}; @@ -127,6 +128,8 @@ pub async fn run_with_gateway_insecure( // after our own enable_raw_mode() would conflict. let detected_theme = theme::detect(theme_mode); + let frozen_client = + FrozenSandboxPoliciesClient::with_interceptor(channel.clone(), interceptor.clone()); let client = OpenShellClient::with_interceptor(channel, interceptor); let mut app = App::new( client, @@ -135,6 +138,7 @@ pub async fn run_with_gateway_insecure( workspace.to_string(), detected_theme, ); + app.frozen_client = Some(frozen_client); app.gateway_insecure = gateway_insecure; enable_raw_mode().into_diagnostic()?; @@ -425,6 +429,10 @@ pub async fn run_with_gateway_insecure( // changes, and policy version bumps are reflected live. if app.screen == Screen::Sandbox { refresh_sandbox_policy(&mut app).await; + // A pending freeze becomes frozen without a policy change. + if app.sandbox_freeze == Some(app::SandboxFreeze::Pending) { + fetch_sandbox_freeze(&mut app).await; + } refresh_draft_chunks(&mut app).await; } } @@ -590,6 +598,10 @@ async fn handle_gateway_switch(app: &mut App, tx: mpsc::UnboundedSender) match connect_to_gateway(&name, &endpoint).await { Ok((channel, interceptor)) => { + app.frozen_client = Some(FrozenSandboxPoliciesClient::with_interceptor( + channel.clone(), + interceptor.clone(), + )); app.client = OpenShellClient::with_interceptor(channel, interceptor); app.gateway_name = name; app.endpoint = endpoint; @@ -964,11 +976,45 @@ async fn fetch_sandbox_detail(app: &mut App) { app.status_text = "sandbox policy request timed out".to_string(); } } + // A newly opened sandbox must not show the previous one's state. + app.sandbox_freeze = None; + fetch_sandbox_freeze(app).await; } app.policy_scroll = 0; } +/// Read the selected sandbox's freeze state for the detail pane. +/// +/// A gateway without the frozen-policy service answers with an error. An +/// error keeps the last known state, so a pending freeze keeps refreshing. +async fn fetch_sandbox_freeze(app: &mut App) { + let Some(name) = app.selected_sandbox_name().map(str::to_string) else { + return; + }; + let request = openshell_core::proto::GetFrozenSandboxPolicyRequest { + workspace_scope: Some(openshell_core::proto::workspace_selector( + app.selected_sandbox_workspace(), + )), + name, + }; + let Some(client) = app.frozen_client.as_mut() else { + return; + }; + if let Ok(Ok(response)) = + tokio::time::timeout(Duration::from_secs(5), client.get_policy(request)).await + { + let state = response.into_inner(); + app.sandbox_freeze = match (state.requested, state.policy) { + (false, _) => None, + (true, None) => Some(app::SandboxFreeze::Pending), + (true, Some(policy)) => Some(app::SandboxFreeze::Frozen { + policy_hash: policy.policy_hash, + }), + }; + } +} + // --------------------------------------------------------------------------- // Shell connect (suspend TUI, launch SSH, resume) // --------------------------------------------------------------------------- diff --git a/crates/openshell-tui/src/ui/sandbox_detail.rs b/crates/openshell-tui/src/ui/sandbox_detail.rs index 726e6d8124..104c5ae993 100644 --- a/crates/openshell-tui/src/ui/sandbox_detail.rs +++ b/crates/openshell-tui/src/ui/sandbox_detail.rs @@ -41,7 +41,8 @@ fn note_lines(app: &App, width: u16) -> Vec { /// Return the rows needed to render every metadata line without clipping. pub(super) fn required_height(app: &App, width: u16) -> u16 { - let policy_rows = u16::from(app.sandbox_policy_is_global); + let policy_rows = + u16::from(app.sandbox_policy_is_global) + u16::from(app.sandbox_freeze.is_some()); let action_rows = if app.confirm_delete { 2 // spacer plus confirmation } else { @@ -193,6 +194,22 @@ pub fn draw(frame: &mut Frame<'_>, app: &App, area: Rect) { ])); } + // A frozen policy refuses edits and approvals, so say so before the user + // tries one. A pending freeze still accepts them. + if let Some(freeze) = app.sandbox_freeze.as_ref() { + let label = match freeze { + crate::app::SandboxFreeze::Frozen { policy_hash } => format!( + "frozen ({}), recreate the sandbox to change it", + policy_hash.get(..12).unwrap_or(policy_hash) + ), + crate::app::SandboxFreeze::Pending => "pending freeze".to_string(), + }; + lines.push(Line::from(vec![ + Span::styled(" Freeze: ", t.muted), + Span::styled(label, t.status_warn), + ])); + } + // Show pending network rules prompt — but not when delete confirmation is // active, since it would push the confirmation off the bottom of the pane. if pending_count > 0 && !app.confirm_delete { diff --git a/docs/extensibility/gateway-interceptors.mdx b/docs/extensibility/gateway-interceptors.mdx index dcde57b708..025cbbca9e 100644 --- a/docs/extensibility/gateway-interceptors.mdx +++ b/docs/extensibility/gateway-interceptors.mdx @@ -107,6 +107,8 @@ Start with the invariant the interceptor must preserve, then identify every gate To gate sandbox activation, bind `validate` to `CreateSandbox`, `StartSandbox`, and `ResumeSandbox`. Bind `post_commit` to `StopSandbox` and `SuspendSandbox` to observe successful stop and suspend requests. +Frozen sandbox creation and the CLI's global policy changes use `openshell.v1.FrozenSandboxPolicies/CreateSandbox` and `openshell.v1.FrozenSandboxPolicies/UpdateGlobalConfig`. They carry the same operations and request fields as `CreateSandbox` and `UpdateConfig`. When an interceptor modifies or validates `CreateSandbox` or `UpdateConfig`, bind the matching frozen RPC too. Until you do, the gateway rejects that frozen RPC with `FAILED_PRECONDITION`, so a caller cannot use it to skip the gate. + The gateway maintains the canonical [interceptable route allowlist](https://github.com/ai-openshell/openshell/blob/main/crates/openshell-gateway-interceptors/src/routes.rs). Read the interceptor manifest and gateway startup diagnostics when selecting bindings. Unknown, streaming, read-only, and non-allowlisted RPCs cannot be intercepted. Choose a phase by intent: diff --git a/docs/how-it-works/gateways/authentication.mdx b/docs/how-it-works/gateways/authentication.mdx index aad6f769cc..43e01cc5c5 100644 --- a/docs/how-it-works/gateways/authentication.mdx +++ b/docs/how-it-works/gateways/authentication.mdx @@ -121,8 +121,11 @@ grpcurl \ : list ``` -Reflection advertises only `openshell.v1.OpenShell`. It does not advertise -internal driver, interceptor, or middleware services. +Reflection advertises the public gateway services: `openshell.v1.OpenShell`, +`openshell.v1.SandboxUpdates`, `openshell.v1.ServiceDiscovery`, and +`openshell.v1.FrozenSandboxPolicies`. Clients read this list to detect +frozen-policy support. It does not advertise internal driver, interceptor, or +middleware services. When the gateway gRPC rate limit is enabled, reflection uses a separate counter with the same request count and window. Opening the reflection RPC consumes one diff --git a/docs/how-it-works/policies/manage-policies.mdx b/docs/how-it-works/policies/manage-policies.mdx index d3d1c1a12f..1420bd2a05 100644 --- a/docs/how-it-works/policies/manage-policies.mdx +++ b/docs/how-it-works/policies/manage-policies.mdx @@ -52,6 +52,128 @@ openshell sandbox create --name my-sandbox Without either, the sandbox uses a policy from its image or the restrictive [default policy](/how-it-works/policies/default-policy). +## Freeze a Sandbox Policy + +Use `--frozen` to keep a sandbox's first accepted effective policy and provider +authorization until the sandbox is deleted. + +```shell +openshell sandbox create --name review-bot \ + --policy ./approved-policy.yaml --provider github --frozen --detach +``` + +The command returns once the sandbox is ready and prints the frozen policy +hash. It fails, and never falls back to an ordinary sandbox, when the gateway +does not support frozen policies or when the sandbox is ready but its policy did +not freeze. You cannot enable or disable freezing on an existing sandbox. + +### What Freezes + +The snapshot includes any global override and attached provider profiles and +authorization. Later global-policy or profile changes leave it unchanged, even +across restarts. Sandbox and image policies receive required proxy filesystem +paths before the snapshot is captured. A global policy must already include +those [baseline paths](/how-it-works/policies/default-policy#baseline-filesystem-paths); +otherwise initialization is rejected until you repair it. +An upgraded runtime that requires additional paths refuses to start a captured +policy. Review the required paths and recreate the sandbox instead of extending +its existing access. Cedar policies in development builds are the exception: +the runtime adds those paths at each start, and they are not part of the +snapshot. + +After the configuration is accepted, policy edits, proposal approvals, and +provider attach or detach fail with `sandbox '' is frozen; delete and +recreate it to change its policy or providers`. Agent policy proposals are off +for a frozen sandbox from creation, and enabling them on it is rejected. +Develop the policy on a sandbox that is not frozen, then create the frozen one +with it. + +### What Does Not Freeze + +- Everything, until the sandbox accepts its first configuration. While + `sandbox get` shows `pending freeze`, policy edits and provider attach or + detach still succeed and become part of what freezes. +- Credential values and tokens, which still rotate. Replacing a credential + with a different secret is delivered like a rotation. Freezing fixes + OpenShell's rules, not what a token can do upstream. +- The image, command, environment, labels, exposed services, and sandbox or + global settings, including logging settings. + +### Verify What Froze + +Read the state back before you rely on it: + +```shell +openshell sandbox get review-bot -o json > frozen.json +jq -e '.policy_state == "frozen"' frozen.json +jq -r '.frozen_policy.policy_hash' frozen.json +jq '.frozen_policy.providers' frozen.json +openshell sandbox get review-bot --policy-only > frozen-policy.yaml +``` + +`policy_state` is `pending` until the capture and `frozen` afterward; `frozen` +is `true` only afterward. `frozen-policy.yaml` is the effective policy: your +policy plus `_provider_*` network rules from attached providers and the +baseline filesystem paths. Compare it with the approved policy as data, since +OpenShell writes it in its own order. `frozen_policy.providers` lists each +captured provider's type, configuration, and profile for comparison with the +approved profiles. + +The hash identifies that effective policy. It is not a digest of your policy +file. The same image, policy, and provider profiles produce the same hash, so +record the hash and providers from a reviewed sandbox and compare later +sandboxes against them. + +Verify approved policy and profile artifacts in a trusted deployment step. +Freezing preserves the accepted policy; it does not verify approval or +provide a pre-launch approval gate. To enforce approval at creation, use a +[gateway interceptor](/extensibility/gateway-interceptors) and bind it to the +frozen create RPC as well as `CreateSandbox`. + +### Find Frozen Sandboxes + +```shell +openshell sandbox list --frozen --all-workspaces +``` + +The list shows `frozen` or `pending freeze` for each sandbox created with +`--frozen` and skips pages that have none. When it prints a next page token, +pass the token with `--page-token` to see the rest. `policy get ` also +marks a frozen policy, and a global policy change names the sandboxes that +keep theirs. + +### Recover a Frozen Sandbox + +Changing a provider's identity, type, profile scope, configuration, or +authorization withholds that provider's credentials from a frozen sandbox +without changing its policy. Token grants then fail with `configuration_error`. +`sandbox get` names each withheld provider and what changed. Restore the +type, profile scope, and configuration in `frozen_policy.providers` to resume +delivery. A replaced provider or a changed authorization needs a new sandbox. +Authorizing the provider again does not help: it is one of the changes that +withholds credentials. + +When a frozen sandbox cannot start, `sandbox get` shows the reason on its +`Configuration` line. Check the sandbox logs with `openshell logs ` for +the cause. A captured policy cannot be repaired, so recreate the sandbox. +While the freeze is pending under a global policy, a platform administrator +repairs that policy instead. + +Recreating starts a new sandbox. Copy the files you need first with +`openshell sandbox download`. + +### Gateway Versions and Clients + +Upgrade every gateway that shares the store before you create the first frozen +sandbox. An older gateway does not know about the freeze: it serves the live +policy, accepts policy changes, and reports no freeze state. Before a +downgrade, list the frozen sandboxes, following every next page token, and +delete them. + +The CLI and the Rust SDK create and inspect frozen sandboxes. The terminal UI +shows a sandbox's freeze state but creates only ordinary sandboxes. Other +clients can call the `openshell.v1.FrozenSandboxPolicies` gRPC service. + ## Ship a Policy in an Image To include a policy in a sandbox image, add it at `/etc/openshell/policy.yaml`: @@ -70,9 +192,9 @@ does not fall back to the default policy. A sandbox's policy has two views. The base policy is the policy you set for the sandbox. The effective policy is the base policy plus any rules that attached -providers add, and the sandbox enforces it once the latest revision loads. While -a global policy is active, both views show the global policy. `--base` shows the -base policy, and `--full` shows the effective policy: +providers add, and the sandbox enforces it once the latest revision loads. +While a global policy is active, non-frozen sandboxes show it in both views. +`--base` shows the base policy, and `--full` shows the effective policy: ```shell openshell policy get my-sandbox --base @@ -331,10 +453,10 @@ filesystem and process changes still apply. ## Apply a Global Policy -A gateway administrator can apply one policy to every sandbox on the gateway. -The global policy replaces each sandbox's policy and blocks sandbox policy -changes until you delete it. These commands require the platform administrator -role: +A gateway administrator can apply one policy across the gateway. Sandboxes with +a frozen policy keep their accepted snapshot. For other sandboxes, the global +policy replaces the sandbox policy and blocks sandbox policy changes until you +delete it. These commands require the platform administrator role: | Task | Command | |---|---| @@ -343,9 +465,10 @@ role: | View global policy history. | `openshell policy list --global` | | Remove the global policy and restore normal policy selection. | `openshell policy delete --global` | -The set and delete commands ask for confirmation, because each one changes the -network access of every sandbox on the gateway. Running sandboxes load a new -global policy at their next configuration check, within about 10 seconds. +The set and delete commands ask for confirmation and name the frozen sandboxes +that keep their policy. A sandbox that froze under a global policy keeps that +policy after you replace or delete it. Running sandboxes without a +frozen policy load a new global policy within about 10 seconds. `--wait` is not available for global policies, so test traffic in a sandbox to confirm a change. After you delete the global policy, `policy get --global` still shows the last one, with the status `Superseded`. Deleting the global diff --git a/docs/how-it-works/policies/overview.mdx b/docs/how-it-works/policies/overview.mdx index d5800bf0ac..57ef88cae7 100644 --- a/docs/how-it-works/policies/overview.mdx +++ b/docs/how-it-works/policies/overview.mdx @@ -33,10 +33,18 @@ specific time: | `network_middlewares` | Additional inspection, transformation, or blocking of traffic that network rules allow. | Sandbox network proxy. | While the sandbox runs. | Filesystem, Landlock, and process settings are fixed once the sandbox starts. -Network rules and middleware can change while it runs, as described in [How +Network rules and middleware can change while it runs, unless the sandbox was +created with `--frozen`, as described in [How Changes Take Effect](/how-it-works/policies/manage-policies#how-changes-take-effect). +A [frozen sandbox](/how-it-works/policies/manage-policies#freeze-a-sandbox-policy) +keeps its first accepted effective policy and provider authorization until it +is deleted, on gateways that support frozen policies. Later global-policy and +provider-profile changes apply to live sandboxes; frozen sandboxes retain their +captured policy. A provider that changes afterward loses credential delivery +to the frozen sandbox instead of gaining new access. + Network rules make up most of a typical policy. OpenShell denies every outbound connection from a sandbox unless a rule in `network_policies` allows it. Each rule lists the destinations it allows and the binaries that can reach them, and @@ -81,8 +89,9 @@ both views. ### Global Policy -A gateway administrator can apply one policy to every sandbox on the gateway. -The global policy replaces each sandbox's own policy rather than limiting it. +A gateway administrator can apply one policy across the gateway. The global +policy replaces a sandbox's own policy rather than limiting it. Frozen +sandboxes keep their accepted snapshot. While it is active, OpenShell blocks sandbox policy changes and proposal approvals, and suppresses provider-contributed network rules. Deleting the global policy restores normal policy selection and provider rules. Refer to diff --git a/docs/how-it-works/providers/profiles.mdx b/docs/how-it-works/providers/profiles.mdx index 9b083fe05e..a084136b70 100644 --- a/docs/how-it-works/providers/profiles.mdx +++ b/docs/how-it-works/providers/profiles.mdx @@ -876,7 +876,7 @@ Each failure has a code, a stage identifying the failed step, and a recovery act |---|---|---| | `provider_authorization_required` | Provider authorization is required, including a missing or expired stored subject credential. | `reauthorize` | | `workload_identity_rejected` | The workload identity was rejected. | `fix_configuration` | -| `configuration_error` | Provider, grant, or token-service configuration is invalid. | `fix_configuration` | +| `configuration_error` | Provider, grant, or token-service configuration is invalid, or the provider changed after a [frozen sandbox](/how-it-works/policies/manage-policies#recover-a-frozen-sandbox) captured it. | `fix_configuration` | | `timeout` | A grant step timed out. | `retry` | | `unavailable` | A service or connection was unavailable. | `retry` | | `unclassified` | No more specific cause is established. | `investigate` | diff --git a/docs/kubernetes/high-availability.mdx b/docs/kubernetes/high-availability.mdx index 5bf5ba2a30..7cd90d7d59 100644 --- a/docs/kubernetes/high-availability.mdx +++ b/docs/kubernetes/high-availability.mdx @@ -580,7 +580,12 @@ barrier does not replace the deployment activation checklist. Image intent and revision are not new public `SandboxStatus` fields. Do not downgrade while updates are pending or retained sandboxes require the -private revision protocol. SQLite supports one gateway process only. For a +private revision protocol. Frozen sandboxes add the same constraint: every +replica must support frozen policies before you create one, and an older +replica would serve a frozen sandbox its live policy. List them with +`openshell sandbox list --frozen --all-workspaces`, following every next page +token, and delete them before a downgrade. SQLite supports one +gateway process only. For a SQLite gateway, activation attests that the old process has stopped; a shared SQLite file is not an HA deployment. diff --git a/docs/sdk/api-errors.mdx b/docs/sdk/api-errors.mdx index 661c52d66b..a0cb438755 100644 --- a/docs/sdk/api-errors.mdx +++ b/docs/sdk/api-errors.mdx @@ -155,7 +155,7 @@ documented exception, and the CLI enables it by default. ## Durable request admission -Thirty-one user-callable unary RPCs accept an optional `request_id` in their protobuf requests. +Thirty-three user-callable unary RPCs accept an optional `request_id` in their protobuf requests. | Resource | RPCs | |---|---| @@ -167,9 +167,11 @@ Thirty-one user-callable unary RPCs accept an optional `request_id` in their pro | Provider | `CreateProvider`, `UpdateProvider`, `DeleteProvider`, `ConfigureProviderRefresh`, `DeleteProviderRefresh`, `RotateProviderCredential` | | Provider profile | `ImportProviderProfiles`, `UpdateProviderProfiles`, `DeleteProviderProfile` | | Policy and config | `UpdateConfig`, `ApproveDraftChunk`, `RejectDraftChunk`, `EditDraftChunk`, `UndoDraftChunk`, `ApproveAllDraftChunks`, `ClearDraftChunks` | +| Frozen policy | `FrozenSandboxPolicies.CreateSandbox`, `FrozenSandboxPolicies.UpdateGlobalConfig` | `UpdateSandbox` belongs to the separate `openshell.v1.SandboxUpdates` service -on the same authenticated gateway listener. The other RPCs above remain on +and the two frozen-policy RPCs to `openshell.v1.FrozenSandboxPolicies`, both on +the same authenticated gateway listener. The other RPCs above remain on `openshell.v1.OpenShell`. Use a nonzero, hyphenated UUID of exactly 36 characters. Uppercase and lowercase diff --git a/e2e/rust/Cargo.lock b/e2e/rust/Cargo.lock index 62e5d5a671..a468fc5e72 100644 --- a/e2e/rust/Cargo.lock +++ b/e2e/rust/Cargo.lock @@ -2381,6 +2381,7 @@ dependencies = [ "tonic", "tonic-prost", "tonic-prost-build", + "tonic-reflection", "tonic-types", "tracing", "url", @@ -4256,6 +4257,20 @@ dependencies = [ "tonic-build", ] +[[package]] +name = "tonic-reflection" +version = "0.14.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "acccd136a4bf19810a1fde9c74edc6129b42a66b44d0c1c8aaa67aeb49a146a7" +dependencies = [ + "prost", + "prost-types", + "tokio", + "tokio-stream", + "tonic", + "tonic-prost", +] + [[package]] name = "tonic-types" version = "0.14.6" diff --git a/examples/governance-interceptor/Cargo.lock b/examples/governance-interceptor/Cargo.lock index b7e925de56..80cf895d65 100644 --- a/examples/governance-interceptor/Cargo.lock +++ b/examples/governance-interceptor/Cargo.lock @@ -2020,6 +2020,7 @@ dependencies = [ "tonic", "tonic-prost", "tonic-prost-build", + "tonic-reflection", "tonic-types", "tracing", "url", @@ -3578,6 +3579,20 @@ dependencies = [ "tonic-build", ] +[[package]] +name = "tonic-reflection" +version = "0.14.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "acccd136a4bf19810a1fde9c74edc6129b42a66b44d0c1c8aaa67aeb49a146a7" +dependencies = [ + "prost", + "prost-types", + "tokio", + "tokio-stream", + "tonic", + "tonic-prost", +] + [[package]] name = "tonic-types" version = "0.14.6" diff --git a/examples/isolation-backend-v8/Cargo.lock b/examples/isolation-backend-v8/Cargo.lock index 86a0784a68..2f1857abb9 100644 --- a/examples/isolation-backend-v8/Cargo.lock +++ b/examples/isolation-backend-v8/Cargo.lock @@ -2349,6 +2349,7 @@ dependencies = [ "tonic", "tonic-prost", "tonic-prost-build", + "tonic-reflection", "tonic-types", "tracing", "url", @@ -4008,6 +4009,20 @@ dependencies = [ "tonic-build", ] +[[package]] +name = "tonic-reflection" +version = "0.14.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "acccd136a4bf19810a1fde9c74edc6129b42a66b44d0c1c8aaa67aeb49a146a7" +dependencies = [ + "prost", + "prost-types", + "tokio", + "tokio-stream", + "tonic", + "tonic-prost", +] + [[package]] name = "tonic-types" version = "0.14.6" diff --git a/examples/supervisor-middleware-content-guard/Cargo.lock b/examples/supervisor-middleware-content-guard/Cargo.lock index 6a855ad03c..d44a18a410 100644 --- a/examples/supervisor-middleware-content-guard/Cargo.lock +++ b/examples/supervisor-middleware-content-guard/Cargo.lock @@ -2168,6 +2168,7 @@ dependencies = [ "tonic", "tonic-prost", "tonic-prost-build", + "tonic-reflection", "tonic-types", "tracing", "url", @@ -3697,6 +3698,20 @@ dependencies = [ "tonic-build", ] +[[package]] +name = "tonic-reflection" +version = "0.14.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "acccd136a4bf19810a1fde9c74edc6129b42a66b44d0c1c8aaa67aeb49a146a7" +dependencies = [ + "prost", + "prost-types", + "tokio", + "tokio-stream", + "tonic", + "tonic-prost", +] + [[package]] name = "tonic-types" version = "0.14.6" diff --git a/proto/openshell.proto b/proto/openshell.proto index 4212445623..8d8125d44b 100644 --- a/proto/openshell.proto +++ b/proto/openshell.proto @@ -1014,6 +1014,207 @@ service SandboxUpdates { } } +// Opt-in frozen policy operations. Existing sandbox messages and the OpenShell +// service retain their source shape on the 0.1.x release train. +service FrozenSandboxPolicies { + // Atomically choose frozen mode when creating a sandbox, including from a template. + rpc CreateSandbox(CreateFrozenSandboxRequest) returns (FrozenSandboxResponse) { + option (openshell.options.v1.authorization) = { + auth_mode: "bearer" + scope: "sandbox:write" + audit: "create" + workspace_role: "user" + }; + } + // Read the creation mode and first-accepted snapshot. An absent policy is pending. + rpc GetPolicy(GetFrozenSandboxPolicyRequest) returns (FrozenSandboxPolicyState) { + option (openshell.options.v1.authorization) = { + auth_mode: "bearer" + scope: "sandbox:read" + workspace_role: "user" + }; + } + // List sandboxes as ListSandboxes does and report which ones chose frozen mode. + rpc ListSandboxes(ListFrozenSandboxesRequest) returns (ListFrozenSandboxesResponse) { + option (openshell.options.v1.authorization) = { + auth_mode: "bearer" + scope: "sandbox:read" + workspace_role: "user" + }; + } + // Runtime delivery includes an explicit captured-policy signal without extending + // the stable PolicySource enum. Uncaptured policies retain normal startup behavior. + rpc GetConfig(GetFrozenSandboxConfigRequest) returns (FrozenSandboxConfigResponse) { + option (openshell.options.v1.authorization) = { + auth_mode: "dual" + scope: "config:read" + workspace_role: "user" + }; + } + // Update gateway-global policy and report sandboxes retaining captured policy. + // global must be true; the ordinary UpdateConfig response remains unchanged. + rpc UpdateGlobalConfig(UpdateFrozenGlobalConfigRequest) + returns (UpdateFrozenGlobalConfigResponse) { + option (openshell.options.v1.authorization) = { + auth_mode: "bearer" + scope: "config:write" + audit: "update" + global_role: "platform_admin" + }; + } +} + +// Frozen mode is chosen at creation; it cannot be enabled or reset later. +message FrozenSandboxPolicyState { + bool requested = 1; + // Absent until the first successfully accepted configuration is captured. + FrozenSandboxPolicy policy = 2; + // Captured providers whose credentials the gateway withholds now, because + // the provider no longer matches the captured authorization. + repeated FrozenSandboxWithheldProvider withheld_providers = 3; +} + +// A captured provider that changed after the policy was frozen. +message FrozenSandboxWithheldProvider { + string provider = 1; + FrozenProviderChange change = 2; +} + +// What changed on a provider since a frozen sandbox captured it. Reverting a +// type, profile scope, or configuration change restores delivery. A replaced +// provider or a changed authorization needs a new sandbox. +enum FrozenProviderChange { + FROZEN_PROVIDER_CHANGE_UNSPECIFIED = 0; + // The provider was deleted, or deleted and created again under the same name. + FROZEN_PROVIDER_CHANGE_REPLACED = 1; + FROZEN_PROVIDER_CHANGE_TYPE = 2; + // The provider now resolves its profile from another scope. + FROZEN_PROVIDER_CHANGE_PROFILE_SCOPE = 3; + FROZEN_PROVIDER_CHANGE_CONFIG = 4; + // The provider was authorized again, or its refresh was added or removed. + FROZEN_PROVIDER_CHANGE_AUTHORIZATION = 5; +} + +message FrozenSandboxResponse { + Sandbox sandbox = 1; + FrozenSandboxPolicyState frozen_policy = 2; + // The same three service URL maps SandboxResponse returns for CreateSandbox. + map service_urls = 3; + map application_service_urls = 4; + map gateway_service_urls = 5; +} + +message FrozenSandboxConfigResponse { + openshell.sandbox.v1.GetSandboxConfigResponse config = 1; + // True only after the authoritative first-accepted snapshot was captured. + bool frozen = 2; + // Chosen at creation, including before the first configuration is accepted. + bool frozen_requested = 3; +} + +message UpdateFrozenGlobalConfigResponse { + UpdateConfigResponse update = 1; + // Workspace-qualified names that retain a captured policy. + repeated string frozen_sandboxes = 2; +} + +message CreateFrozenSandboxRequest { + // Workspace scope. Only a named workspace selection is accepted. + openshell.datamodel.v1.WorkspaceSelector workspace_scope = 7; + SandboxSpec spec = 1; + // Optional user-supplied sandbox name. When empty the server generates one. + string name = 2; + // Optional labels for the sandbox (key-value metadata). + map labels = 3; + // Optional annotations for the sandbox (non-selector metadata). Keys under + // the `internal.openshell.ai/` prefix are reserved for the gateway. + map annotations = 4; + // One-shot launch hint indicating that the creating client will attach to + // the canonical main process. The supervisor keeps the terminal transport + // alive until that attachment connects and closes naturally. + bool await_main_process_attachment = 5; + // Workspace-scoped SandboxWorkloadTemplate name to resolve at creation time. + string workload_template = 6; + // Optional nonzero UUID for durable at-most-once admission. Successful results + // can be replayed for 24 hours; see the API errors and retries reference. + string request_id = 8; + // HTTP services to expose when the sandbox is created. Endpoints are + // registered after the sandbox has been persisted and route only while the + // sandbox is ready. + repeated SandboxServiceExposure service_exposures = 9; +} + +message GetFrozenSandboxPolicyRequest { + // Workspace scope. Only a named workspace selection is accepted. + openshell.datamodel.v1.WorkspaceSelector workspace_scope = 2; + string name = 1; +} + +// Counterpart of ListSandboxesRequest with the same fields and paging rules. +message ListFrozenSandboxesRequest { + // Workspace scope. Named and all-workspaces selections are accepted. + openshell.datamodel.v1.WorkspaceSelector workspace_scope = 4; + // The maximum number of sandboxes to return. Zero uses 100. Values above + // 1000 are coerced to 1000; negative values are invalid. + int32 page_size = 1; + // Token from a previous response. All other request parameters except + // page_size must match the request that produced it. + string page_token = 2; + // Optional label selector for filtering (format: "key1=value1,key2=value2"). + string label_selector = 3; +} + +// ListSandboxesResponse plus the freeze state of the listed sandboxes. +message ListFrozenSandboxesResponse { + repeated Sandbox sandboxes = 1; + // Token for the next page. Empty when there are no subsequent pages. + string next_page_token = 2; + // One entry for each listed sandbox that chose frozen mode at creation. + repeated FrozenSandboxSummary frozen_sandboxes = 3; +} + +// Freeze state of one listed sandbox, without the captured policy body. +message FrozenSandboxSummary { + string workspace = 1; + string sandbox = 2; + // Absent while the freeze is pending. + optional string policy_hash = 3; + // Absent while the freeze is pending. + google.protobuf.Timestamp frozen_time = 4; +} + +message GetFrozenSandboxConfigRequest { + // Workspace scope. Select one named workspace; authenticated sandbox callers may omit it during bootstrap. + openshell.datamodel.v1.WorkspaceSelector workspace_scope = 3; + string name = 1; + // Policy capabilities of sandbox-authenticated callers receiving config. + repeated string supported_capabilities = 5; +} + +// Global-only counterpart of UpdateConfig. The mirrored sandbox-only fields +// retain familiar request mapping but must remain absent/empty; the gateway +// rejects them rather than silently ignoring a requested operation. +message UpdateFrozenGlobalConfigRequest { + // Must be omitted for this global operation. + openshell.datamodel.v1.WorkspaceSelector workspace_scope = 10; + openshell.sandbox.v1.SandboxPolicy policy = 2; + string setting_key = 3; + openshell.sandbox.v1.SettingValue setting_value = 4; + bool delete_setting = 5; + // Required to be true. + bool global = 6; + // Unsupported at global scope; must be empty. + repeated PolicyMergeOperation merge_operations = 7; + // Unsupported at global scope; must be zero. + uint64 expected_resource_version = 8; + // Unsupported at global scope; must be empty. + map annotations = 9; + // Unsupported at global scope; must be empty. + string sandbox = 1; + // Optional nonzero UUID for durable at-most-once admission. + string request_id = 11; +} + // IssueSandboxToken request. Empty body; identity is established by the // authentication credentials carried in the request headers (a projected // Kubernetes ServiceAccount JWT in the K8s driver path). @@ -1400,6 +1601,31 @@ message SandboxStatus { TokenGrantFailureObservation last_token_grant_failure = 17; } +// Non-secret policy and provider authorization captured by frozen creation. +message FrozenSandboxPolicy { + openshell.sandbox.v1.SandboxPolicy policy = 1; + uint32 version = 2; + string policy_hash = 3; + google.protobuf.Timestamp frozen_time = 4; + // Original selection before the policy became frozen. + openshell.sandbox.v1.PolicySource policy_source = 5; + uint32 global_policy_version = 6; + repeated FrozenSandboxProvider providers = 7; +} + +// Provider authorization only. Credential values and handles are never copied. +message FrozenSandboxProvider { + string provider = 1; + // Internal immutable identity prevents same-name provider replacement. + string provider_id = 2; + string type = 3; + string profile_workspace = 4; + map config = 5; + ProviderProfile profile = 6; + // Automatic token rotation preserves these epochs; reauthorization does not. + map refresh_authorization_epochs = 7; +} + // User-facing sandbox condition derived from platform or gateway observations. message SandboxCondition { reserved 5; diff --git a/skills/generate-sandbox-policy/SKILL.md b/skills/generate-sandbox-policy/SKILL.md index c36b244f71..84fa4cf293 100644 --- a/skills/generate-sandbox-policy/SKILL.md +++ b/skills/generate-sandbox-policy/SKILL.md @@ -13,6 +13,11 @@ This skill translates a user's plain-language policy intent into a valid sandbox The output is a `network_policies` YAML block, an optional `network_middlewares` block, and optionally a full policy file that conforms to the sandbox policy schema. +When the sandbox was created with `--frozen`, inspect its initialized state +before proposing a policy update. A frozen sandbox requires deletion and +recreation with the newly reviewed policy. Freeze is a creation option, not a +YAML policy field; credential values may rotate without changing authorization. + ## Step 1: Gather Inputs ### Determine the Detail Tier diff --git a/skills/openshell-cli/SKILL.md b/skills/openshell-cli/SKILL.md index c89ba151ea..00c3383adb 100644 --- a/skills/openshell-cli/SKILL.md +++ b/skills/openshell-cli/SKILL.md @@ -112,6 +112,19 @@ openshell sandbox create --from registry.example.com/your-org/claude-agent:lates openshell sandbox create --from registry.example.com/your-org/codex-agent:latest --provider codex -- codex ``` +For fixed access, add `--frozen` at creation. The first accepted effective policy +and provider authorization remain fixed until deletion; new policy requires +recreation. The create command prints the frozen hash and fails if the policy +did not freeze. Check `sandbox get` for `pending freeze` or `frozen`, and +`sandbox get -o json` for `policy_state`, the hash, and the captured +providers. `sandbox list --frozen` lists frozen sandboxes; follow each next +page token. Credential values +still rotate, and freezing does not limit what a credential can do upstream. +Do not try to repair a frozen sandbox with policy updates, proposal approvals, +provider attach/detach, or provider reauthorization. When `sandbox get` shows a +withheld provider, apply the repair it names or recreate the sandbox. +Settings, image, command, and environment are not frozen. + The agent will be prompted interactively if credentials are missing. ### Step 4: Exit and clean up @@ -349,6 +362,7 @@ Key flags: - `--provider`: Attach configured credential providers for API keys, tokens, and other secrets (repeatable) - `--policy`: Custom policy YAML (otherwise uses built-in default or `OPENSHELL_SANDBOX_POLICY` env var) +- `--frozen`: Keep the first accepted effective policy and provider authorization fixed until the sandbox is deleted; cannot be changed later - `--gpu [COUNT]`: Request the driver's default GPU selection or a specific GPU count - `--cpu`, `--memory`: Set per-sandbox compute sizing. Docker/Podman apply limits; Kubernetes applies matching requests and limits. - `--driver-config-json`: Pass experimental driver-specific sandbox configuration diff --git a/tests/suites/conformance/Cargo.lock b/tests/suites/conformance/Cargo.lock index 6ff1a5420d..6816fecf89 100644 --- a/tests/suites/conformance/Cargo.lock +++ b/tests/suites/conformance/Cargo.lock @@ -2361,6 +2361,7 @@ dependencies = [ "tonic", "tonic-prost", "tonic-prost-build", + "tonic-reflection", "tonic-types", "tracing", "url", @@ -4158,6 +4159,20 @@ dependencies = [ "tonic-build", ] +[[package]] +name = "tonic-reflection" +version = "0.14.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "acccd136a4bf19810a1fde9c74edc6129b42a66b44d0c1c8aaa67aeb49a146a7" +dependencies = [ + "prost", + "prost-types", + "tokio", + "tokio-stream", + "tonic", + "tonic-prost", +] + [[package]] name = "tonic-types" version = "0.14.6" diff --git a/tests/suites/continuity/Cargo.lock b/tests/suites/continuity/Cargo.lock index 7271dca1bf..e646172f39 100644 --- a/tests/suites/continuity/Cargo.lock +++ b/tests/suites/continuity/Cargo.lock @@ -2340,6 +2340,7 @@ dependencies = [ "tonic", "tonic-prost", "tonic-prost-build", + "tonic-reflection", "tonic-types", "tracing", "url", @@ -4127,6 +4128,20 @@ dependencies = [ "tonic-build", ] +[[package]] +name = "tonic-reflection" +version = "0.14.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "acccd136a4bf19810a1fde9c74edc6129b42a66b44d0c1c8aaa67aeb49a146a7" +dependencies = [ + "prost", + "prost-types", + "tokio", + "tokio-stream", + "tonic", + "tonic-prost", +] + [[package]] name = "tonic-types" version = "0.14.6" diff --git a/tests/suites/drivers/podman/Cargo.lock b/tests/suites/drivers/podman/Cargo.lock index 2e4145634f..839a956967 100644 --- a/tests/suites/drivers/podman/Cargo.lock +++ b/tests/suites/drivers/podman/Cargo.lock @@ -2341,6 +2341,7 @@ dependencies = [ "tonic", "tonic-prost", "tonic-prost-build", + "tonic-reflection", "tonic-types", "tracing", "url", @@ -4145,6 +4146,20 @@ dependencies = [ "tonic-build", ] +[[package]] +name = "tonic-reflection" +version = "0.14.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "acccd136a4bf19810a1fde9c74edc6129b42a66b44d0c1c8aaa67aeb49a146a7" +dependencies = [ + "prost", + "prost-types", + "tokio", + "tokio-stream", + "tonic", + "tonic-prost", +] + [[package]] name = "tonic-types" version = "0.14.6" diff --git a/tests/suites/features/Cargo.lock b/tests/suites/features/Cargo.lock index 3b9ce24d97..240882c826 100644 --- a/tests/suites/features/Cargo.lock +++ b/tests/suites/features/Cargo.lock @@ -2419,6 +2419,7 @@ dependencies = [ "tonic", "tonic-prost", "tonic-prost-build", + "tonic-reflection", "tonic-types", "tracing", "url", @@ -4246,6 +4247,20 @@ dependencies = [ "tonic-build", ] +[[package]] +name = "tonic-reflection" +version = "0.14.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "acccd136a4bf19810a1fde9c74edc6129b42a66b44d0c1c8aaa67aeb49a146a7" +dependencies = [ + "prost", + "prost-types", + "tokio", + "tokio-stream", + "tonic", + "tonic-prost", +] + [[package]] name = "tonic-types" version = "0.14.6" diff --git a/tests/support/Cargo.lock b/tests/support/Cargo.lock index b8fef4d8b7..aa9a7516b9 100644 --- a/tests/support/Cargo.lock +++ b/tests/support/Cargo.lock @@ -2366,6 +2366,7 @@ dependencies = [ "tonic", "tonic-prost", "tonic-prost-build", + "tonic-reflection", "tonic-types", "tracing", "url", @@ -4171,6 +4172,20 @@ dependencies = [ "tonic-build", ] +[[package]] +name = "tonic-reflection" +version = "0.14.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "acccd136a4bf19810a1fde9c74edc6129b42a66b44d0c1c8aaa67aeb49a146a7" +dependencies = [ + "prost", + "prost-types", + "tokio", + "tokio-stream", + "tonic", + "tonic-prost", +] + [[package]] name = "tonic-types" version = "0.14.6" diff --git a/tests/testkit/Cargo.lock b/tests/testkit/Cargo.lock index 25223d39e3..085095c62e 100644 --- a/tests/testkit/Cargo.lock +++ b/tests/testkit/Cargo.lock @@ -2332,6 +2332,7 @@ dependencies = [ "tonic", "tonic-prost", "tonic-prost-build", + "tonic-reflection", "tonic-types", "tracing", "url", @@ -4119,6 +4120,20 @@ dependencies = [ "tonic-build", ] +[[package]] +name = "tonic-reflection" +version = "0.14.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "acccd136a4bf19810a1fde9c74edc6129b42a66b44d0c1c8aaa67aeb49a146a7" +dependencies = [ + "prost", + "prost-types", + "tokio", + "tokio-stream", + "tonic", + "tonic-prost", +] + [[package]] name = "tonic-types" version = "0.14.6"