diff --git a/architecture/gateway.md b/architecture/gateway.md index c523e08045..ba325ccc2c 100644 --- a/architecture/gateway.md +++ b/architecture/gateway.md @@ -192,7 +192,7 @@ Supported auth modes: | Plaintext | Local development or a trusted reverse proxy boundary. | | Unauthenticated local users | Trusted Kubernetes dev or fully trusted proxy deployments only. | | Cloudflare JWT | Edge-authenticated deployments where Cloudflare Access supplies identity. | -| OIDC | Bearer-token auth for users, with browser or device-code PKCE and client credentials login. | +| OIDC | Bearer-token auth for users, with browser or device-code PKCE and client credentials login. JWKS validation accepts RS256, RS384, RS512, PS256, PS384, PS512, ES256, ES384, and EdDSA (Ed25519) signing keys. | The CLI persists the scopes requested during OIDC login in gateway metadata and reuses them when refreshing an access token. This preserves the intended API diff --git a/crates/openshell-cli/src/commands/mod.rs b/crates/openshell-cli/src/commands/mod.rs index 09ea2941a4..8d75cf5ae3 100644 --- a/crates/openshell-cli/src/commands/mod.rs +++ b/crates/openshell-cli/src/commands/mod.rs @@ -3,3 +3,4 @@ pub mod common; pub mod gateway; +pub mod provider; diff --git a/crates/openshell-cli/src/commands/provider.rs b/crates/openshell-cli/src/commands/provider.rs new file mode 100644 index 0000000000..c903156af0 --- /dev/null +++ b/crates/openshell-cli/src/commands/provider.rs @@ -0,0 +1,3021 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +use crate::color::Colorize; +use crate::commands::common::{ + format_epoch_ms, format_optional_epoch_ms, parse_credential_expiry_pairs, + parse_credential_pairs, parse_key_value_pairs, parse_secret_material_env_pairs, + truncate_display, truncate_status_field, +}; +use crate::tls::{TlsOptions, grpc_client}; +use dialoguer::Confirm; +use miette::{IntoDiagnostic, Result, WrapErr, miette}; +use openshell_core::proto::ProviderProfileCategory; +use openshell_core::proto::{ + AttachSandboxProviderRequest, ConfigureProviderRefreshRequest, CreateProviderRequest, + DeleteProviderProfileRequest, DeleteProviderRefreshRequest, DeleteProviderRequest, + DetachSandboxProviderRequest, GetProviderProfileRequest, GetProviderRefreshStatusRequest, + GetProviderRequest, GetSandboxRequest, ImportProviderProfilesRequest, + LintProviderProfilesRequest, ListProviderProfilesRequest, ListProvidersRequest, + ListSandboxProvidersRequest, Provider, ProviderCredentialRefreshRecoveryAction, + ProviderCredentialRefreshStatus, ProviderCredentialRefreshStrategy, + ProviderCredentialTokenGrantType, ProviderProfile, ProviderProfileDiagnostic, + ProviderProfileImportItem, RotateProviderCredentialRequest, UpdateProviderProfilesRequest, + UpdateProviderRequest, +}; +use openshell_core::{ObjectId, ObjectName, ObjectWorkspace}; +use openshell_providers::{ + ProviderTypeProfile, RealDiscoveryContext, detect_provider_from_command, discover_from_profile, + normalize_profile_id, normalize_provider_type, parse_profile_json, parse_profile_yaml, + profile_to_json, profile_to_yaml, profiles_to_json, profiles_to_yaml, +}; +use std::collections::{HashMap, HashSet}; +use std::io::IsTerminal; +use std::path::{Path, PathBuf}; +use tonic::{Code, Status}; + +fn aggregate_delete_failures(resource: &str, failures: &[String]) -> Result<()> { + if failures.is_empty() { + Ok(()) + } else { + Err(miette!( + "failed to delete {} {}{}: {}", + failures.len(), + resource, + if failures.len() == 1 { "" } else { "s" }, + failures.join(", ") + )) + } +} + +pub async fn sandbox_provider_list( + server: &str, + name: &str, + output: &str, + workspace: &str, + tls: &TlsOptions, +) -> Result<()> { + let mut client = grpc_client(server, tls).await?; + let response = client + .list_sandbox_providers(ListSandboxProvidersRequest { + sandbox_name: name.to_string(), + workspace: workspace.to_string(), + }) + .await + .into_diagnostic()?; + let providers = response.into_inner().providers; + + if crate::output::print_output_collection(output, &providers, attached_provider_to_json)? { + return Ok(()); + } + + if providers.is_empty() { + println!("No providers attached to sandbox {name}."); + return Ok(()); + } + + print_provider_attachment_table(&providers); + Ok(()) +} + +pub async fn sandbox_provider_attach( + server: &str, + name: &str, + provider: &str, + workspace: &str, + tls: &TlsOptions, +) -> Result<()> { + let mut client = grpc_client(server, tls).await?; + + // Fetch current sandbox to get resource_version for CAS + let sandbox = client + .get_sandbox(GetSandboxRequest { + name: name.to_string(), + workspace: workspace.to_string(), + }) + .await + .into_diagnostic()? + .into_inner() + .sandbox + .ok_or_else(|| miette::miette!("sandbox not found"))?; + + let resource_version = sandbox.metadata.as_ref().map_or(0, |m| m.resource_version); + + let response = match client + .attach_sandbox_provider(AttachSandboxProviderRequest { + sandbox_name: name.to_string(), + provider_name: provider.to_string(), + expected_resource_version: resource_version, + workspace: workspace.to_string(), + }) + .await + { + Ok(response) => response.into_inner(), + Err(status) if status.code() == Code::Aborted => { + return Err(miette::miette!( + "Failed to attach provider: sandbox was modified by another operation.\n\ + Please retry the command." + ) + .with_source_code(status.message().to_string())); + } + Err(e) => return Err(e).into_diagnostic(), + }; + + if response.attached { + println!( + "{} Attached provider {} to sandbox {}", + "✓".green().bold(), + provider, + name + ); + } else { + println!("Provider {provider} is already attached to sandbox {name}."); + } + Ok(()) +} + +pub async fn sandbox_provider_detach( + server: &str, + name: &str, + provider: &str, + workspace: &str, + tls: &TlsOptions, +) -> Result<()> { + let mut client = grpc_client(server, tls).await?; + + // Fetch current sandbox to get resource_version for CAS + let sandbox = client + .get_sandbox(GetSandboxRequest { + name: name.to_string(), + workspace: workspace.to_string(), + }) + .await + .into_diagnostic()? + .into_inner() + .sandbox + .ok_or_else(|| miette::miette!("sandbox not found"))?; + + let resource_version = sandbox.metadata.as_ref().map_or(0, |m| m.resource_version); + + let response = match client + .detach_sandbox_provider(DetachSandboxProviderRequest { + sandbox_name: name.to_string(), + provider_name: provider.to_string(), + expected_resource_version: resource_version, + workspace: workspace.to_string(), + }) + .await + { + Ok(response) => response.into_inner(), + Err(status) if status.code() == Code::Aborted => { + return Err(miette::miette!( + "Failed to detach provider: sandbox was modified by another operation.\n\ + Please retry the command." + ) + .with_source_code(status.message().to_string())); + } + Err(e) => return Err(e).into_diagnostic(), + }; + + if response.detached { + println!( + "{} Detached provider {} from sandbox {}", + "✓".green().bold(), + provider, + name + ); + } else { + println!("Provider {provider} was not attached to sandbox {name}."); + } + Ok(()) +} + +fn print_provider_attachment_table(providers: &[Provider]) { + print!("{}", format_provider_attachment_table(providers, true)); +} + +fn attached_provider_to_json(provider: &Provider) -> serde_json::Value { + let mut config_keys = provider.config.keys().cloned().collect::>(); + config_keys.sort(); + + serde_json::json!({ + "name": provider.object_name(), + "type": provider.r#type, + "credential_keys": provider_credential_keys(provider), + "config_keys": config_keys, + }) +} + +fn format_provider_attachment_table(providers: &[Provider], color: bool) -> String { + use std::fmt::Write as _; + + let name_width = providers + .iter() + .map(|provider| provider.object_name().len()) + .max() + .unwrap_or(4) + .max(4); + let type_width = providers + .iter() + .map(|provider| provider.r#type.len()) + .max() + .unwrap_or(4) + .max(4); + + let name_header = if color { + "NAME".bold().to_string() + } else { + "NAME".to_string() + }; + let type_header = if color { + "TYPE".bold().to_string() + } else { + "TYPE".to_string() + }; + let credential_keys_header = if color { + "CREDENTIAL_KEYS".bold().to_string() + } else { + "CREDENTIAL_KEYS".to_string() + }; + let config_keys_header = if color { + "CONFIG_KEYS".bold().to_string() + } else { + "CONFIG_KEYS".to_string() + }; + + let mut output = String::new(); + let _ = writeln!( + output, + "{name_header: Option { + detect_provider_from_command(command).map(str::to_string) +} + +/// Ensure all required providers exist. +/// +/// `explicit_names` are provider **names** supplied via `--provider`. They are +/// passed through directly; the server validates they exist at sandbox creation. +/// +/// `inferred_types` are provider **types** inferred from the trailing command +/// (e.g. `claude` -> type `"claude-code"`). These are resolved to provider names via +/// a type→name lookup, and missing types may be auto-created interactively. +/// +/// Returns a deduplicated list of provider **names** suitable for +/// `SandboxSpec.providers`. +pub async fn ensure_required_providers( + client: &mut crate::tls::GrpcClient, + explicit_names: &[String], + inferred_types: &[String], + auto_providers_override: Option, + workspace: &str, +) -> Result> { + if explicit_names.is_empty() && inferred_types.is_empty() { + return Ok(Vec::new()); + } + + let mut configured_names: Vec = Vec::new(); + let mut seen_names: HashSet = HashSet::new(); + + // ── Fetch all existing providers ───────────────────────────────────── + // Build both a name set (for explicit --provider lookups) and a + // type-to-name map (for inferred provider resolution). + let mut known_names: HashSet = HashSet::new(); + let mut type_to_name: HashMap = HashMap::new(); + { + let mut offset = 0_u32; + let limit = 100_u32; + loop { + let response = client + .list_providers(ListProvidersRequest { + limit, + offset, + workspace: workspace.to_string(), + all_workspaces: false, + }) + .await + .into_diagnostic()?; + let providers = response.into_inner().providers; + for provider in &providers { + known_names.insert(provider.object_name().to_string()); + if !provider.r#type.is_empty() { + let type_lower = provider.r#type.to_ascii_lowercase(); + type_to_name + .entry(type_lower) + .or_insert_with(|| provider.object_name().to_string()); + } + } + if providers.len() < limit as usize { + break; + } + offset = offset.saturating_add(limit); + } + } + + // ── Explicit provider names ────────────────────────────────────────── + // If the name exists on the server, use it directly. Otherwise, if the + // name matches a known provider type, auto-create a provider of that + // type with the requested name. + for name in explicit_names { + if known_names.contains(name) { + if seen_names.insert(name.clone()) { + configured_names.push(name.clone()); + } + } else { + let profile_id = name.trim(); + let profile = fetch_provider_profile(client, profile_id, workspace) + .await + .map_err(|_| { + miette::miette!( + "provider '{name}' not found and no provider profile named '{profile_id}' is available. \ + Create or import the profile first, then create the provider" + ) + })?; + let provider_type = profile.id; + auto_create_provider( + client, + &provider_type, + Some(name), + auto_providers_override, + &mut seen_names, + &mut configured_names, + workspace, + ) + .await?; + // Record the type mapping so the inferred-types pass below + // doesn't attempt to create a duplicate provider. + type_to_name + .entry(provider_type.to_ascii_lowercase()) + .or_insert_with(|| name.clone()); + } + } + + // ── Resolve inferred provider types ────────────────────────────────── + if !inferred_types.is_empty() { + // Collect resolved names for types that already have a provider. + for t in inferred_types { + if let Some(name) = type_to_name.get(&t.to_ascii_lowercase()) + && seen_names.insert(name.clone()) + { + configured_names.push(name.clone()); + } + } + + let missing = inferred_types + .iter() + .filter(|t| !type_to_name.contains_key(&t.to_ascii_lowercase())) + .cloned() + .collect::>(); + + for provider_type in missing { + auto_create_provider( + client, + &provider_type, + None, + auto_providers_override, + &mut seen_names, + &mut configured_names, + workspace, + ) + .await?; + } + } + + Ok(configured_names) +} + +/// Prompt for (or auto-confirm) creation of a provider from local credentials. +/// +/// When `preferred_name` is `Some`, the provider is created with that exact +/// name (used for explicit `--provider ` values). When `None`, the name +/// defaults to the type and retries with suffixes on conflict (used for +/// inferred provider types). +async fn auto_create_provider( + client: &mut crate::tls::GrpcClient, + provider_type: &str, + preferred_name: Option<&str>, + auto_providers_override: Option, + seen_names: &mut HashSet, + configured_names: &mut Vec, + workspace: &str, +) -> Result<()> { + eprintln!("Missing provider: {provider_type}"); + + // --no-auto-providers: skip silently. + if auto_providers_override == Some(false) { + eprintln!( + "{} Skipping provider '{provider_type}' (--no-auto-providers)", + "!".yellow(), + ); + eprintln!(); + return Ok(()); + } + + // No override and non-interactive: error. + if auto_providers_override.is_none() && !std::io::stdin().is_terminal() { + return Err(miette::miette!( + "missing required provider '{provider_type}'. Create it first with \ + `openshell provider create --type {provider_type} --name {provider_type} --from-existing`, \ + pass --auto-providers to auto-create, or set it up manually from inside the sandbox" + )); + } + + // --auto-providers: auto-confirm; otherwise prompt. + let should_create = if auto_providers_override == Some(true) { + true + } else { + Confirm::new() + .with_prompt("Create from local credentials?") + .default(true) + .interact() + .into_diagnostic()? + }; + + if !should_create { + eprintln!("{} Skipping provider '{provider_type}'", "!".yellow()); + eprintln!(); + return Ok(()); + } + + let profile = fetch_provider_profile(client, provider_type, workspace).await?; + let discovered = discover_existing_provider_data(client, provider_type, workspace) + .await + .map_err(|err| miette::miette!("failed to discover provider '{provider_type}': {err}"))?; + let discovered = match discovered { + Some(discovered) => discovered, + None if provider_profile_allows_empty_credentials(&profile) => { + openshell_providers::DiscoveredProvider::default() + } + None => { + return Err(miette::miette!( + "no existing local credentials found for provider profile '{provider_type}'. \ + Create it first with `openshell provider create --type {provider_type} --name {provider_type} --credential `" + )); + } + }; + + if let Some(exact_name) = preferred_name { + // Explicit name: create with exactly that name, no retries. + let request = CreateProviderRequest { + provider: Some(Provider { + metadata: Some(openshell_core::proto::datamodel::v1::ObjectMeta { + id: String::new(), + name: exact_name.to_string(), + created_at_ms: 0, + labels: HashMap::new(), + resource_version: 0, + annotations: HashMap::new(), + workspace: workspace.to_string(), + deletion_timestamp_ms: 0, + }), + r#type: provider_type.to_string(), + credentials: discovered.credentials.clone(), + config: discovered.config.clone(), + credential_expires_at_ms: HashMap::new(), + profile_workspace: workspace.to_string(), + credential_handles: HashMap::new(), + }), + workspace: workspace.to_string(), + }; + + let response = client.create_provider(request).await.map_err(|status| { + miette::miette!("failed to create provider '{exact_name}': {status}") + })?; + let provider = response + .into_inner() + .provider + .ok_or_else(|| miette::miette!("provider missing from response"))?; + eprintln!( + "{} Created provider {} ({}) from existing local state", + "✓".green().bold(), + provider.object_name(), + provider.r#type + ); + if seen_names.insert(provider.object_name().to_string()) { + configured_names.push(provider.object_name().to_string()); + } + } else { + // Inferred type: try type as name, then suffixed variants. + let mut created = false; + for attempt in 0..5 { + let name = if attempt == 0 { + provider_type.to_string() + } else { + format!("{provider_type}-{attempt}") + }; + + let request = CreateProviderRequest { + provider: Some(Provider { + metadata: Some(openshell_core::proto::datamodel::v1::ObjectMeta { + id: String::new(), + name: name.clone(), + created_at_ms: 0, + labels: HashMap::new(), + resource_version: 0, + annotations: HashMap::new(), + workspace: workspace.to_string(), + deletion_timestamp_ms: 0, + }), + r#type: provider_type.to_string(), + credentials: discovered.credentials.clone(), + config: discovered.config.clone(), + credential_expires_at_ms: HashMap::new(), + profile_workspace: workspace.to_string(), + credential_handles: HashMap::new(), + }), + workspace: workspace.to_string(), + }; + + match client.create_provider(request).await { + Ok(response) => { + let provider = response + .into_inner() + .provider + .ok_or_else(|| miette::miette!("provider missing from response"))?; + eprintln!( + "{} Created provider {} ({}) from existing local state", + "✓".green().bold(), + provider.object_name(), + provider.r#type + ); + if seen_names.insert(provider.object_name().to_string()) { + configured_names.push(provider.object_name().to_string()); + } + created = true; + break; + } + Err(status) if status.code() == Code::AlreadyExists => {} + Err(status) => { + return Err(miette::miette!( + "failed to create provider for type '{provider_type}': {status}" + )); + } + } + } + + if !created { + return Err(miette::miette!( + "failed to create provider for type '{provider_type}' after name retries" + )); + } + } + + eprintln!(); + Ok(()) +} + +fn read_gcloud_adc() -> Result<(String, String, String)> { + let path = if let Some(env_path) = std::env::var("GOOGLE_APPLICATION_CREDENTIALS") + .ok() + .filter(|v| !v.is_empty()) + { + PathBuf::from(env_path) + } else if let Some(config_dir) = std::env::var("CLOUDSDK_CONFIG") + .ok() + .filter(|v| !v.is_empty()) + { + PathBuf::from(config_dir).join("application_default_credentials.json") + } else { + let home = std::env::var("HOME") + .map_err(|_| miette::miette!("HOME is not set; cannot locate gcloud ADC file"))?; + PathBuf::from(home) + .join(".config") + .join("gcloud") + .join("application_default_credentials.json") + }; + + let content = std::fs::read_to_string(&path).map_err(|err| { + miette::miette!( + "failed to read gcloud ADC file at {}: {}. \ + Run: gcloud auth application-default login", + path.display(), + err + ) + })?; + + let json: serde_json::Value = serde_json::from_str(&content) + .map_err(|err| miette::miette!("failed to parse gcloud ADC file: {err}"))?; + + let cred_type = json.get("type").and_then(|v| v.as_str()); + match cred_type { + Some("service_account") => { + return Err(miette::miette!( + "Application Default Credentials are a service account key, not user credentials. \ + To use a service account, create the provider with the service account JSON key \ + and configure gateway-managed refresh for 'GOOGLE_VERTEX_AI_SERVICE_ACCOUNT_TOKEN'. \ + See: openshell provider create --help" + )); + } + Some("authorized_user") => {} + Some(other) => { + return Err(miette::miette!( + "Application Default Credentials have unsupported type '{other}' \ + (expected 'authorized_user'). \ + Run: gcloud auth application-default login" + )); + } + None => { + return Err(miette::miette!( + "gcloud ADC file is missing the 'type' field. \ + The file may be malformed. \ + Run: gcloud auth application-default login" + )); + } + } + + let client_id = json + .get("client_id") + .and_then(|v| v.as_str()) + .filter(|s| !s.is_empty()) + .ok_or_else(|| miette::miette!("gcloud ADC file is missing 'client_id'"))? + .to_string(); + + let client_secret = json + .get("client_secret") + .and_then(|v| v.as_str()) + .filter(|s| !s.is_empty()) + .ok_or_else(|| miette::miette!("gcloud ADC file is missing 'client_secret'"))? + .to_string(); + + let refresh_token = json + .get("refresh_token") + .and_then(|v| v.as_str()) + .filter(|s| !s.is_empty()) + .ok_or_else(|| miette::miette!("gcloud ADC file is missing 'refresh_token'"))? + .to_string(); + + Ok((client_id, client_secret, refresh_token)) +} + +async fn rollback_provider_create_after_gcloud_adc_failure( + client: &mut crate::tls::GrpcClient, + provider_name: &str, + stage: &str, + source: &Status, + workspace: &str, +) -> Result<()> { + match client + .delete_provider(DeleteProviderRequest { + name: provider_name.to_string(), + workspace: workspace.to_string(), + }) + .await + { + Ok(_) => Err(miette!( + "failed to {stage} credentials from gcloud ADC for provider '{provider_name}': {source}. \ + The provider was rolled back successfully." + )), + Err(cleanup_err) => { + eprintln!( + "{} Failed to clean up provider '{}' after {} failed: {}. \ + Run 'openshell provider delete {}' to remove it manually.", + "⚠".yellow(), + provider_name, + stage, + cleanup_err, + provider_name + ); + Err(miette!( + "failed to {stage} credentials from gcloud ADC for provider '{provider_name}': {source}. \ + Cleanup also failed, so the provider may still exist. \ + Run 'openshell provider delete {provider_name}' to remove it manually." + )) + } + } +} + +async fn fetch_provider_profile( + client: &mut crate::tls::GrpcClient, + provider_type: &str, + workspace: &str, +) -> Result { + let requested = provider_type.trim(); + let response = match fetch_provider_profile_exact(client, requested, workspace).await { + Ok(response) => response, + Err(status) if status.code() == Code::NotFound => { + let Some(alias) = normalize_provider_type(requested) + .filter(|alias| normalize_profile_id(requested).as_deref() != Some(*alias)) + else { + return Err(miette::miette!( + "provider profile '{requested}' not found; import a matching profile before using this provider type" + )); + }; + fetch_provider_profile_exact(client, alias, workspace) + .await + .map_err(|fallback_status| { + if fallback_status.code() == Code::NotFound { + miette::miette!( + "provider profile '{requested}' not found; import a matching profile before using this provider type" + ) + } else { + miette::miette!(fallback_status.to_string()) + } + })? + } + Err(status) => return Err(miette::miette!(status.to_string())), + }; + + Ok(response) +} + +async fn fetch_provider_profile_exact( + client: &mut crate::tls::GrpcClient, + provider_type: &str, + workspace: &str, +) -> std::result::Result { + client + .get_provider_profile(GetProviderProfileRequest { + id: provider_type.to_string(), + workspace: workspace.to_string(), + }) + .await + .and_then(|response| { + response + .into_inner() + .profile + .ok_or_else(|| Status::internal("provider profile missing from response")) + }) +} + +async fn discover_existing_provider_data( + client: &mut crate::tls::GrpcClient, + provider_type: &str, + workspace: &str, +) -> Result> { + let profile = fetch_provider_profile(client, provider_type, workspace).await?; + let profile = ProviderTypeProfile::from_proto(&profile); + let discovered = discover_from_profile(&profile, &RealDiscoveryContext).map_err(|err| { + miette::miette!("failed to discover existing provider data from profile: {err}") + })?; + + Ok(discovered) +} + +/// Canonical provider type string for Google Vertex AI. +const VERTEX_AI_PROVIDER_TYPE: &str = "google-vertex-ai"; + +/// Canonical provider type string for Google Cloud (GCP APIs). +const GOOGLE_CLOUD_PROVIDER_TYPE: &str = "google-cloud"; + +fn missing_credentials_error(provider_type: &str) -> miette::Report { + if provider_type == VERTEX_AI_PROVIDER_TYPE { + return miette::miette!( + "no credentials resolved for provider type '{provider_type}'. \ + Set GOOGLE_VERTEX_AI_TOKEN, VERTEX_AI_TOKEN, \ + GOOGLE_VERTEX_AI_SERVICE_ACCOUNT_TOKEN, or VERTEX_AI_SERVICE_ACCOUNT_TOKEN; \ + or use --from-gcloud-adc or --from-existing with those env vars set." + ); + } + + if provider_type == GOOGLE_CLOUD_PROVIDER_TYPE { + return miette::miette!( + "no credentials resolved for provider type '{provider_type}'. \ + Set GCP_ADC_ACCESS_TOKEN or GCP_SA_ACCESS_TOKEN; \ + or use --from-gcloud-adc / --from-existing with those env vars set." + ); + } + + miette::miette!( + "no credentials resolved for provider type '{provider_type}'. \ + Use --credential KEY[=VALUE], --runtime-credentials for runtime-resolved profile credentials, or --from-existing \ + with the appropriate env vars set." + ) +} + +async fn provider_credential_from_oidc_token( + credentials: &[String], + profile: Option<&ProviderProfile>, + tls: &TlsOptions, +) -> Result<(HashMap, HashMap)> { + let credential_key = oidc_subject_credential_key(credentials, profile)?; + + let gateway_name = tls.gateway_name().ok_or_else(|| { + miette::miette!("--from-oidc-token requires an active named OIDC gateway") + })?; + let bundle = + crate::oidc_auth::ensure_valid_oidc_token_bundle(gateway_name, tls.gateway_insecure) + .await + .map_err(|err| { + miette::miette!( + "failed to load or refresh OIDC token for gateway '{gateway_name}' while preparing provider credential: {err}" + ) + })?; + + let mut credential_map = HashMap::new(); + credential_map.insert(credential_key.clone(), bundle.access_token); + + let mut credential_expires_at_ms = HashMap::new(); + if let Some(expires_at) = bundle.expires_at { + let expires_at_ms = i64::try_from(expires_at) + .unwrap_or(i64::MAX / 1000) + .saturating_mul(1000); + credential_expires_at_ms.insert(credential_key, expires_at_ms); + } + + Ok((credential_map, credential_expires_at_ms)) +} + +fn oidc_subject_credential_key( + credentials: &[String], + profile: Option<&ProviderProfile>, +) -> Result { + if credentials.len() > 1 { + return Err(miette::miette!( + "--from-oidc-token accepts at most one --credential KEY destination" + )); + } + + if let Some(credential) = credentials.first() { + let credential = credential.trim(); + if credential.is_empty() || credential.contains('=') { + return Err(miette::miette!( + "--from-oidc-token requires --credential KEY without an inline value" + )); + } + if let Some(profile) = profile { + ensure_profile_declares_subject_credential(profile, credential)?; + } + return Ok(credential.to_string()); + } + + let Some(profile) = profile else { + return Err(miette::miette!( + "--from-oidc-token requires --credential KEY when the provider profile is unavailable" + )); + }; + + infer_oidc_subject_credential_from_profile(profile) +} + +fn ensure_profile_declares_subject_credential( + profile: &ProviderProfile, + credential: &str, +) -> Result<()> { + let matches = token_exchange_subject_credentials(profile); + if matches.iter().any(|candidate| candidate == credential) { + return Ok(()); + } + Err(miette::miette!( + "credential '{credential}' is not declared as a token-exchange subject credential in provider profile '{}'; expected one of: {}", + profile.id, + matches.join(", ") + )) +} + +fn infer_oidc_subject_credential_from_profile(profile: &ProviderProfile) -> Result { + let matches = token_exchange_subject_credentials(profile); + match matches.as_slice() { + [credential] => Ok(credential.clone()), + [] => Err(miette::miette!( + "provider profile '{}' does not declare a token-exchange subject credential; pass --credential KEY", + profile.id + )), + _ => Err(miette::miette!( + "provider profile '{}' declares multiple token-exchange subject credentials ({}); pass --credential KEY", + profile.id, + matches.join(", ") + )), + } +} + +fn token_exchange_subject_credentials(profile: &ProviderProfile) -> Vec { + let mut matches = Vec::new(); + for credential in &profile.credentials { + let Some(token_grant) = credential.token_grant.as_ref() else { + continue; + }; + if ProviderCredentialTokenGrantType::try_from(token_grant.grant_type).ok() + != Some(ProviderCredentialTokenGrantType::TokenExchange) + { + continue; + } + let Some(subject_token) = token_grant.subject_token.as_ref() else { + continue; + }; + if subject_token.source != "provider_credential" || subject_token.credential.is_empty() { + continue; + } + if !matches.contains(&subject_token.credential) { + matches.push(subject_token.credential.clone()); + } + } + matches +} + +#[allow(clippy::too_many_arguments)] +pub async fn provider_create( + server: &str, + name: &str, + provider_type: &str, + from_existing: bool, + credentials: &[String], + from_gcloud_adc: bool, + config: &[String], + workspace: &str, + tls: &TlsOptions, +) -> Result<()> { + let credential_source = match (from_existing, from_gcloud_adc) { + (true, true) => { + return Err(miette::miette!( + "--from-gcloud-adc cannot be combined with --from-existing, --from-oidc-token, or --credential; it also cannot be combined with --runtime-credentials" + )); + } + (true, false) => ProviderCreateCredentialSource::Existing, + (false, true) => ProviderCreateCredentialSource::GcloudAdc, + (false, false) => ProviderCreateCredentialSource::ExplicitCredentials, + }; + provider_create_with_options(ProviderCreateOptions { + server, + name, + provider_type, + credentials, + credential_source, + config, + workspace, + profile_workspace: workspace, + tls, + }) + .await +} + +pub struct ProviderCreateOptions<'a> { + pub server: &'a str, + pub name: &'a str, + pub provider_type: &'a str, + pub credentials: &'a [String], + pub credential_source: ProviderCreateCredentialSource, + pub config: &'a [String], + pub workspace: &'a str, + pub profile_workspace: &'a str, + pub tls: &'a TlsOptions, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum ProviderCreateCredentialSource { + ExplicitCredentials, + Existing, + GcloudAdc, + OidcToken, + Runtime, +} + +pub async fn provider_create_with_options(options: ProviderCreateOptions<'_>) -> Result<()> { + let ProviderCreateOptions { + server, + name, + provider_type, + credentials, + credential_source, + config, + workspace, + profile_workspace, + tls, + } = options; + + let from_existing = credential_source == ProviderCreateCredentialSource::Existing; + let from_gcloud_adc = credential_source == ProviderCreateCredentialSource::GcloudAdc; + let from_oidc_token = credential_source == ProviderCreateCredentialSource::OidcToken; + let runtime_credentials = credential_source == ProviderCreateCredentialSource::Runtime; + + if from_gcloud_adc && !credentials.is_empty() { + return Err(miette::miette!( + "--from-gcloud-adc cannot be combined with --from-existing, --from-oidc-token, or --credential; it also cannot be combined with --runtime-credentials" + )); + } + if from_existing && !credentials.is_empty() { + return Err(miette::miette!( + "--from-existing cannot be combined with --credential" + )); + } + if runtime_credentials && !credentials.is_empty() { + return Err(miette::miette!( + "--runtime-credentials cannot be combined with --credential" + )); + } + + let mut client = grpc_client(server, tls).await?; + + let profile_id = provider_type.trim(); + if profile_id.is_empty() { + return Err(miette::miette!("provider type is required")); + } + let provider_profile = fetch_provider_profile(&mut client, profile_id, profile_workspace) + .await + .map_err(|err| { + miette::miette!("unsupported provider type or profile: {profile_id} ({err})") + })?; + let provider_type = provider_profile.id.clone(); + + let adc_credential_key = if from_gcloud_adc { + let profile = ProviderTypeProfile::from_proto(&provider_profile); + let adc_cred = profile.adc_credential().ok_or_else(|| { + miette::miette!( + "--from-gcloud-adc is not supported for '{provider_type}' providers \ + (no ADC-compatible credential in the provider profile)" + ) + })?; + Some( + adc_cred + .env_vars + .first() + .ok_or_else(|| { + miette::miette!( + "ADC credential in '{provider_type}' profile has no env_vars declared" + ) + })? + .clone(), + ) + } else { + None + }; + + let oidc_profile = if from_oidc_token { + Some(provider_profile.clone()) + } else { + None + }; + + let (mut credential_map, oidc_credential_expires_at_ms) = if from_oidc_token { + provider_credential_from_oidc_token(credentials, oidc_profile.as_ref(), tls).await? + } else { + (parse_credential_pairs(credentials)?, HashMap::new()) + }; + let mut config_map = parse_key_value_pairs(config, "--config")?; + + if from_existing { + let discovered = + discover_existing_provider_data(&mut client, &provider_type, profile_workspace).await?; + let Some(discovered) = discovered else { + return Err(miette::miette!( + "no existing local credentials/config found for provider type '{provider_type}'" + )); + }; + + for (key, value) in discovered.credentials { + credential_map.entry(key).or_insert(value); + } + for (key, value) in discovered.config { + config_map.entry(key).or_insert(value); + } + } + + if credential_map.is_empty() { + if from_existing { + return Err(missing_credentials_error(&provider_type)); + } + if runtime_credentials && !provider_profile_allows_runtime_credentials(&provider_profile) { + return Err(miette::miette!( + "--runtime-credentials is only valid for provider profiles whose required credentials are resolved at runtime" + )); + } + if !provider_profile_allows_empty_credentials(&provider_profile) { + return Err(missing_credentials_error(&provider_type)); + } + } + + // Validate and read the ADC file BEFORE creating the provider so that + // a bad/missing ADC does not leave an orphan provider behind. Bundle the + // credential key with the material so they stay coupled. + let gcloud_adc_bootstrap = if from_gcloud_adc { + let (client_id, client_secret, refresh_token) = read_gcloud_adc()?; + let key = adc_credential_key.expect("set when from_gcloud_adc is true"); + Some((key, client_id, client_secret, refresh_token)) + } else { + None + }; + + let response = client + .create_provider(CreateProviderRequest { + provider: Some(Provider { + metadata: Some(openshell_core::proto::datamodel::v1::ObjectMeta { + id: String::new(), + name: name.to_string(), + created_at_ms: 0, + labels: HashMap::new(), + resource_version: 0, + annotations: HashMap::new(), + workspace: workspace.to_string(), + deletion_timestamp_ms: 0, + }), + r#type: provider_type.clone(), + credentials: credential_map, + config: config_map, + credential_expires_at_ms: oidc_credential_expires_at_ms, + profile_workspace: profile_workspace.to_string(), + credential_handles: HashMap::new(), + }), + workspace: workspace.to_string(), + }) + .await + .into_diagnostic()?; + + let provider = response + .into_inner() + .provider + .ok_or_else(|| miette::miette!("provider missing from response"))?; + let provider_name = provider.object_name().to_string(); + + if let Some((adc_credential_key, client_id, client_secret, refresh_token)) = + gcloud_adc_bootstrap + { + let mut material = HashMap::new(); + material.insert("client_id".to_string(), client_id); + material.insert("client_secret".to_string(), client_secret); + material.insert("refresh_token".to_string(), refresh_token); + + if let Err(configure_err) = client + .configure_provider_refresh(ConfigureProviderRefreshRequest { + provider: provider_name.clone(), + credential_key: adc_credential_key.clone(), + strategy: ProviderCredentialRefreshStrategy::Oauth2RefreshToken as i32, + material, + secret_material_keys: vec![ + "client_secret".to_string(), + "refresh_token".to_string(), + ], + expires_at_ms: None, + workspace: workspace.to_string(), + }) + .await + { + return rollback_provider_create_after_gcloud_adc_failure( + &mut client, + &provider_name, + "configure", + &configure_err, + workspace, + ) + .await; + } + + if let Err(rotate_err) = client + .rotate_provider_credential(RotateProviderCredentialRequest { + provider: provider_name.clone(), + credential_key: adc_credential_key, + workspace: workspace.to_string(), + }) + .await + { + return rollback_provider_create_after_gcloud_adc_failure( + &mut client, + &provider_name, + "mint the initial access token for", + &rotate_err, + workspace, + ) + .await; + } + + println!("{} Created provider {}", "✓".green().bold(), provider_name); + println!("Configured GCP credentials from gcloud ADC and minted the initial access token"); + return Ok(()); + } + + println!("{} Created provider {}", "✓".green().bold(), provider_name); + Ok(()) +} + +fn provider_profile_allows_empty_credentials(profile: &ProviderProfile) -> bool { + ProviderTypeProfile::from_proto(profile).allows_empty_provider_credentials() +} + +fn provider_profile_allows_runtime_credentials(profile: &ProviderProfile) -> bool { + ProviderTypeProfile::from_proto(profile).allows_runtime_provider_credentials() +} + +pub async fn provider_get( + server: &str, + name: &str, + workspace: &str, + tls: &TlsOptions, +) -> Result<()> { + let mut client = grpc_client(server, tls).await?; + let response = client + .get_provider(GetProviderRequest { + name: name.to_string(), + workspace: workspace.to_string(), + }) + .await + .into_diagnostic()?; + + let provider = response + .into_inner() + .provider + .ok_or_else(|| miette::miette!("provider missing from response"))?; + + let credential_keys = provider_credential_keys(&provider); + let config_keys = provider.config.keys().cloned().collect::>(); + + println!("{}", "Provider:".cyan().bold()); + println!(); + println!(" {} {}", "Id:".dimmed(), provider.object_id()); + println!(" {} {}", "Name:".dimmed(), provider.object_name()); + println!(" {} {}", "Type:".dimmed(), provider.r#type); + println!( + " {} {}", + "Resource version:".dimmed(), + provider.metadata.as_ref().map_or(0, |m| m.resource_version) + ); + println!( + " {} {}", + "Credential keys:".dimmed(), + if credential_keys.is_empty() { + "".to_string() + } else { + credential_keys.join(", ") + } + ); + println!( + " {} {}", + "Config keys:".dimmed(), + if config_keys.is_empty() { + "".to_string() + } else { + config_keys.join(", ") + } + ); + + Ok(()) +} + +fn provider_to_json(provider: &Provider) -> serde_json::Value { + let mut obj = serde_json::Map::new(); + + // Core fields + obj.insert("id".to_string(), serde_json::json!(provider.object_id())); + obj.insert( + "name".to_string(), + serde_json::json!(provider.object_name()), + ); + obj.insert( + "workspace".to_string(), + serde_json::json!(provider.object_workspace()), + ); + obj.insert("type".to_string(), serde_json::json!(provider.r#type)); + + // Credential keys (NEVER values - security) + let credential_keys = provider_credential_keys(provider); + obj.insert( + "credential_keys".to_string(), + serde_json::json!(credential_keys), + ); + + // Config keys (keys only, not values) + if !provider.config.is_empty() { + let config_keys: Vec = provider.config.keys().cloned().collect(); + obj.insert("config_keys".to_string(), serde_json::json!(config_keys)); + } + + // Metadata fields (only if metadata exists) + if let Some(meta) = &provider.metadata { + if !meta.labels.is_empty() { + obj.insert("labels".to_string(), serde_json::json!(meta.labels)); + } + if meta.resource_version != 0 { + obj.insert( + "resource_version".to_string(), + serde_json::json!(meta.resource_version), + ); + } + if meta.created_at_ms != 0 { + obj.insert( + "created_at".to_string(), + serde_json::json!(format_epoch_ms(meta.created_at_ms)), + ); + } + } + + // Credential expiration times (only if present) + if !provider.credential_expires_at_ms.is_empty() { + obj.insert( + "credential_expires_at_ms".to_string(), + serde_json::json!(provider.credential_expires_at_ms), + ); + } + + serde_json::Value::Object(obj) +} + +fn provider_credential_keys(provider: &Provider) -> Vec { + let mut keys: Vec = provider + .credentials + .keys() + .chain(provider.credential_handles.keys()) + .cloned() + .collect(); + keys.sort(); + keys.dedup(); + keys +} + +#[allow(clippy::too_many_arguments)] +pub async fn provider_list( + server: &str, + limit: u32, + offset: u32, + names_only: bool, + output: &str, + workspace: &str, + all_workspaces: bool, + tls: &TlsOptions, +) -> Result<()> { + let mut client = grpc_client(server, tls).await?; + let response = client + .list_providers(ListProvidersRequest { + limit, + offset, + workspace: if all_workspaces { + String::new() + } else { + workspace.to_string() + }, + all_workspaces, + }) + .await + .into_diagnostic()?; + let providers = response.into_inner().providers; + + // Handle structured output formats (json, yaml) + if crate::output::print_output_collection(output, &providers, provider_to_json)? { + return Ok(()); + } + + if providers.is_empty() { + if !names_only { + println!("No providers found."); + } + return Ok(()); + } + + if names_only { + for provider in &providers { + if all_workspaces { + println!("{}/{}", provider.object_workspace(), provider.object_name()); + } else { + println!("{}", provider.object_name()); + } + } + return Ok(()); + } + + let ws_width = if all_workspaces { + providers + .iter() + .map(|p| p.object_workspace().len()) + .max() + .unwrap_or(9) + .max(9) + } else { + 0 + }; + let name_width = providers + .iter() + .map(|provider| provider.object_name().len()) + .max() + .unwrap_or(4) + .max(4); + let type_width = providers + .iter() + .map(|provider| provider.r#type.len()) + .max() + .unwrap_or(4) + .max(4); + + if all_workspaces { + println!( + "{: Result<()> { + let mut client = grpc_client(server, tls).await?; + let response = client + .list_provider_profiles(ListProviderProfilesRequest { + limit: 100, + offset: 0, + workspace: workspace.to_string(), + }) + .await + .into_diagnostic()?; + let mut profiles = response.into_inner().profiles; + profiles.sort_by(|left, right| { + left.category + .cmp(&right.category) + .then_with(|| left.id.cmp(&right.id)) + }); + let dto_profiles = profiles + .iter() + .map(ProviderTypeProfile::from_proto) + .collect::>(); + + if crate::output::print_output_direct( + output, + || profiles_to_json(&dto_profiles).into_diagnostic(), + || profiles_to_yaml(&dto_profiles).into_diagnostic(), + )? { + return Ok(()); + } + + if profiles.is_empty() { + println!("No provider profiles found."); + return Ok(()); + } + + println!("{}", "Available Provider Profiles:".cyan().bold()); + let id_width = provider_profile_id_width(&profiles); + let display_width = provider_profile_display_width(&profiles); + let source_width = provider_profile_source_width(&profiles); + let scope_width = provider_profile_scope_width(&profiles); + let mut current_category = i32::MIN; + for profile in &profiles { + if profile.category != current_category { + current_category = profile.category; + println!(); + println!(" {}", display_provider_category(current_category).bold()); + print_provider_type_header(id_width, scope_width, source_width, display_width); + } + print_provider_type_row(profile, id_width, scope_width, source_width, display_width); + } + + Ok(()) +} + +pub async fn provider_profile_export( + server: &str, + id: &str, + output: &str, + workspace: &str, + tls: &TlsOptions, +) -> Result<()> { + let rendered = provider_profile_export_text(server, id, output, workspace, tls).await?; + if output == "json" { + println!("{rendered}"); + } else { + print!("{rendered}"); + } + Ok(()) +} + +pub async fn provider_profile_export_text( + server: &str, + id: &str, + output: &str, + workspace: &str, + tls: &TlsOptions, +) -> Result { + let mut client = grpc_client(server, tls).await?; + let response = client + .get_provider_profile(GetProviderProfileRequest { + id: id.to_string(), + workspace: workspace.to_string(), + }) + .await + .into_diagnostic()?; + let profile = response + .into_inner() + .profile + .ok_or_else(|| miette!("provider profile '{id}' not found"))?; + let profile = ProviderTypeProfile::from_proto(&profile); + + match output { + "json" => profile_to_json(&profile).into_diagnostic(), + "yaml" => profile_to_yaml(&profile).into_diagnostic(), + "table" => Err(miette!( + "profile export supports '-o yaml' and '-o json'; table output is not supported" + )), + _ => Err(miette!("unsupported output format: {output}")), + } +} + +pub async fn provider_profile_import( + server: &str, + file: Option<&Path>, + from: Option<&Path>, + workspace: &str, + tls: &TlsOptions, +) -> Result<()> { + let (items, mut diagnostics) = load_profile_import_items(file, from)?; + if items.is_empty() && diagnostics.is_empty() { + return Err(miette!("no provider profile files found")); + } + if profile_diagnostics_have_errors(&diagnostics) { + print_profile_diagnostics(&diagnostics); + return Err(miette!("provider profile import failed")); + } + + let mut client = grpc_client(server, tls).await?; + if !items.is_empty() { + let response = client + .import_provider_profiles(ImportProviderProfilesRequest { + profiles: items, + workspace: workspace.to_string(), + }) + .await + .into_diagnostic()? + .into_inner(); + diagnostics.extend(response.diagnostics); + if response.imported { + println!( + "Imported {} provider profile{}.", + response.profiles.len(), + if response.profiles.len() == 1 { + "" + } else { + "s" + } + ); + return Ok(()); + } + } + + print_profile_diagnostics(&diagnostics); + Err(miette!("provider profile import failed")) +} + +pub async fn provider_profile_update( + server: &str, + id: &str, + file: &Path, + workspace: &str, + tls: &TlsOptions, +) -> Result<()> { + let (mut items, mut diagnostics) = load_profile_import_items(Some(file), None)?; + if items.is_empty() && diagnostics.is_empty() { + return Err(miette!("no provider profile files found")); + } + if profile_diagnostics_have_errors(&diagnostics) { + print_profile_diagnostics(&diagnostics); + return Err(miette!("provider profile update failed")); + } + + let mut client = grpc_client(server, tls).await?; + if let Some(item) = items.pop() { + let expected_resource_version = item + .profile + .as_ref() + .map_or(0, |profile| profile.resource_version); + let response = client + .update_provider_profiles(UpdateProviderProfilesRequest { + profile: Some(item), + expected_resource_version, + id: id.to_string(), + workspace: workspace.to_string(), + }) + .await + .into_diagnostic()? + .into_inner(); + diagnostics.extend(response.diagnostics); + if response.updated { + println!("Updated provider profile."); + return Ok(()); + } + } + + print_profile_diagnostics(&diagnostics); + Err(miette!("provider profile update failed")) +} + +pub async fn provider_profile_lint( + server: &str, + file: Option<&Path>, + from: Option<&Path>, + workspace: &str, + tls: &TlsOptions, +) -> Result<()> { + let (items, mut diagnostics) = load_profile_import_items(file, from)?; + if items.is_empty() && diagnostics.is_empty() { + return Err(miette!("no provider profile files found")); + } + + if !items.is_empty() { + let mut client = grpc_client(server, tls).await?; + let response = client + .lint_provider_profiles(LintProviderProfilesRequest { + profiles: items, + workspace: workspace.to_string(), + }) + .await + .into_diagnostic()? + .into_inner(); + diagnostics.extend(response.diagnostics); + } + + if profile_diagnostics_have_errors(&diagnostics) { + print_profile_diagnostics(&diagnostics); + return Err(miette!("provider profile lint failed")); + } + + println!("Provider profile lint passed."); + Ok(()) +} + +pub async fn provider_profile_delete( + server: &str, + ids: &[String], + workspace: &str, + tls: &TlsOptions, +) -> Result<()> { + let mut client = grpc_client(server, tls).await?; + let mut failures = Vec::new(); + for id in ids { + let response = match client + .delete_provider_profile(DeleteProviderProfileRequest { + id: id.clone(), + workspace: workspace.to_string(), + }) + .await + { + Ok(response) => response.into_inner(), + Err(status) => { + eprintln!( + "{} Failed to delete provider profile {id}: {status}", + "!".red().bold() + ); + failures.push(id.clone()); + continue; + } + }; + if response.deleted { + println!("{} Deleted provider profile {id}", "✓".green().bold()); + } else { + println!("{} Provider profile {id} not found", "!".yellow()); + } + } + aggregate_delete_failures("provider profile", &failures) +} + +pub async fn provider_refresh_status( + server: &str, + name: &str, + credential_key: Option<&str>, + workspace: &str, + tls: &TlsOptions, +) -> Result<()> { + let mut client = grpc_client(server, tls).await?; + let response = client + .get_provider_refresh_status(GetProviderRefreshStatusRequest { + provider: name.to_string(), + credential_key: credential_key.unwrap_or_default().to_string(), + workspace: workspace.to_string(), + }) + .await + .into_diagnostic()? + .into_inner(); + + if response.credentials.is_empty() { + if let Some(credential_key) = credential_key { + println!( + "No refresh configuration found for provider '{name}' credential '{credential_key}'." + ); + } else { + println!("No refresh configurations found for provider '{name}'."); + } + return Ok(()); + } + + println!("{}", refresh_status_header()); + for status in response.credentials { + print_refresh_status_row(&status); + } + Ok(()) +} + +fn refresh_status_header() -> String { + format!( + "{:<24} {:<28} {:<28} {:<24} {:<18} {:<20} {:<20} {:<20} {:<44} {}", + "PROVIDER".bold(), + "CREDENTIAL_KEY".bold(), + "STRATEGY".bold(), + "STATUS".bold(), + "RECOVERY".bold(), + "EXPIRES_AT".bold(), + "NEXT_REFRESH".bold(), + "LAST_REFRESH".bold(), + "FAILURE_CODE".bold(), + "LAST_ERROR".bold(), + ) +} + +pub struct ProviderRefreshConfigInput<'a> { + pub name: &'a str, + pub credential_key: &'a str, + pub strategy: &'a str, + pub material: &'a [String], + pub secret_material_env: &'a [String], + pub secret_material_keys: &'a [String], + pub credential_expires_at_ms: Option, +} + +pub async fn provider_refresh_config( + server: &str, + input: ProviderRefreshConfigInput<'_>, + workspace: &str, + tls: &TlsOptions, +) -> Result<()> { + let strategy = provider_refresh_strategy(input.strategy)?; + let mut material = parse_key_value_pairs(input.material, "--material")?; + let mut secret_material_keys = input.secret_material_keys.to_vec(); + // Env-resolved secrets are auto-marked secret; duplicate keys are an + // error rather than a precedence order. + for (key, value) in parse_secret_material_env_pairs(input.secret_material_env)? { + if material.contains_key(&key) { + return Err(miette!( + "duplicate material key '{key}': supplied via both --material and --secret-material-env" + )); + } + if !secret_material_keys.contains(&key) { + secret_material_keys.push(key.clone()); + } + material.insert(key, value); + } + let mut client = grpc_client(server, tls).await?; + let status = client + .configure_provider_refresh(ConfigureProviderRefreshRequest { + provider: input.name.to_string(), + credential_key: input.credential_key.to_string(), + strategy: strategy as i32, + material, + secret_material_keys, + expires_at_ms: input.credential_expires_at_ms, + workspace: workspace.to_string(), + }) + .await + .into_diagnostic()? + .into_inner() + .status + .ok_or_else(|| miette!("provider refresh status missing from response"))?; + + println!( + "{} Configured refresh for {} {}", + "✓".green().bold(), + status.provider_name, + status.credential_key + ); + Ok(()) +} + +pub async fn provider_rotate( + server: &str, + name: &str, + credential_key: &str, + workspace: &str, + tls: &TlsOptions, +) -> Result<()> { + let mut client = grpc_client(server, tls).await?; + let status = client + .rotate_provider_credential(RotateProviderCredentialRequest { + provider: name.to_string(), + credential_key: credential_key.to_string(), + workspace: workspace.to_string(), + }) + .await + .into_diagnostic()? + .into_inner() + .status + .ok_or_else(|| miette!("provider refresh status missing from response"))?; + + if status.last_error.is_empty() { + println!( + "{} Rotation requested for {} {} ({})", + "✓".green().bold(), + status.provider_name, + status.credential_key, + status.status + ); + } else { + println!( + "Rotation request recorded for {} {} ({}): {}", + status.provider_name, status.credential_key, status.status, status.last_error + ); + } + Ok(()) +} + +pub async fn provider_refresh_delete( + server: &str, + name: &str, + credential_key: &str, + workspace: &str, + tls: &TlsOptions, +) -> Result<()> { + let mut client = grpc_client(server, tls).await?; + let response = client + .delete_provider_refresh(DeleteProviderRefreshRequest { + provider: name.to_string(), + credential_key: credential_key.to_string(), + workspace: workspace.to_string(), + }) + .await + .into_diagnostic()? + .into_inner(); + + if response.deleted { + println!( + "{} Deleted refresh config for {} {}", + "✓".green().bold(), + name, + credential_key + ); + } else { + println!("No refresh config found for provider '{name}' credential '{credential_key}'."); + } + Ok(()) +} + +fn provider_refresh_strategy(strategy: &str) -> Result { + match strategy { + "oauth2_refresh_token" => Ok(ProviderCredentialRefreshStrategy::Oauth2RefreshToken), + "oauth2_client_credentials" => { + Ok(ProviderCredentialRefreshStrategy::Oauth2ClientCredentials) + } + "google_service_account_jwt" => { + Ok(ProviderCredentialRefreshStrategy::GoogleServiceAccountJwt) + } + "aws_sts_assume_role" => Ok(ProviderCredentialRefreshStrategy::AwsStsAssumeRole), + _ => Err(miette!("unsupported provider refresh strategy: {strategy}")), + } +} + +fn print_refresh_status_row(status: &ProviderCredentialRefreshStatus) { + println!("{}", refresh_status_row(status)); +} + +fn refresh_status_row(status: &ProviderCredentialRefreshStatus) -> String { + let strategy = ProviderCredentialRefreshStrategy::try_from(status.strategy) + .unwrap_or(ProviderCredentialRefreshStrategy::Unspecified); + let recovery_action = ProviderCredentialRefreshRecoveryAction::try_from(status.recovery_action) + .unwrap_or(ProviderCredentialRefreshRecoveryAction::Unspecified); + format!( + "{:<24} {:<28} {:<28} {:<24} {:<18} {:<20} {:<20} {:<20} {:<44} {}", + status.provider_name, + status.credential_key, + provider_refresh_strategy_name(strategy), + status.status, + provider_refresh_recovery_action_name(recovery_action), + format_optional_epoch_ms(status.expires_at_ms), + format_refresh_next_at_ms(status.next_refresh_at_ms), + format_optional_epoch_ms(status.last_refresh_at_ms), + status.failure_code, + truncate_status_field(&status.last_error, 72), + ) +} + +fn format_refresh_next_at_ms(next_refresh_at_ms: i64) -> String { + if next_refresh_at_ms == i64::MAX { + "-".to_string() + } else { + format_optional_epoch_ms(next_refresh_at_ms) + } +} + +fn provider_refresh_recovery_action_name( + action: ProviderCredentialRefreshRecoveryAction, +) -> &'static str { + match action { + ProviderCredentialRefreshRecoveryAction::Retry => "retry", + ProviderCredentialRefreshRecoveryAction::Reauthorize => "reauthorize", + ProviderCredentialRefreshRecoveryAction::FixConfiguration => "fix_configuration", + ProviderCredentialRefreshRecoveryAction::Investigate => "investigate", + ProviderCredentialRefreshRecoveryAction::Unspecified => "-", + } +} + +fn provider_refresh_strategy_name(strategy: ProviderCredentialRefreshStrategy) -> &'static str { + match strategy { + ProviderCredentialRefreshStrategy::Static => "static", + ProviderCredentialRefreshStrategy::External => "external", + ProviderCredentialRefreshStrategy::Oauth2RefreshToken => "oauth2_refresh_token", + ProviderCredentialRefreshStrategy::Oauth2ClientCredentials => "oauth2_client_credentials", + ProviderCredentialRefreshStrategy::GoogleServiceAccountJwt => "google_service_account_jwt", + ProviderCredentialRefreshStrategy::AwsStsAssumeRole => "aws_sts_assume_role", + ProviderCredentialRefreshStrategy::Unspecified => "unspecified", + } +} + +fn load_profile_import_items( + file: Option<&Path>, + from: Option<&Path>, +) -> Result<( + Vec, + Vec, +)> { + let paths = profile_source_paths(file, from)?; + let mut items = Vec::new(); + let mut diagnostics = Vec::new(); + for path in paths { + match load_profile_import_item(&path) { + Ok(item) => items.push(item), + Err(diagnostic) => diagnostics.push(diagnostic), + } + } + Ok((items, diagnostics)) +} + +fn profile_source_paths(file: Option<&Path>, from: Option<&Path>) -> Result> { + if let Some(file) = file { + return Ok(vec![file.to_path_buf()]); + } + let Some(from) = from else { + return Ok(Vec::new()); + }; + let mut paths = Vec::new(); + for entry in std::fs::read_dir(from) + .into_diagnostic() + .wrap_err_with(|| format!("failed to read profile directory {}", from.display()))? + { + let entry = entry.into_diagnostic()?; + let path = entry.path(); + if path.is_file() && profile_extension_supported(&path) { + paths.push(path); + } + } + paths.sort(); + Ok(paths) +} + +fn profile_extension_supported(path: &Path) -> bool { + matches!( + path.extension().and_then(|ext| ext.to_str()), + Some("yaml" | "yml" | "json") + ) +} + +fn load_profile_import_item( + path: &Path, +) -> Result { + let source = path.display().to_string(); + let input = std::fs::read_to_string(path).map_err(|err| { + profile_file_diagnostic( + &source, + format!("failed to read provider profile file: {err}"), + ) + })?; + let profile = match path.extension().and_then(|ext| ext.to_str()) { + Some("yaml" | "yml") => parse_profile_yaml(&input), + Some("json") => parse_profile_json(&input), + _ => { + return Err(profile_file_diagnostic( + &source, + "unsupported provider profile file format".to_string(), + )); + } + } + .map_err(|err| profile_file_diagnostic(&source, err.to_string()))?; + + let pre_lower = profile.validate_before_lowering(&source); + if let Some(diag) = pre_lower.into_iter().find(|d| d.severity == "error") { + return Err(ProviderProfileDiagnostic { + source: diag.source, + profile_id: diag.profile_id, + field: diag.field, + message: diag.message, + severity: diag.severity, + }); + } + + Ok(ProviderProfileImportItem { + profile: Some(profile.to_proto()), + source, + }) +} + +fn profile_file_diagnostic(source: &str, message: String) -> ProviderProfileDiagnostic { + ProviderProfileDiagnostic { + source: source.to_string(), + profile_id: String::new(), + field: "file".to_string(), + message, + severity: "error".to_string(), + } +} + +fn print_profile_diagnostics(diagnostics: &[ProviderProfileDiagnostic]) { + if diagnostics.is_empty() { + return; + } + eprintln!("{}", "Provider profile diagnostics:".red().bold()); + for diagnostic in diagnostics { + let source = if diagnostic.source.is_empty() { + "" + } else { + &diagnostic.source + }; + let profile = if diagnostic.profile_id.is_empty() { + "-".to_string() + } else { + diagnostic.profile_id.clone() + }; + eprintln!( + " {} {} profile={} field={} {}", + diagnostic.severity.as_str().red(), + source, + profile, + diagnostic.field, + diagnostic.message + ); + } +} + +fn profile_diagnostics_have_errors(diagnostics: &[ProviderProfileDiagnostic]) -> bool { + diagnostics + .iter() + .any(|diagnostic| diagnostic.severity == "error") +} + +fn display_provider_category(category: i32) -> &'static str { + match ProviderProfileCategory::try_from(category).unwrap_or(ProviderProfileCategory::Other) { + ProviderProfileCategory::Inference => "INFERENCE", + ProviderProfileCategory::Agent => "AGENT", + ProviderProfileCategory::SourceControl => "SOURCE CONTROL", + ProviderProfileCategory::Messaging => "MESSAGING", + ProviderProfileCategory::Data => "DATA", + ProviderProfileCategory::Knowledge => "KNOWLEDGE", + ProviderProfileCategory::Other | ProviderProfileCategory::Unspecified => "OTHER", + } +} + +const PROVIDER_PROFILE_ID_MAX_WIDTH: usize = 32; +const PROVIDER_PROFILE_DISPLAY_MAX_WIDTH: usize = 40; +const PROVIDER_PROFILE_SOURCE_MAX_WIDTH: usize = 24; + +fn provider_profile_id_width(profiles: &[ProviderProfile]) -> usize { + profiles + .iter() + .map(|profile| { + profile + .id + .chars() + .count() + .min(PROVIDER_PROFILE_ID_MAX_WIDTH) + }) + .max() + .unwrap_or(2) + .max(2) +} + +fn provider_profile_display_width(profiles: &[ProviderProfile]) -> usize { + profiles + .iter() + .map(|profile| { + profile + .display_name + .chars() + .count() + .min(PROVIDER_PROFILE_DISPLAY_MAX_WIDTH) + }) + .max() + .unwrap_or(4) + .max(4) +} + +fn provider_profile_scope_width(profiles: &[ProviderProfile]) -> usize { + profiles + .iter() + .map(|profile| profile.scope.chars().count()) + .max() + .unwrap_or(5) + .max(5) +} + +fn provider_profile_source_width(profiles: &[ProviderProfile]) -> usize { + profiles + .iter() + .map(|profile| { + profile + .source + .chars() + .count() + .min(PROVIDER_PROFILE_SOURCE_MAX_WIDTH) + }) + .max() + .unwrap_or(6) + .max(6) +} + +fn print_provider_type_header( + id_width: usize, + scope_width: usize, + source_width: usize, + display_width: usize, +) { + let endpoints = "ENDPOINTS"; + println!( + " {: { + pub server: &'a str, + pub name: &'a str, + pub from_existing: bool, + pub from_oidc_token: bool, + pub credentials: &'a [String], + pub config: &'a [String], + pub credential_expires_at: &'a [String], + pub workspace: &'a str, + pub tls: &'a TlsOptions, +} + +pub async fn provider_update(options: ProviderUpdateOptions<'_>) -> Result<()> { + let ProviderUpdateOptions { + server, + name, + from_existing, + from_oidc_token, + credentials, + config, + credential_expires_at, + workspace, + tls, + } = options; + + if from_existing && !credentials.is_empty() { + return Err(miette::miette!( + "--from-existing cannot be combined with --credential" + )); + } + if from_existing && from_oidc_token { + return Err(miette::miette!( + "--from-existing cannot be combined with --from-oidc-token" + )); + } + + let mut client = grpc_client(server, tls).await?; + + // Look up the stored provider so the update can carry its type and profile + // workspace. Policy interceptors evaluate the request before the gateway + // merges it with stored state, so an update that omits them cannot be + // authorized against the profile that owns the provider. + // + // The read is best-effort. A caller holding `provider:write` without + // `provider:read` must still be able to rotate credentials, so a denied + // read keeps the previous behavior of sending empty metadata rather than + // failing the update. `--from-existing` and `--from-oidc-token` need the + // stored type, so they surface the error instead. + let existing = match client + .get_provider(GetProviderRequest { + name: name.to_string(), + workspace: workspace.to_string(), + }) + .await + { + Ok(response) => response.into_inner().provider, + Err(status) + if status.code() == Code::PermissionDenied && !from_existing && !from_oidc_token => + { + None + } + Err(status) => return Err(status).into_diagnostic(), + }; + + if existing.is_none() && (from_existing || from_oidc_token) { + return Err(miette::miette!("provider '{name}' not found")); + } + + let oidc_profile = if from_oidc_token { + let existing = existing.as_ref().expect("checked above"); + Some( + fetch_provider_profile(&mut client, &existing.r#type, &existing.profile_workspace) + .await?, + ) + } else { + None + }; + + let (mut credential_map, oidc_credential_expires_at_ms) = if from_oidc_token { + provider_credential_from_oidc_token(credentials, oidc_profile.as_ref(), tls).await? + } else { + (parse_credential_pairs(credentials)?, HashMap::new()) + }; + let mut config_map = parse_key_value_pairs(config, "--config")?; + let mut credential_expires_at_ms = parse_credential_expiry_pairs(credential_expires_at)?; + credential_expires_at_ms.extend(oidc_credential_expires_at_ms); + + if from_existing { + let stored = existing.as_ref().expect("checked above"); + let provider_type = stored.r#type.clone(); + let discovered = + discover_existing_provider_data(&mut client, &provider_type, &stored.profile_workspace) + .await?; + let Some(discovered) = discovered else { + return Err(miette::miette!( + "no existing local credentials/config found for provider type '{provider_type}'" + )); + }; + + for (key, value) in discovered.credentials { + credential_map.entry(key).or_insert(value); + } + for (key, value) in discovered.config { + config_map.entry(key).or_insert(value); + } + } + + let response = client + .update_provider(UpdateProviderRequest { + provider: Some(Provider { + metadata: Some(openshell_core::proto::datamodel::v1::ObjectMeta { + id: String::new(), + name: name.to_string(), + created_at_ms: 0, + labels: HashMap::new(), + resource_version: 0, + annotations: HashMap::new(), + workspace: workspace.to_string(), + deletion_timestamp_ms: 0, + }), + r#type: existing + .as_ref() + .map(|provider| provider.r#type.clone()) + .unwrap_or_default(), + credentials: credential_map, + config: config_map, + credential_expires_at_ms: HashMap::new(), + profile_workspace: existing + .as_ref() + .map(|provider| provider.profile_workspace.clone()) + .unwrap_or_default(), + credential_handles: HashMap::new(), + }), + credential_expires_at_ms, + workspace: workspace.to_string(), + }) + .await + .into_diagnostic()?; + + let provider = response + .into_inner() + .provider + .ok_or_else(|| miette::miette!("provider missing from response"))?; + + println!( + "{} Updated provider {}", + "✓".green().bold(), + provider.object_name() + ); + Ok(()) +} + +pub async fn provider_delete( + server: &str, + names: &[String], + workspace: &str, + tls: &TlsOptions, +) -> Result<()> { + let mut client = grpc_client(server, tls).await?; + let mut failures = Vec::new(); + for name in names { + let response = match client + .delete_provider(DeleteProviderRequest { + name: name.clone(), + workspace: workspace.to_string(), + }) + .await + { + Ok(response) => response, + Err(status) => { + eprintln!( + "{} Failed to delete provider {name}: {status}", + "!".red().bold() + ); + failures.push(name.clone()); + continue; + } + }; + if response.into_inner().deleted { + println!("{} Deleted provider {name}", "✓".green().bold()); + } else { + println!("{} Provider {name} not found", "!".yellow()); + } + } + aggregate_delete_failures("provider", &failures) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::TEST_ENV_LOCK; + use crate::test_utils::EnvVarGuard; + use std::fs; + use std::io::Write; + + use openshell_core::proto::{ + CredentialHandle, Provider, ProviderCredentialRefresh, + ProviderCredentialRefreshRecoveryAction, ProviderCredentialRefreshStatus, + ProviderCredentialRefreshStrategy, ProviderCredentialTokenGrant, ProviderProfile, + ProviderProfileCredential, datamodel::v1::ObjectMeta, + }; + + #[test] + fn attached_provider_json_is_sorted_and_secret_safe() { + let provider = Provider { + metadata: Some(ObjectMeta { + name: "github".to_string(), + ..Default::default() + }), + r#type: "github".to_string(), + credentials: HashMap::from([ + ("Z_TOKEN".to_string(), "inline-secret".to_string()), + ("SHARED".to_string(), "shared-secret".to_string()), + ]), + config: HashMap::from([ + ("Z_URL".to_string(), "https://secret.example".to_string()), + ("A_MODE".to_string(), "sensitive-config".to_string()), + ]), + credential_expires_at_ms: HashMap::from([("Z_TOKEN".to_string(), 123)]), + profile_workspace: "internal".to_string(), + credential_handles: HashMap::from([ + ( + "A_HANDLE".to_string(), + CredentialHandle { + driver: "vault".to_string(), + handle: "opaque-secret-handle".to_string(), + metadata: HashMap::from([( + "internal".to_string(), + "metadata-value".to_string(), + )]), + }, + ), + ("SHARED".to_string(), CredentialHandle::default()), + ]), + }; + + let value = attached_provider_to_json(&provider); + assert_eq!( + value, + serde_json::json!({ + "name": "github", + "type": "github", + "credential_keys": ["A_HANDLE", "SHARED", "Z_TOKEN"], + "config_keys": ["A_MODE", "Z_URL"], + }) + ); + let serialized = value.to_string(); + for secret in [ + "inline-secret", + "shared-secret", + "https://secret.example", + "sensitive-config", + "opaque-secret-handle", + "metadata-value", + "internal", + "123", + ] { + assert!(!serialized.contains(secret), "leaked {secret}"); + } + } + + #[test] + fn provider_attachment_table_formats_provider_counts() { + let output = format_provider_attachment_table( + &[Provider { + metadata: Some(ObjectMeta { + name: "work-custom".to_string(), + ..Default::default() + }), + r#type: "custom-api".to_string(), + credentials: [ + ("CUSTOM_API_KEY".to_string(), "REDACTED".to_string()), + ("CUSTOM_API_SECRET".to_string(), "REDACTED".to_string()), + ] + .into_iter() + .collect(), + config: std::iter::once(( + "BASE_URL".to_string(), + "https://api.custom.example".to_string(), + )) + .collect(), + credential_expires_at_ms: HashMap::new(), + profile_workspace: String::new(), + credential_handles: HashMap::new(), + }], + false, + ); + + assert!(output.contains("NAME")); + assert!(output.contains("TYPE")); + assert!(output.contains("CREDENTIAL_KEYS")); + assert!(output.contains("CONFIG_KEYS")); + assert!(output.contains("work-custom")); + assert!(output.contains("custom-api")); + assert!(output.contains('2')); + assert!(output.contains('1')); + } + + #[test] + fn refresh_status_table_includes_operational_fields() { + let header = refresh_status_header(); + assert!(header.contains("NEXT_REFRESH")); + assert!(header.contains("LAST_REFRESH")); + assert!(header.contains("RECOVERY")); + assert!(header.contains("FAILURE_CODE")); + assert!(header.contains("LAST_ERROR")); + + let row = refresh_status_row(&ProviderCredentialRefreshStatus { + provider_name: "my-graph".to_string(), + provider_id: "provider-id".to_string(), + credential_key: "MS_GRAPH_ACCESS_TOKEN".to_string(), + strategy: ProviderCredentialRefreshStrategy::Oauth2ClientCredentials as i32, + status: "error".to_string(), + expires_at_ms: 1_767_225_600_000, + next_refresh_at_ms: i64::MAX, + last_refresh_at_ms: 1_767_225_000_000, + last_error: "token endpoint returned a very long error message that should be truncated for table readability" + .to_string(), + recovery_action: ProviderCredentialRefreshRecoveryAction::Reauthorize as i32, + failure_code: "oauth_rotated_refresh_token_handle_missing".to_string(), + provider_error_subtype: "invalid_rapt".to_string(), + last_error_at_ms: 1_767_225_000_000, + }); + + assert!(row.contains("my-graph")); + assert!(row.contains("MS_GRAPH_ACCESS_TOKEN")); + assert!(row.contains("oauth2_client_credentials")); + assert!(row.contains("error")); + assert!(row.contains("reauthorize")); + assert!(row.contains("oauth_rotated_refresh_token_handle_missing")); + assert!(row.contains("2026-01-01 00:00:00")); + assert!(!row.contains("292278994")); + assert!(row.contains("...")); + } + + #[test] + fn empty_provider_credentials_require_all_required_credentials_to_be_runtime_resolvable() { + let refresh_token_profile = ProviderProfile { + credentials: vec![ProviderProfileCredential { + name: "MS_GRAPH_ACCESS_TOKEN".to_string(), + required: true, + refresh: Some(ProviderCredentialRefresh { + strategy: ProviderCredentialRefreshStrategy::Oauth2RefreshToken as i32, + ..Default::default() + }), + ..Default::default() + }], + ..Default::default() + }; + assert!(provider_profile_allows_empty_credentials( + &refresh_token_profile + )); + + let token_grant_profile = ProviderProfile { + credentials: vec![ProviderProfileCredential { + name: "ACCESS_TOKEN".to_string(), + required: true, + token_grant: Some(ProviderCredentialTokenGrant { + token_endpoint: "https://auth.example.com/token".to_string(), + ..Default::default() + }), + ..Default::default() + }], + ..Default::default() + }; + assert!(provider_profile_allows_empty_credentials( + &token_grant_profile + )); + + let mixed_static_profile = ProviderProfile { + credentials: vec![ + ProviderProfileCredential { + name: "ACCESS_TOKEN".to_string(), + required: true, + refresh: Some(ProviderCredentialRefresh { + strategy: ProviderCredentialRefreshStrategy::Oauth2ClientCredentials as i32, + ..Default::default() + }), + ..Default::default() + }, + ProviderProfileCredential { + name: "STATIC_API_KEY".to_string(), + required: true, + refresh: None, + ..Default::default() + }, + ], + ..Default::default() + }; + assert!(!provider_profile_allows_empty_credentials( + &mixed_static_profile + )); + + let optional_refresh_profile = ProviderProfile { + credentials: vec![ProviderProfileCredential { + name: "OPTIONAL_TOKEN".to_string(), + required: false, + refresh: Some(ProviderCredentialRefresh { + strategy: ProviderCredentialRefreshStrategy::GoogleServiceAccountJwt as i32, + ..Default::default() + }), + ..Default::default() + }], + ..Default::default() + }; + assert!(provider_profile_allows_empty_credentials( + &optional_refresh_profile + )); + } + + #[test] + fn inferred_provider_type_returns_type_for_known_command() { + let result = inferred_provider_type(&["claude".to_string(), "--help".to_string()]); + assert_eq!(result, Some("claude-code".to_string())); + } + + #[test] + fn inferred_provider_type_returns_none_for_unknown_command() { + let result = inferred_provider_type(&["bash".to_string()]); + assert_eq!(result, None); + } + + #[test] + fn inferred_provider_type_returns_none_for_empty_command() { + let result = inferred_provider_type(&[]); + assert_eq!(result, None); + } + + #[test] + fn inferred_provider_type_normalizes_aliases() { + // Retired legacy types are not inferred, even when a custom profile + // with the same ID could be imported and attached explicitly. + let result = inferred_provider_type(&["glab".to_string()]); + assert_eq!(result, None); + + // `gh` should resolve to `github` + let result = inferred_provider_type(&["gh".to_string()]); + assert_eq!(result, Some("github".to_string())); + } + + #[test] + fn inferred_provider_type_handles_full_path() { + let result = inferred_provider_type(&["/usr/local/bin/claude".to_string()]); + assert_eq!(result, Some("claude-code".to_string())); + } + + #[test] + fn read_gcloud_adc_missing_file_errors() { + let _lock = TEST_ENV_LOCK + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let _guard = EnvVarGuard::set( + "GOOGLE_APPLICATION_CREDENTIALS", + "/nonexistent/path/to/adc.json", + ); + let err = read_gcloud_adc().expect_err("missing file should error"); + assert!( + err.to_string().contains("failed to read gcloud ADC file"), + "unexpected error: {err}" + ); + } + + #[test] + fn read_gcloud_adc_wrong_type_errors() { + let _lock = TEST_ENV_LOCK + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let tmp = tempfile::NamedTempFile::new().expect("tempfile"); + let json = serde_json::json!({ + "type": "service_account", + "project_id": "my-project", + "private_key_id": "key123" + }); + Write::write_all(&mut tmp.as_file(), json.to_string().as_bytes()).expect("write tempfile"); + let _guard = EnvVarGuard::set( + "GOOGLE_APPLICATION_CREDENTIALS", + tmp.path().to_str().expect("tempfile path"), + ); + let err = read_gcloud_adc().expect_err("wrong type should error"); + // The service_account type gets a targeted message directing the user + // to the real Vertex service-account credential flow instead of the + // generic authorized_user hint. + assert!( + err.to_string() + .contains("GOOGLE_VERTEX_AI_SERVICE_ACCOUNT_TOKEN"), + "error should mention the service-account token key, got: {err}" + ); + } + + #[test] + fn read_gcloud_adc_parses_user_creds() { + let _lock = TEST_ENV_LOCK + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let tmp = tempfile::NamedTempFile::new().expect("tempfile"); + let json = serde_json::json!({ + "type": "authorized_user", + "client_id": "test-client-id.apps.googleusercontent.com", + "client_secret": "test-client-secret", + "refresh_token": "test-refresh-token" + }); + Write::write_all(&mut tmp.as_file(), json.to_string().as_bytes()).expect("write tempfile"); + let _guard = EnvVarGuard::set( + "GOOGLE_APPLICATION_CREDENTIALS", + tmp.path().to_str().expect("tempfile path"), + ); + let (client_id, client_secret, refresh_token) = + read_gcloud_adc().expect("valid ADC should parse"); + assert_eq!(client_id, "test-client-id.apps.googleusercontent.com"); + assert_eq!(client_secret, "test-client-secret"); + assert_eq!(refresh_token, "test-refresh-token"); + } + + #[test] + fn read_gcloud_adc_uses_cloudsdk_config_fallback() { + let _lock = TEST_ENV_LOCK + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let dir = tempfile::tempdir().expect("tempdir"); + let adc_path = dir.path().join("application_default_credentials.json"); + let json = serde_json::json!({ + "type": "authorized_user", + "client_id": "cloudsdk-client-id.apps.googleusercontent.com", + "client_secret": "cloudsdk-client-secret", + "refresh_token": "cloudsdk-refresh-token" + }); + fs::write(&adc_path, json.to_string()).expect("write adc file"); + let _adc_guard = EnvVarGuard::unset("GOOGLE_APPLICATION_CREDENTIALS"); + let _cloudsdk_guard = + EnvVarGuard::set("CLOUDSDK_CONFIG", dir.path().to_str().expect("config path")); + + let (client_id, client_secret, refresh_token) = + read_gcloud_adc().expect("valid CLOUDSDK_CONFIG ADC should parse"); + assert_eq!(client_id, "cloudsdk-client-id.apps.googleusercontent.com"); + assert_eq!(client_secret, "cloudsdk-client-secret"); + assert_eq!(refresh_token, "cloudsdk-refresh-token"); + } + + #[test] + fn read_gcloud_adc_malformed_json_errors() { + let _lock = TEST_ENV_LOCK + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let tmp = tempfile::NamedTempFile::new().expect("tempfile"); + Write::write_all(&mut tmp.as_file(), b"not valid json at all {{{{") + .expect("write tempfile"); + let _guard = EnvVarGuard::set( + "GOOGLE_APPLICATION_CREDENTIALS", + tmp.path().to_str().expect("tempfile path"), + ); + let result = read_gcloud_adc(); + assert!( + result.is_err(), + "malformed JSON should produce an error, got: {result:?}" + ); + let err = result.unwrap_err(); + let msg = format!("{err}"); + assert!( + msg.contains("parse") + || msg.contains("JSON") + || msg.contains("json") + || msg.contains("invalid") + || msg.contains("failed"), + "error message should mention parse/JSON failure, got: {msg}" + ); + } + + #[test] + fn empty_provider_credentials_allow_oauth2_refresh_token() { + use openshell_core::proto::{ + ProviderCredentialRefresh, ProviderCredentialRefreshStrategy, ProviderProfile, + ProviderProfileCredential, + }; + + let strategy = ProviderCredentialRefreshStrategy::Oauth2RefreshToken as i32; + let profile = ProviderProfile { + credentials: vec![ProviderProfileCredential { + required: true, + refresh: Some(ProviderCredentialRefresh { + strategy, + ..Default::default() + }), + ..Default::default() + }], + ..Default::default() + }; + assert!( + provider_profile_allows_empty_credentials(&profile), + "Oauth2RefreshToken should be allowed for refresh bootstrap" + ); + } + + #[test] + fn provider_to_json_includes_core_fields() { + let metadata = ObjectMeta { + id: "prov-123".to_string(), + name: "test-provider".to_string(), + ..Default::default() + }; + + let provider = Provider { + metadata: Some(metadata), + r#type: "anthropic".to_string(), + credentials: HashMap::new(), + config: HashMap::new(), + credential_expires_at_ms: HashMap::new(), + profile_workspace: String::new(), + credential_handles: HashMap::new(), + }; + + let json = provider_to_json(&provider); + + assert_eq!(json["id"], "prov-123"); + assert_eq!(json["name"], "test-provider"); + assert_eq!(json["workspace"], ""); + assert_eq!(json["type"], "anthropic"); + } + + #[test] + fn provider_to_json_exposes_credential_keys_not_values() { + let mut credentials = HashMap::new(); + credentials.insert("ANTHROPIC_API_KEY".to_string(), "secret-value".to_string()); + credentials.insert("OTHER_KEY".to_string(), "other-secret".to_string()); + + let provider = Provider { + metadata: Some(ObjectMeta::default()), + r#type: "anthropic".to_string(), + credentials, + config: HashMap::new(), + credential_expires_at_ms: HashMap::new(), + profile_workspace: String::new(), + credential_handles: HashMap::new(), + }; + + let json = provider_to_json(&provider); + let json_str = json.to_string(); + + // Assert credential keys are present + let keys = json["credential_keys"].as_array().unwrap(); + assert_eq!(keys.len(), 2); + assert!(keys.iter().any(|k| k.as_str() == Some("ANTHROPIC_API_KEY"))); + assert!(keys.iter().any(|k| k.as_str() == Some("OTHER_KEY"))); + + // Assert credential values are NOT in the output (SECURITY) + assert!( + !json_str.contains("secret-value"), + "credential values must not be exposed" + ); + assert!( + !json_str.contains("other-secret"), + "credential values must not be exposed" + ); + } + + #[test] + fn provider_to_json_exposes_config_keys_not_values() { + let mut config = HashMap::new(); + config.insert("region".to_string(), "us-west".to_string()); + config.insert( + "endpoint".to_string(), + "https://api.example.com".to_string(), + ); + + let provider = Provider { + metadata: Some(ObjectMeta::default()), + r#type: "custom".to_string(), + credentials: HashMap::new(), + config, + credential_expires_at_ms: HashMap::new(), + profile_workspace: String::new(), + credential_handles: HashMap::new(), + }; + + let json = provider_to_json(&provider); + let json_str = json.to_string(); + + // Assert config keys are present + let keys = json["config_keys"].as_array().unwrap(); + assert_eq!(keys.len(), 2); + assert!(keys.iter().any(|k| k.as_str() == Some("region"))); + assert!(keys.iter().any(|k| k.as_str() == Some("endpoint"))); + + // Assert config values are NOT in the output (SECURITY) + assert!( + !json_str.contains("us-west"), + "config values must not be exposed" + ); + assert!( + !json_str.contains("https://api.example.com"), + "config values must not be exposed" + ); + } + + #[test] + fn provider_to_json_omits_empty_config() { + let provider = Provider { + metadata: Some(ObjectMeta::default()), + r#type: "anthropic".to_string(), + credentials: HashMap::new(), + config: HashMap::new(), // Empty config + credential_expires_at_ms: HashMap::new(), + profile_workspace: String::new(), + credential_handles: HashMap::new(), + }; + + let json = provider_to_json(&provider); + + assert!( + json.get("config_keys").is_none(), + "empty config_keys should be omitted" + ); + } + + #[test] + fn provider_to_json_includes_metadata_fields_when_present() { + let mut labels = HashMap::new(); + labels.insert("env".to_string(), "prod".to_string()); + + let metadata = ObjectMeta { + id: "prov-123".to_string(), + name: "test-provider".to_string(), + resource_version: 42, + created_at_ms: 1_234_567_890_000, + labels, + annotations: HashMap::new(), + workspace: String::new(), + deletion_timestamp_ms: 0, + }; + + let provider = Provider { + metadata: Some(metadata), + r#type: "anthropic".to_string(), + credentials: HashMap::new(), + config: HashMap::new(), + credential_expires_at_ms: HashMap::new(), + profile_workspace: String::new(), + credential_handles: HashMap::new(), + }; + + let json = provider_to_json(&provider); + + assert_eq!(json["resource_version"], 42); + assert_eq!(json["created_at"], "2009-02-13 23:31:30"); + assert_eq!(json["labels"]["env"], "prod"); + } + + #[test] + fn provider_to_json_omits_zero_metadata_fields() { + let metadata = ObjectMeta { + id: "prov-123".to_string(), + name: "test-provider".to_string(), + // resource_version and created_at_ms are 0 + // labels is empty + ..Default::default() + }; + + let provider = Provider { + metadata: Some(metadata), + r#type: "anthropic".to_string(), + credentials: HashMap::new(), + config: HashMap::new(), + credential_expires_at_ms: HashMap::new(), + profile_workspace: String::new(), + credential_handles: HashMap::new(), + }; + + let json = provider_to_json(&provider); + + assert!( + json.get("resource_version").is_none(), + "zero resource_version should be omitted" + ); + assert!( + json.get("created_at").is_none(), + "zero created_at should be omitted" + ); + assert!( + json.get("labels").is_none(), + "empty labels should be omitted" + ); + } + + #[test] + fn provider_to_json_includes_credential_expiration() { + let mut credential_expires_at_ms = HashMap::new(); + credential_expires_at_ms.insert("ACCESS_TOKEN".to_string(), 1_234_567_890); + + let provider = Provider { + metadata: Some(ObjectMeta::default()), + r#type: "oauth".to_string(), + credentials: HashMap::new(), + config: HashMap::new(), + credential_expires_at_ms, + profile_workspace: String::new(), + credential_handles: HashMap::new(), + }; + + let json = provider_to_json(&provider); + + assert_eq!( + json["credential_expires_at_ms"]["ACCESS_TOKEN"], + 1_234_567_890 + ); + } + + #[test] + fn provider_to_json_formats_created_at_as_human_readable() { + let metadata = ObjectMeta { + id: "prov-123".to_string(), + name: "test-provider".to_string(), + created_at_ms: 1_609_459_200_000, // 2021-01-01 00:00:00 + ..Default::default() + }; + + let provider = Provider { + metadata: Some(metadata), + r#type: "anthropic".to_string(), + credentials: HashMap::new(), + config: HashMap::new(), + credential_expires_at_ms: HashMap::new(), + profile_workspace: String::new(), + credential_handles: HashMap::new(), + }; + + let json = provider_to_json(&provider); + + // Should format as human-readable datetime, not raw milliseconds + assert_eq!(json["created_at"], "2021-01-01 00:00:00"); + assert!( + json.get("created_at_ms").is_none(), + "raw milliseconds field should not exist" + ); + } +} diff --git a/crates/openshell-cli/src/run.rs b/crates/openshell-cli/src/run.rs index 4cd4e34a76..78a794aa30 100644 --- a/crates/openshell-cli/src/run.rs +++ b/crates/openshell-cli/src/run.rs @@ -9,23 +9,33 @@ pub use crate::commands::common::{ }; use crate::commands::common::{ ProvisioningDisplay, ProvisioningStep, confirm_global_setting_delete, - confirm_global_setting_takeover, format_epoch_ms, format_optional_epoch_ms, - format_setting_value, format_timestamp, format_timestamp_ms, handle_platform_progress_event, - is_provisioning_progress_event, non_empty_or, parse_cli_setting_value, - parse_credential_expiry_pairs, parse_credential_pairs, parse_duration_to_ms, phase_name, + confirm_global_setting_takeover, format_epoch_ms, format_setting_value, format_timestamp, + format_timestamp_ms, handle_platform_progress_event, is_provisioning_progress_event, + non_empty_or, parse_cli_setting_value, parse_duration_to_ms, phase_name, print_policy_merge_warnings, print_sandbox_header, print_sandbox_policy, provisioning_timeout_message, ready_false_condition_message, scrub_git_env, short_hash, - truncate_display, truncate_status_field, + truncate_status_field, }; pub use crate::commands::gateway::{ gateway_add, gateway_info, gateway_info_not_configured, gateway_list, gateway_login, gateway_logout, gateway_remove, gateway_select, gateway_status, gateway_use, }; +use crate::commands::provider::inferred_provider_type; +pub use crate::commands::provider::{ + ProviderCreateCredentialSource, ProviderCreateOptions, ProviderRefreshConfigInput, + ProviderUpdateOptions, ensure_required_providers, provider_create, + provider_create_with_options, provider_delete, provider_get, provider_list, + provider_list_profiles, provider_profile_delete, provider_profile_export, + provider_profile_export_text, provider_profile_import, provider_profile_lint, + provider_profile_update, provider_refresh_config, provider_refresh_delete, + provider_refresh_status, provider_rotate, provider_update, sandbox_provider_attach, + sandbox_provider_detach, sandbox_provider_list, +}; + use crate::color::Colorize; use crate::policy_update::build_policy_update_plan; use crate::tls::{TlsOptions, grpc_client, grpc_inference_client}; -use dialoguer::Confirm; use futures::StreamExt; use indicatif::{ProgressBar, ProgressStyle}; use miette::{IntoDiagnostic, Result, WrapErr, miette}; @@ -33,42 +43,28 @@ use openshell_bootstrap::{ GatewayMetadata, clear_last_sandbox_if_matches, get_gateway_metadata, save_last_sandbox, }; use openshell_core::net::set_tcp_nodelay_best_effort; -use openshell_core::proto::ProviderProfileCategory; use openshell_core::proto::{ - ApproveAllDraftChunksRequest, ApproveDraftChunkRequest, AttachSandboxProviderRequest, - ClearDraftChunksRequest, ConfigureProviderRefreshRequest, CreateProviderRequest, + ApproveAllDraftChunksRequest, ApproveDraftChunkRequest, ClearDraftChunksRequest, CreateSandboxRequest, CreateSandboxTemplateRequest, CreateSshSessionRequest, - DeleteInferenceRouteRequest, DeleteProviderProfileRequest, DeleteProviderRefreshRequest, - DeleteProviderRequest, DeleteSandboxRequest, DeleteSandboxTemplateRequest, - DeleteServiceRequest, DetachSandboxProviderRequest, ExecSandboxRequest, ExposeServiceRequest, - GetCurrentUserRequest, GetDraftHistoryRequest, GetDraftPolicyRequest, GetGatewayConfigRequest, - GetInferenceRouteRequest, GetProviderProfileRequest, GetProviderRefreshStatusRequest, - GetProviderRequest, GetSandboxConfigRequest, GetSandboxConfigResponse, GetSandboxLogsRequest, - GetSandboxPolicyStatusRequest, GetSandboxRequest, GetSandboxTemplateRequest, GetServiceRequest, - GpuResourceRequirements, ImportProviderProfilesRequest, LintProviderProfilesRequest, - ListProviderProfilesRequest, ListProvidersRequest, ListSandboxPoliciesRequest, - ListSandboxProvidersRequest, ListSandboxTemplatesRequest, ListSandboxesRequest, - ListServicesRequest, PolicySource, PolicyStatus, Provider, - ProviderCredentialRefreshRecoveryAction, ProviderCredentialRefreshStatus, - ProviderCredentialRefreshStrategy, ProviderCredentialTokenGrantType, ProviderProfile, - ProviderProfileDiagnostic, ProviderProfileImportItem, RejectDraftChunkRequest, - ResourceRequirements, RevokeSshSessionRequest, RotateProviderCredentialRequest, Sandbox, - SandboxPhase, SandboxPolicy, SandboxResources, SandboxServiceLevel, SandboxSpec, - SandboxStartup, SandboxTemplate, SandboxWorkloadConfig, SandboxWorkloadTemplate, - SandboxWorkloadTemplateSpec, ServiceEndpointResponse, SetInferenceRouteRequest, SettingScope, - StartSandboxRequest, StopSandboxRequest, TcpForwardFrame, TcpForwardInit, TcpRelayTarget, - UpdateConfigRequest, UpdateProviderProfilesRequest, UpdateProviderRequest, WatchSandboxRequest, + DeleteInferenceRouteRequest, DeleteSandboxRequest, DeleteSandboxTemplateRequest, + DeleteServiceRequest, ExecSandboxRequest, ExposeServiceRequest, GetCurrentUserRequest, + GetDraftHistoryRequest, GetDraftPolicyRequest, GetGatewayConfigRequest, + GetInferenceRouteRequest, GetSandboxConfigRequest, GetSandboxConfigResponse, + GetSandboxLogsRequest, GetSandboxPolicyStatusRequest, GetSandboxRequest, + GetSandboxTemplateRequest, GetServiceRequest, GpuResourceRequirements, + ListSandboxPoliciesRequest, ListSandboxTemplatesRequest, ListSandboxesRequest, + ListServicesRequest, PolicySource, PolicyStatus, RejectDraftChunkRequest, ResourceRequirements, + RevokeSshSessionRequest, Sandbox, SandboxPhase, SandboxPolicy, SandboxResources, + SandboxServiceLevel, SandboxSpec, SandboxStartup, SandboxTemplate, SandboxWorkloadConfig, + SandboxWorkloadTemplate, SandboxWorkloadTemplateSpec, ServiceEndpointResponse, + SetInferenceRouteRequest, SettingScope, StartSandboxRequest, StopSandboxRequest, + TcpForwardFrame, TcpForwardInit, TcpRelayTarget, UpdateConfigRequest, WatchSandboxRequest, exec_sandbox_event, tcp_forward_init, }; use openshell_core::settings; use openshell_core::{ObjectId, ObjectName, ObjectWorkspace}; -use openshell_providers::{ - ProviderTypeProfile, RealDiscoveryContext, detect_provider_from_command, discover_from_profile, - normalize_profile_id, normalize_provider_type, parse_profile_json, parse_profile_yaml, - profile_to_json, profile_to_yaml, profiles_to_json, profiles_to_yaml, -}; use std::borrow::Cow; -use std::collections::{HashMap, HashSet}; +use std::collections::HashMap; use std::io::{ErrorKind, IsTerminal, Read, Write}; use std::path::{Path, PathBuf}; use std::process::Command; @@ -593,11 +589,11 @@ pub async fn sandbox_create( let main_terminal = tty_override .unwrap_or_else(|| std::io::stdin().is_terminal() && std::io::stdout().is_terminal()); - let main_command = if command.is_empty() { - vec!["/bin/bash".to_string(), "-l".to_string()] - } else { - command.to_vec() - }; + // Forward the command as-is. When empty, the gateway persists it empty and + // the supervisor resolves the default login shell against the sandbox image + // (bash when present, otherwise /bin/sh on minimal images like Alpine). + // Baking a shell here would force a shell the image may not ship. + let main_command = command.to_vec(); let persist = sandbox_should_persist(keep, forward.as_ref()); let create_detaches = detach || (persist @@ -2340,220 +2336,6 @@ fn sandbox_detail_to_json( Ok(value) } -pub async fn sandbox_provider_list( - server: &str, - name: &str, - output: &str, - workspace: &str, - tls: &TlsOptions, -) -> Result<()> { - let mut client = grpc_client(server, tls).await?; - let response = client - .list_sandbox_providers(ListSandboxProvidersRequest { - sandbox_name: name.to_string(), - workspace: workspace.to_string(), - }) - .await - .into_diagnostic()?; - let providers = response.into_inner().providers; - - if crate::output::print_output_collection(output, &providers, attached_provider_to_json)? { - return Ok(()); - } - - if providers.is_empty() { - println!("No providers attached to sandbox {name}."); - return Ok(()); - } - - print_provider_attachment_table(&providers); - Ok(()) -} - -pub async fn sandbox_provider_attach( - server: &str, - name: &str, - provider: &str, - workspace: &str, - tls: &TlsOptions, -) -> Result<()> { - let mut client = grpc_client(server, tls).await?; - - // Fetch current sandbox to get resource_version for CAS - let sandbox = client - .get_sandbox(GetSandboxRequest { - name: name.to_string(), - workspace: workspace.to_string(), - }) - .await - .into_diagnostic()? - .into_inner() - .sandbox - .ok_or_else(|| miette::miette!("sandbox not found"))?; - - let resource_version = sandbox.metadata.as_ref().map_or(0, |m| m.resource_version); - - let response = match client - .attach_sandbox_provider(AttachSandboxProviderRequest { - sandbox_name: name.to_string(), - provider_name: provider.to_string(), - expected_resource_version: resource_version, - workspace: workspace.to_string(), - }) - .await - { - Ok(response) => response.into_inner(), - Err(status) if status.code() == Code::Aborted => { - return Err(miette::miette!( - "Failed to attach provider: sandbox was modified by another operation.\n\ - Please retry the command." - ) - .with_source_code(status.message().to_string())); - } - Err(e) => return Err(e).into_diagnostic(), - }; - - if response.attached { - println!( - "{} Attached provider {} to sandbox {}", - "✓".green().bold(), - provider, - name - ); - } else { - println!("Provider {provider} is already attached to sandbox {name}."); - } - Ok(()) -} - -pub async fn sandbox_provider_detach( - server: &str, - name: &str, - provider: &str, - workspace: &str, - tls: &TlsOptions, -) -> Result<()> { - let mut client = grpc_client(server, tls).await?; - - // Fetch current sandbox to get resource_version for CAS - let sandbox = client - .get_sandbox(GetSandboxRequest { - name: name.to_string(), - workspace: workspace.to_string(), - }) - .await - .into_diagnostic()? - .into_inner() - .sandbox - .ok_or_else(|| miette::miette!("sandbox not found"))?; - - let resource_version = sandbox.metadata.as_ref().map_or(0, |m| m.resource_version); - - let response = match client - .detach_sandbox_provider(DetachSandboxProviderRequest { - sandbox_name: name.to_string(), - provider_name: provider.to_string(), - expected_resource_version: resource_version, - workspace: workspace.to_string(), - }) - .await - { - Ok(response) => response.into_inner(), - Err(status) if status.code() == Code::Aborted => { - return Err(miette::miette!( - "Failed to detach provider: sandbox was modified by another operation.\n\ - Please retry the command." - ) - .with_source_code(status.message().to_string())); - } - Err(e) => return Err(e).into_diagnostic(), - }; - - if response.detached { - println!( - "{} Detached provider {} from sandbox {}", - "✓".green().bold(), - provider, - name - ); - } else { - println!("Provider {provider} was not attached to sandbox {name}."); - } - Ok(()) -} - -fn print_provider_attachment_table(providers: &[Provider]) { - print!("{}", format_provider_attachment_table(providers, true)); -} - -fn attached_provider_to_json(provider: &Provider) -> serde_json::Value { - let mut config_keys = provider.config.keys().cloned().collect::>(); - config_keys.sort(); - - serde_json::json!({ - "name": provider.object_name(), - "type": provider.r#type, - "credential_keys": provider_credential_keys(provider), - "config_keys": config_keys, - }) -} - -fn format_provider_attachment_table(providers: &[Provider], color: bool) -> String { - use std::fmt::Write as _; - - let name_width = providers - .iter() - .map(|provider| provider.object_name().len()) - .max() - .unwrap_or(4) - .max(4); - let type_width = providers - .iter() - .map(|provider| provider.r#type.len()) - .max() - .unwrap_or(4) - .max(4); - - let name_header = if color { - "NAME".bold().to_string() - } else { - "NAME".to_string() - }; - let type_header = if color { - "TYPE".bold().to_string() - } else { - "TYPE".to_string() - }; - let credential_keys_header = if color { - "CREDENTIAL_KEYS".bold().to_string() - } else { - "CREDENTIAL_KEYS".to_string() - }; - let config_keys_header = if color { - "CONFIG_KEYS".bold().to_string() - } else { - "CONFIG_KEYS".to_string() - }; - - let mut output = String::new(); - let _ = writeln!( - output, - "{name_header: Option { - detect_provider_from_command(command).map(str::to_string) -} - -/// Ensure all required providers exist. -/// -/// `explicit_names` are provider **names** supplied via `--provider`. They are -/// passed through directly; the server validates they exist at sandbox creation. -/// -/// `inferred_types` are provider **types** inferred from the trailing command -/// (e.g. `claude` -> type `"claude-code"`). These are resolved to provider names via -/// a type→name lookup, and missing types may be auto-created interactively. -/// -/// Returns a deduplicated list of provider **names** suitable for -/// `SandboxSpec.providers`. -pub async fn ensure_required_providers( - client: &mut crate::tls::GrpcClient, - explicit_names: &[String], - inferred_types: &[String], - auto_providers_override: Option, - workspace: &str, -) -> Result> { - if explicit_names.is_empty() && inferred_types.is_empty() { - return Ok(Vec::new()); - } - - let mut configured_names: Vec = Vec::new(); - let mut seen_names: HashSet = HashSet::new(); - - // ── Fetch all existing providers ───────────────────────────────────── - // Build both a name set (for explicit --provider lookups) and a - // type-to-name map (for inferred provider resolution). - let mut known_names: HashSet = HashSet::new(); - let mut type_to_name: HashMap = HashMap::new(); - { - let mut offset = 0_u32; - let limit = 100_u32; - loop { - let response = client - .list_providers(ListProvidersRequest { - limit, - offset, - workspace: workspace.to_string(), - all_workspaces: false, - }) - .await - .into_diagnostic()?; - let providers = response.into_inner().providers; - for provider in &providers { - known_names.insert(provider.object_name().to_string()); - if !provider.r#type.is_empty() { - let type_lower = provider.r#type.to_ascii_lowercase(); - type_to_name - .entry(type_lower) - .or_insert_with(|| provider.object_name().to_string()); - } - } - if providers.len() < limit as usize { - break; - } - offset = offset.saturating_add(limit); - } - } - - // ── Explicit provider names ────────────────────────────────────────── - // If the name exists on the server, use it directly. Otherwise, if the - // name matches a known provider type, auto-create a provider of that - // type with the requested name. - for name in explicit_names { - if known_names.contains(name) { - if seen_names.insert(name.clone()) { - configured_names.push(name.clone()); - } - } else { - let profile_id = name.trim(); - let profile = fetch_provider_profile(client, profile_id, workspace) - .await - .map_err(|_| { - miette::miette!( - "provider '{name}' not found and no provider profile named '{profile_id}' is available. \ - Create or import the profile first, then create the provider" - ) - })?; - let provider_type = profile.id; - auto_create_provider( - client, - &provider_type, - Some(name), - auto_providers_override, - &mut seen_names, - &mut configured_names, - workspace, - ) - .await?; - // Record the type mapping so the inferred-types pass below - // doesn't attempt to create a duplicate provider. - type_to_name - .entry(provider_type.to_ascii_lowercase()) - .or_insert_with(|| name.clone()); - } - } - - // ── Resolve inferred provider types ────────────────────────────────── - if !inferred_types.is_empty() { - // Collect resolved names for types that already have a provider. - for t in inferred_types { - if let Some(name) = type_to_name.get(&t.to_ascii_lowercase()) - && seen_names.insert(name.clone()) - { - configured_names.push(name.clone()); - } - } - - let missing = inferred_types - .iter() - .filter(|t| !type_to_name.contains_key(&t.to_ascii_lowercase())) - .cloned() - .collect::>(); - - for provider_type in missing { - auto_create_provider( - client, - &provider_type, - None, - auto_providers_override, - &mut seen_names, - &mut configured_names, - workspace, - ) - .await?; - } - } - - Ok(configured_names) -} - -/// Prompt for (or auto-confirm) creation of a provider from local credentials. -/// -/// When `preferred_name` is `Some`, the provider is created with that exact -/// name (used for explicit `--provider ` values). When `None`, the name -/// defaults to the type and retries with suffixes on conflict (used for -/// inferred provider types). -async fn auto_create_provider( - client: &mut crate::tls::GrpcClient, - provider_type: &str, - preferred_name: Option<&str>, - auto_providers_override: Option, - seen_names: &mut HashSet, - configured_names: &mut Vec, - workspace: &str, -) -> Result<()> { - eprintln!("Missing provider: {provider_type}"); - - // --no-auto-providers: skip silently. - if auto_providers_override == Some(false) { - eprintln!( - "{} Skipping provider '{provider_type}' (--no-auto-providers)", - "!".yellow(), - ); - eprintln!(); - return Ok(()); - } - - // No override and non-interactive: error. - if auto_providers_override.is_none() && !std::io::stdin().is_terminal() { - return Err(miette::miette!( - "missing required provider '{provider_type}'. Create it first with \ - `openshell provider create --type {provider_type} --name {provider_type} --from-existing`, \ - pass --auto-providers to auto-create, or set it up manually from inside the sandbox" - )); - } - - // --auto-providers: auto-confirm; otherwise prompt. - let should_create = if auto_providers_override == Some(true) { - true - } else { - Confirm::new() - .with_prompt("Create from local credentials?") - .default(true) - .interact() - .into_diagnostic()? - }; - - if !should_create { - eprintln!("{} Skipping provider '{provider_type}'", "!".yellow()); - eprintln!(); - return Ok(()); - } - - let profile = fetch_provider_profile(client, provider_type, workspace).await?; - let discovered = discover_existing_provider_data(client, provider_type, workspace) - .await - .map_err(|err| miette::miette!("failed to discover provider '{provider_type}': {err}"))?; - let discovered = match discovered { - Some(discovered) => discovered, - None if provider_profile_allows_empty_credentials(&profile) => { - openshell_providers::DiscoveredProvider::default() - } - None => { - return Err(miette::miette!( - "no existing local credentials found for provider profile '{provider_type}'. \ - Create it first with `openshell provider create --type {provider_type} --name {provider_type} --credential `" - )); - } - }; - - if let Some(exact_name) = preferred_name { - // Explicit name: create with exactly that name, no retries. - let request = CreateProviderRequest { - provider: Some(Provider { - metadata: Some(openshell_core::proto::datamodel::v1::ObjectMeta { - id: String::new(), - name: exact_name.to_string(), - created_at_ms: 0, - labels: HashMap::new(), - resource_version: 0, - annotations: HashMap::new(), - workspace: workspace.to_string(), - deletion_timestamp_ms: 0, - }), - r#type: provider_type.to_string(), - credentials: discovered.credentials.clone(), - config: discovered.config.clone(), - credential_expires_at_ms: HashMap::new(), - profile_workspace: workspace.to_string(), - credential_handles: HashMap::new(), - }), - workspace: workspace.to_string(), - }; - - let response = client.create_provider(request).await.map_err(|status| { - miette::miette!("failed to create provider '{exact_name}': {status}") - })?; - let provider = response - .into_inner() - .provider - .ok_or_else(|| miette::miette!("provider missing from response"))?; - eprintln!( - "{} Created provider {} ({}) from existing local state", - "✓".green().bold(), - provider.object_name(), - provider.r#type - ); - if seen_names.insert(provider.object_name().to_string()) { - configured_names.push(provider.object_name().to_string()); - } - } else { - // Inferred type: try type as name, then suffixed variants. - let mut created = false; - for attempt in 0..5 { - let name = if attempt == 0 { - provider_type.to_string() - } else { - format!("{provider_type}-{attempt}") - }; - - let request = CreateProviderRequest { - provider: Some(Provider { - metadata: Some(openshell_core::proto::datamodel::v1::ObjectMeta { - id: String::new(), - name: name.clone(), - created_at_ms: 0, - labels: HashMap::new(), - resource_version: 0, - annotations: HashMap::new(), - workspace: workspace.to_string(), - deletion_timestamp_ms: 0, - }), - r#type: provider_type.to_string(), - credentials: discovered.credentials.clone(), - config: discovered.config.clone(), - credential_expires_at_ms: HashMap::new(), - profile_workspace: workspace.to_string(), - credential_handles: HashMap::new(), - }), - workspace: workspace.to_string(), - }; - - match client.create_provider(request).await { - Ok(response) => { - let provider = response - .into_inner() - .provider - .ok_or_else(|| miette::miette!("provider missing from response"))?; - eprintln!( - "{} Created provider {} ({}) from existing local state", - "✓".green().bold(), - provider.object_name(), - provider.r#type - ); - if seen_names.insert(provider.object_name().to_string()) { - configured_names.push(provider.object_name().to_string()); - } - created = true; - break; - } - Err(status) if status.code() == Code::AlreadyExists => {} - Err(status) => { - return Err(miette::miette!( - "failed to create provider for type '{provider_type}': {status}" - )); - } - } - } - - if !created { - return Err(miette::miette!( - "failed to create provider for type '{provider_type}' after name retries" - )); - } - } - - eprintln!(); - Ok(()) -} - pub async fn service_expose( server: &str, sandbox: &str, @@ -3957,1826 +3422,33 @@ fn service_endpoint_to_json( })) } -fn service_display_name(service: &str) -> &str { - if service.is_empty() { "-" } else { service } -} - -/// Read gcloud Application Default Credentials from disk. -/// -/// Returns `(client_id, client_secret, refresh_token)`. -/// -/// Checks `GOOGLE_APPLICATION_CREDENTIALS` first; falls back to -/// `$CLOUDSDK_CONFIG/application_default_credentials.json` when set, then to -/// `~/.config/gcloud/application_default_credentials.json`. -fn read_gcloud_adc() -> Result<(String, String, String)> { - let path = if let Some(env_path) = std::env::var("GOOGLE_APPLICATION_CREDENTIALS") - .ok() - .filter(|v| !v.is_empty()) - { - PathBuf::from(env_path) - } else if let Some(config_dir) = std::env::var("CLOUDSDK_CONFIG") - .ok() - .filter(|v| !v.is_empty()) - { - PathBuf::from(config_dir).join("application_default_credentials.json") - } else { - let home = std::env::var("HOME") - .map_err(|_| miette::miette!("HOME is not set; cannot locate gcloud ADC file"))?; - PathBuf::from(home) - .join(".config") - .join("gcloud") - .join("application_default_credentials.json") - }; - - let content = std::fs::read_to_string(&path).map_err(|err| { - miette::miette!( - "failed to read gcloud ADC file at {}: {}. \ - Run: gcloud auth application-default login", - path.display(), - err - ) - })?; - - let json: serde_json::Value = serde_json::from_str(&content) - .map_err(|err| miette::miette!("failed to parse gcloud ADC file: {err}"))?; - - let cred_type = json.get("type").and_then(|v| v.as_str()); - match cred_type { - Some("service_account") => { - return Err(miette::miette!( - "Application Default Credentials are a service account key, not user credentials. \ - To use a service account, create the provider with the service account JSON key \ - and configure gateway-managed refresh for 'GOOGLE_VERTEX_AI_SERVICE_ACCOUNT_TOKEN'. \ - See: openshell provider create --help" - )); - } - Some("authorized_user") => {} - Some(other) => { - return Err(miette::miette!( - "Application Default Credentials have unsupported type '{other}' \ - (expected 'authorized_user'). \ - Run: gcloud auth application-default login" - )); - } - None => { - return Err(miette::miette!( - "gcloud ADC file is missing the 'type' field. \ - The file may be malformed. \ - Run: gcloud auth application-default login" - )); - } - } - - let client_id = json - .get("client_id") - .and_then(|v| v.as_str()) - .filter(|s| !s.is_empty()) - .ok_or_else(|| miette::miette!("gcloud ADC file is missing 'client_id'"))? - .to_string(); - - let client_secret = json - .get("client_secret") - .and_then(|v| v.as_str()) - .filter(|s| !s.is_empty()) - .ok_or_else(|| miette::miette!("gcloud ADC file is missing 'client_secret'"))? - .to_string(); - - let refresh_token = json - .get("refresh_token") - .and_then(|v| v.as_str()) - .filter(|s| !s.is_empty()) - .ok_or_else(|| miette::miette!("gcloud ADC file is missing 'refresh_token'"))? - .to_string(); - - Ok((client_id, client_secret, refresh_token)) -} - -async fn rollback_provider_create_after_gcloud_adc_failure( - client: &mut crate::tls::GrpcClient, - provider_name: &str, - stage: &str, - source: &Status, - workspace: &str, -) -> Result<()> { - match client - .delete_provider(DeleteProviderRequest { - name: provider_name.to_string(), - workspace: workspace.to_string(), - }) - .await - { - Ok(_) => Err(miette!( - "failed to {stage} credentials from gcloud ADC for provider '{provider_name}': {source}. \ - The provider was rolled back successfully." - )), - Err(cleanup_err) => { - eprintln!( - "{} Failed to clean up provider '{}' after {} failed: {}. \ - Run 'openshell provider delete {}' to remove it manually.", - "⚠".yellow(), - provider_name, - stage, - cleanup_err, - provider_name - ); - Err(miette!( - "failed to {stage} credentials from gcloud ADC for provider '{provider_name}': {source}. \ - Cleanup also failed, so the provider may still exist. \ - Run 'openshell provider delete {provider_name}' to remove it manually." - )) - } - } -} - -fn service_url_for_gateway(service_url: &str, gateway_endpoint: &str) -> String { - let (Ok(mut service_url), Ok(gateway_endpoint)) = ( - url::Url::parse(service_url), - url::Url::parse(gateway_endpoint), - ) else { - return service_url.to_string(); - }; - - if service_url - .set_port(gateway_endpoint.port_or_known_default()) - .is_err() - { - return service_url.to_string(); - } - - service_url.to_string() -} - -async fn fetch_provider_profile( - client: &mut crate::tls::GrpcClient, - provider_type: &str, - workspace: &str, -) -> Result { - let requested = provider_type.trim(); - let response = match fetch_provider_profile_exact(client, requested, workspace).await { - Ok(response) => response, - Err(status) if status.code() == Code::NotFound => { - let Some(alias) = normalize_provider_type(requested) - .filter(|alias| normalize_profile_id(requested).as_deref() != Some(*alias)) - else { - return Err(miette::miette!( - "provider profile '{requested}' not found; import a matching profile before using this provider type" - )); - }; - fetch_provider_profile_exact(client, alias, workspace) - .await - .map_err(|fallback_status| { - if fallback_status.code() == Code::NotFound { - miette::miette!( - "provider profile '{requested}' not found; import a matching profile before using this provider type" - ) - } else { - miette::miette!(fallback_status.to_string()) - } - })? - } - Err(status) => return Err(miette::miette!(status.to_string())), - }; - - Ok(response) -} - -async fn fetch_provider_profile_exact( - client: &mut crate::tls::GrpcClient, - provider_type: &str, - workspace: &str, -) -> std::result::Result { - client - .get_provider_profile(GetProviderProfileRequest { - id: provider_type.to_string(), - workspace: workspace.to_string(), - }) - .await - .and_then(|response| { - response - .into_inner() - .profile - .ok_or_else(|| Status::internal("provider profile missing from response")) - }) -} - -async fn discover_existing_provider_data( - client: &mut crate::tls::GrpcClient, - provider_type: &str, - workspace: &str, -) -> Result> { - let profile = fetch_provider_profile(client, provider_type, workspace).await?; - let profile = ProviderTypeProfile::from_proto(&profile); - let discovered = discover_from_profile(&profile, &RealDiscoveryContext).map_err(|err| { - miette::miette!("failed to discover existing provider data from profile: {err}") - })?; - - Ok(discovered) -} - -/// Canonical provider type string for Google Vertex AI. -const VERTEX_AI_PROVIDER_TYPE: &str = "google-vertex-ai"; - -/// Canonical provider type string for Google Cloud (GCP APIs). -const GOOGLE_CLOUD_PROVIDER_TYPE: &str = "google-cloud"; - -fn missing_credentials_error(provider_type: &str) -> miette::Report { - if provider_type == VERTEX_AI_PROVIDER_TYPE { - return miette::miette!( - "no credentials resolved for provider type '{provider_type}'. \ - Set GOOGLE_VERTEX_AI_TOKEN, VERTEX_AI_TOKEN, \ - GOOGLE_VERTEX_AI_SERVICE_ACCOUNT_TOKEN, or VERTEX_AI_SERVICE_ACCOUNT_TOKEN; \ - or use --from-gcloud-adc or --from-existing with those env vars set." - ); - } - - if provider_type == GOOGLE_CLOUD_PROVIDER_TYPE { - return miette::miette!( - "no credentials resolved for provider type '{provider_type}'. \ - Set GCP_ADC_ACCESS_TOKEN or GCP_SA_ACCESS_TOKEN; \ - or use --from-gcloud-adc / --from-existing with those env vars set." - ); - } - - miette::miette!( - "no credentials resolved for provider type '{provider_type}'. \ - Use --credential KEY[=VALUE], --runtime-credentials for runtime-resolved profile credentials, or --from-existing \ - with the appropriate env vars set." - ) -} - -async fn provider_credential_from_oidc_token( - credentials: &[String], - profile: Option<&ProviderProfile>, - tls: &TlsOptions, -) -> Result<(HashMap, HashMap)> { - let credential_key = oidc_subject_credential_key(credentials, profile)?; - - let gateway_name = tls.gateway_name().ok_or_else(|| { - miette::miette!("--from-oidc-token requires an active named OIDC gateway") - })?; - let bundle = - crate::oidc_auth::ensure_valid_oidc_token_bundle(gateway_name, tls.gateway_insecure) - .await - .map_err(|err| { - miette::miette!( - "failed to load or refresh OIDC token for gateway '{gateway_name}' while preparing provider credential: {err}" - ) - })?; - - let mut credential_map = HashMap::new(); - credential_map.insert(credential_key.clone(), bundle.access_token); - - let mut credential_expires_at_ms = HashMap::new(); - if let Some(expires_at) = bundle.expires_at { - let expires_at_ms = i64::try_from(expires_at) - .unwrap_or(i64::MAX / 1000) - .saturating_mul(1000); - credential_expires_at_ms.insert(credential_key, expires_at_ms); - } - - Ok((credential_map, credential_expires_at_ms)) -} - -fn oidc_subject_credential_key( - credentials: &[String], - profile: Option<&ProviderProfile>, -) -> Result { - if credentials.len() > 1 { - return Err(miette::miette!( - "--from-oidc-token accepts at most one --credential KEY destination" - )); - } - - if let Some(credential) = credentials.first() { - let credential = credential.trim(); - if credential.is_empty() || credential.contains('=') { - return Err(miette::miette!( - "--from-oidc-token requires --credential KEY without an inline value" - )); - } - if let Some(profile) = profile { - ensure_profile_declares_subject_credential(profile, credential)?; - } - return Ok(credential.to_string()); - } - - let Some(profile) = profile else { - return Err(miette::miette!( - "--from-oidc-token requires --credential KEY when the provider profile is unavailable" - )); - }; - - infer_oidc_subject_credential_from_profile(profile) -} - -fn ensure_profile_declares_subject_credential( - profile: &ProviderProfile, - credential: &str, -) -> Result<()> { - let matches = token_exchange_subject_credentials(profile); - if matches.iter().any(|candidate| candidate == credential) { - return Ok(()); - } - Err(miette::miette!( - "credential '{credential}' is not declared as a token-exchange subject credential in provider profile '{}'; expected one of: {}", - profile.id, - matches.join(", ") - )) -} - -fn infer_oidc_subject_credential_from_profile(profile: &ProviderProfile) -> Result { - let matches = token_exchange_subject_credentials(profile); - match matches.as_slice() { - [credential] => Ok(credential.clone()), - [] => Err(miette::miette!( - "provider profile '{}' does not declare a token-exchange subject credential; pass --credential KEY", - profile.id - )), - _ => Err(miette::miette!( - "provider profile '{}' declares multiple token-exchange subject credentials ({}); pass --credential KEY", - profile.id, - matches.join(", ") - )), - } -} - -fn token_exchange_subject_credentials(profile: &ProviderProfile) -> Vec { - let mut matches = Vec::new(); - for credential in &profile.credentials { - let Some(token_grant) = credential.token_grant.as_ref() else { - continue; - }; - if ProviderCredentialTokenGrantType::try_from(token_grant.grant_type).ok() - != Some(ProviderCredentialTokenGrantType::TokenExchange) - { - continue; - } - let Some(subject_token) = token_grant.subject_token.as_ref() else { - continue; - }; - if subject_token.source != "provider_credential" || subject_token.credential.is_empty() { - continue; - } - if !matches.contains(&subject_token.credential) { - matches.push(subject_token.credential.clone()); - } - } - matches -} - -#[allow(clippy::too_many_arguments)] -pub async fn provider_create( - server: &str, - name: &str, - provider_type: &str, - from_existing: bool, - credentials: &[String], - from_gcloud_adc: bool, - config: &[String], - workspace: &str, - tls: &TlsOptions, -) -> Result<()> { - let credential_source = match (from_existing, from_gcloud_adc) { - (true, true) => { - return Err(miette::miette!( - "--from-gcloud-adc cannot be combined with --from-existing, --from-oidc-token, or --credential; it also cannot be combined with --runtime-credentials" - )); - } - (true, false) => ProviderCreateCredentialSource::Existing, - (false, true) => ProviderCreateCredentialSource::GcloudAdc, - (false, false) => ProviderCreateCredentialSource::ExplicitCredentials, - }; - provider_create_with_options(ProviderCreateOptions { - server, - name, - provider_type, - credentials, - credential_source, - config, - workspace, - profile_workspace: workspace, - tls, - }) - .await -} - -pub struct ProviderCreateOptions<'a> { - pub server: &'a str, - pub name: &'a str, - pub provider_type: &'a str, - pub credentials: &'a [String], - pub credential_source: ProviderCreateCredentialSource, - pub config: &'a [String], - pub workspace: &'a str, - pub profile_workspace: &'a str, - pub tls: &'a TlsOptions, -} - -#[derive(Clone, Copy, Debug, Eq, PartialEq)] -pub enum ProviderCreateCredentialSource { - ExplicitCredentials, - Existing, - GcloudAdc, - OidcToken, - Runtime, -} - -pub async fn provider_create_with_options(options: ProviderCreateOptions<'_>) -> Result<()> { - let ProviderCreateOptions { - server, - name, - provider_type, - credentials, - credential_source, - config, - workspace, - profile_workspace, - tls, - } = options; - - let from_existing = credential_source == ProviderCreateCredentialSource::Existing; - let from_gcloud_adc = credential_source == ProviderCreateCredentialSource::GcloudAdc; - let from_oidc_token = credential_source == ProviderCreateCredentialSource::OidcToken; - let runtime_credentials = credential_source == ProviderCreateCredentialSource::Runtime; - - if from_gcloud_adc && !credentials.is_empty() { - return Err(miette::miette!( - "--from-gcloud-adc cannot be combined with --from-existing, --from-oidc-token, or --credential; it also cannot be combined with --runtime-credentials" - )); - } - if from_existing && !credentials.is_empty() { - return Err(miette::miette!( - "--from-existing cannot be combined with --credential" - )); - } - if runtime_credentials && !credentials.is_empty() { - return Err(miette::miette!( - "--runtime-credentials cannot be combined with --credential" - )); - } - - let mut client = grpc_client(server, tls).await?; - - let profile_id = provider_type.trim(); - if profile_id.is_empty() { - return Err(miette::miette!("provider type is required")); - } - let provider_profile = fetch_provider_profile(&mut client, profile_id, profile_workspace) - .await - .map_err(|err| { - miette::miette!("unsupported provider type or profile: {profile_id} ({err})") - })?; - let provider_type = provider_profile.id.clone(); - - let adc_credential_key = if from_gcloud_adc { - let profile = ProviderTypeProfile::from_proto(&provider_profile); - let adc_cred = profile.adc_credential().ok_or_else(|| { - miette::miette!( - "--from-gcloud-adc is not supported for '{provider_type}' providers \ - (no ADC-compatible credential in the provider profile)" - ) - })?; - Some( - adc_cred - .env_vars - .first() - .ok_or_else(|| { - miette::miette!( - "ADC credential in '{provider_type}' profile has no env_vars declared" - ) - })? - .clone(), - ) - } else { - None - }; - - let oidc_profile = if from_oidc_token { - Some(provider_profile.clone()) - } else { - None - }; - - let (mut credential_map, oidc_credential_expires_at_ms) = if from_oidc_token { - provider_credential_from_oidc_token(credentials, oidc_profile.as_ref(), tls).await? - } else { - (parse_credential_pairs(credentials)?, HashMap::new()) - }; - let mut config_map = parse_key_value_pairs(config, "--config")?; - - if from_existing { - let discovered = - discover_existing_provider_data(&mut client, &provider_type, profile_workspace).await?; - let Some(discovered) = discovered else { - return Err(miette::miette!( - "no existing local credentials/config found for provider type '{provider_type}'" - )); - }; - - for (key, value) in discovered.credentials { - credential_map.entry(key).or_insert(value); - } - for (key, value) in discovered.config { - config_map.entry(key).or_insert(value); - } - } - - if credential_map.is_empty() { - if from_existing { - return Err(missing_credentials_error(&provider_type)); - } - if runtime_credentials && !provider_profile_allows_runtime_credentials(&provider_profile) { - return Err(miette::miette!( - "--runtime-credentials is only valid for provider profiles whose required credentials are resolved at runtime" - )); - } - if !provider_profile_allows_empty_credentials(&provider_profile) { - return Err(missing_credentials_error(&provider_type)); - } - } - - // Validate and read the ADC file BEFORE creating the provider so that - // a bad/missing ADC does not leave an orphan provider behind. Bundle the - // credential key with the material so they stay coupled. - let gcloud_adc_bootstrap = if from_gcloud_adc { - let (client_id, client_secret, refresh_token) = read_gcloud_adc()?; - let key = adc_credential_key.expect("set when from_gcloud_adc is true"); - Some((key, client_id, client_secret, refresh_token)) - } else { - None - }; - - let response = client - .create_provider(CreateProviderRequest { - provider: Some(Provider { - metadata: Some(openshell_core::proto::datamodel::v1::ObjectMeta { - id: String::new(), - name: name.to_string(), - created_at_ms: 0, - labels: HashMap::new(), - resource_version: 0, - annotations: HashMap::new(), - workspace: workspace.to_string(), - deletion_timestamp_ms: 0, - }), - r#type: provider_type.clone(), - credentials: credential_map, - config: config_map, - credential_expires_at_ms: oidc_credential_expires_at_ms, - profile_workspace: profile_workspace.to_string(), - credential_handles: HashMap::new(), - }), - workspace: workspace.to_string(), - }) - .await - .into_diagnostic()?; - - let provider = response - .into_inner() - .provider - .ok_or_else(|| miette::miette!("provider missing from response"))?; - let provider_name = provider.object_name().to_string(); - - if let Some((adc_credential_key, client_id, client_secret, refresh_token)) = - gcloud_adc_bootstrap - { - let mut material = HashMap::new(); - material.insert("client_id".to_string(), client_id); - material.insert("client_secret".to_string(), client_secret); - material.insert("refresh_token".to_string(), refresh_token); - - if let Err(configure_err) = client - .configure_provider_refresh(ConfigureProviderRefreshRequest { - provider: provider_name.clone(), - credential_key: adc_credential_key.clone(), - strategy: ProviderCredentialRefreshStrategy::Oauth2RefreshToken as i32, - material, - secret_material_keys: vec![ - "client_secret".to_string(), - "refresh_token".to_string(), - ], - expires_at_ms: None, - workspace: workspace.to_string(), - }) - .await - { - return rollback_provider_create_after_gcloud_adc_failure( - &mut client, - &provider_name, - "configure", - &configure_err, - workspace, - ) - .await; - } - - if let Err(rotate_err) = client - .rotate_provider_credential(RotateProviderCredentialRequest { - provider: provider_name.clone(), - credential_key: adc_credential_key, - workspace: workspace.to_string(), - }) - .await - { - return rollback_provider_create_after_gcloud_adc_failure( - &mut client, - &provider_name, - "mint the initial access token for", - &rotate_err, - workspace, - ) - .await; - } - - println!("{} Created provider {}", "✓".green().bold(), provider_name); - println!("Configured GCP credentials from gcloud ADC and minted the initial access token"); - return Ok(()); - } - - println!("{} Created provider {}", "✓".green().bold(), provider_name); - Ok(()) -} - -fn provider_profile_allows_empty_credentials(profile: &ProviderProfile) -> bool { - ProviderTypeProfile::from_proto(profile).allows_empty_provider_credentials() -} - -fn provider_profile_allows_runtime_credentials(profile: &ProviderProfile) -> bool { - ProviderTypeProfile::from_proto(profile).allows_runtime_provider_credentials() -} - -pub async fn provider_get( - server: &str, - name: &str, - workspace: &str, - tls: &TlsOptions, -) -> Result<()> { - let mut client = grpc_client(server, tls).await?; - let response = client - .get_provider(GetProviderRequest { - name: name.to_string(), - workspace: workspace.to_string(), - }) - .await - .into_diagnostic()?; - - let provider = response - .into_inner() - .provider - .ok_or_else(|| miette::miette!("provider missing from response"))?; - - let credential_keys = provider_credential_keys(&provider); - let config_keys = provider.config.keys().cloned().collect::>(); - - println!("{}", "Provider:".cyan().bold()); - println!(); - println!(" {} {}", "Id:".dimmed(), provider.object_id()); - println!(" {} {}", "Name:".dimmed(), provider.object_name()); - println!(" {} {}", "Type:".dimmed(), provider.r#type); - println!( - " {} {}", - "Resource version:".dimmed(), - provider.metadata.as_ref().map_or(0, |m| m.resource_version) - ); - println!( - " {} {}", - "Credential keys:".dimmed(), - if credential_keys.is_empty() { - "".to_string() - } else { - credential_keys.join(", ") - } - ); - println!( - " {} {}", - "Config keys:".dimmed(), - if config_keys.is_empty() { - "".to_string() - } else { - config_keys.join(", ") - } - ); - - Ok(()) -} - -fn provider_to_json(provider: &Provider) -> serde_json::Value { - let mut obj = serde_json::Map::new(); - - // Core fields - obj.insert("id".to_string(), serde_json::json!(provider.object_id())); - obj.insert( - "name".to_string(), - serde_json::json!(provider.object_name()), - ); - obj.insert( - "workspace".to_string(), - serde_json::json!(provider.object_workspace()), - ); - obj.insert("type".to_string(), serde_json::json!(provider.r#type)); - - // Credential keys (NEVER values - security) - let credential_keys = provider_credential_keys(provider); - obj.insert( - "credential_keys".to_string(), - serde_json::json!(credential_keys), - ); - - // Config keys (keys only, not values) - if !provider.config.is_empty() { - let config_keys: Vec = provider.config.keys().cloned().collect(); - obj.insert("config_keys".to_string(), serde_json::json!(config_keys)); - } - - // Metadata fields (only if metadata exists) - if let Some(meta) = &provider.metadata { - if !meta.labels.is_empty() { - obj.insert("labels".to_string(), serde_json::json!(meta.labels)); - } - if meta.resource_version != 0 { - obj.insert( - "resource_version".to_string(), - serde_json::json!(meta.resource_version), - ); - } - if meta.created_at_ms != 0 { - obj.insert( - "created_at".to_string(), - serde_json::json!(format_epoch_ms(meta.created_at_ms)), - ); - } - } - - // Credential expiration times (only if present) - if !provider.credential_expires_at_ms.is_empty() { - obj.insert( - "credential_expires_at_ms".to_string(), - serde_json::json!(provider.credential_expires_at_ms), - ); - } - - serde_json::Value::Object(obj) -} - -fn provider_credential_keys(provider: &Provider) -> Vec { - let mut keys: Vec = provider - .credentials - .keys() - .chain(provider.credential_handles.keys()) - .cloned() - .collect(); - keys.sort(); - keys.dedup(); - keys -} - -#[allow(clippy::too_many_arguments)] -pub async fn provider_list( - server: &str, - limit: u32, - offset: u32, - names_only: bool, - output: &str, - workspace: &str, - all_workspaces: bool, - tls: &TlsOptions, -) -> Result<()> { - let mut client = grpc_client(server, tls).await?; - let response = client - .list_providers(ListProvidersRequest { - limit, - offset, - workspace: if all_workspaces { - String::new() - } else { - workspace.to_string() - }, - all_workspaces, - }) - .await - .into_diagnostic()?; - let providers = response.into_inner().providers; - - // Handle structured output formats (json, yaml) - if crate::output::print_output_collection(output, &providers, provider_to_json)? { - return Ok(()); - } - - if providers.is_empty() { - if !names_only { - println!("No providers found."); - } - return Ok(()); - } - - if names_only { - for provider in &providers { - if all_workspaces { - println!("{}/{}", provider.object_workspace(), provider.object_name()); - } else { - println!("{}", provider.object_name()); - } - } - return Ok(()); - } - - let ws_width = if all_workspaces { - providers - .iter() - .map(|p| p.object_workspace().len()) - .max() - .unwrap_or(9) - .max(9) - } else { - 0 - }; - let name_width = providers - .iter() - .map(|provider| provider.object_name().len()) - .max() - .unwrap_or(4) - .max(4); - let type_width = providers - .iter() - .map(|provider| provider.r#type.len()) - .max() - .unwrap_or(4) - .max(4); - - if all_workspaces { - println!( - "{: Result<()> { - let mut client = grpc_client(server, tls).await?; - let response = client - .list_provider_profiles(ListProviderProfilesRequest { - limit: 100, - offset: 0, - workspace: workspace.to_string(), - }) - .await - .into_diagnostic()?; - let mut profiles = response.into_inner().profiles; - profiles.sort_by(|left, right| { - left.category - .cmp(&right.category) - .then_with(|| left.id.cmp(&right.id)) - }); - let dto_profiles = profiles - .iter() - .map(ProviderTypeProfile::from_proto) - .collect::>(); - - if crate::output::print_output_direct( - output, - || profiles_to_json(&dto_profiles).into_diagnostic(), - || profiles_to_yaml(&dto_profiles).into_diagnostic(), - )? { - return Ok(()); - } - - if profiles.is_empty() { - println!("No provider profiles found."); - return Ok(()); - } - - println!("{}", "Available Provider Profiles:".cyan().bold()); - let id_width = provider_profile_id_width(&profiles); - let display_width = provider_profile_display_width(&profiles); - let source_width = provider_profile_source_width(&profiles); - let scope_width = provider_profile_scope_width(&profiles); - let mut current_category = i32::MIN; - for profile in &profiles { - if profile.category != current_category { - current_category = profile.category; - println!(); - println!(" {}", display_provider_category(current_category).bold()); - print_provider_type_header(id_width, scope_width, source_width, display_width); - } - print_provider_type_row(profile, id_width, scope_width, source_width, display_width); - } - - Ok(()) -} - -pub async fn provider_profile_export( - server: &str, - id: &str, - output: &str, - workspace: &str, - tls: &TlsOptions, -) -> Result<()> { - let rendered = provider_profile_export_text(server, id, output, workspace, tls).await?; - if output == "json" { - println!("{rendered}"); - } else { - print!("{rendered}"); - } - Ok(()) -} - -pub async fn provider_profile_export_text( - server: &str, - id: &str, - output: &str, - workspace: &str, - tls: &TlsOptions, -) -> Result { - let mut client = grpc_client(server, tls).await?; - let response = client - .get_provider_profile(GetProviderProfileRequest { - id: id.to_string(), - workspace: workspace.to_string(), - }) - .await - .into_diagnostic()?; - let profile = response - .into_inner() - .profile - .ok_or_else(|| miette!("provider profile '{id}' not found"))?; - let profile = ProviderTypeProfile::from_proto(&profile); - - match output { - "json" => profile_to_json(&profile).into_diagnostic(), - "yaml" => profile_to_yaml(&profile).into_diagnostic(), - "table" => Err(miette!( - "profile export supports '-o yaml' and '-o json'; table output is not supported" - )), - _ => Err(miette!("unsupported output format: {output}")), - } -} - -pub async fn provider_profile_import( - server: &str, - file: Option<&Path>, - from: Option<&Path>, - workspace: &str, - tls: &TlsOptions, -) -> Result<()> { - let (items, mut diagnostics) = load_profile_import_items(file, from)?; - if items.is_empty() && diagnostics.is_empty() { - return Err(miette!("no provider profile files found")); - } - if profile_diagnostics_have_errors(&diagnostics) { - print_profile_diagnostics(&diagnostics); - return Err(miette!("provider profile import failed")); - } - - let mut client = grpc_client(server, tls).await?; - if !items.is_empty() { - let response = client - .import_provider_profiles(ImportProviderProfilesRequest { - profiles: items, - workspace: workspace.to_string(), - }) - .await - .into_diagnostic()? - .into_inner(); - diagnostics.extend(response.diagnostics); - if response.imported { - println!( - "Imported {} provider profile{}.", - response.profiles.len(), - if response.profiles.len() == 1 { - "" - } else { - "s" - } - ); - return Ok(()); - } - } - - print_profile_diagnostics(&diagnostics); - Err(miette!("provider profile import failed")) -} - -pub async fn provider_profile_update( - server: &str, - id: &str, - file: &Path, - workspace: &str, - tls: &TlsOptions, -) -> Result<()> { - let (mut items, mut diagnostics) = load_profile_import_items(Some(file), None)?; - if items.is_empty() && diagnostics.is_empty() { - return Err(miette!("no provider profile files found")); - } - if profile_diagnostics_have_errors(&diagnostics) { - print_profile_diagnostics(&diagnostics); - return Err(miette!("provider profile update failed")); - } - - let mut client = grpc_client(server, tls).await?; - if let Some(item) = items.pop() { - let expected_resource_version = item - .profile - .as_ref() - .map_or(0, |profile| profile.resource_version); - let response = client - .update_provider_profiles(UpdateProviderProfilesRequest { - profile: Some(item), - expected_resource_version, - id: id.to_string(), - workspace: workspace.to_string(), - }) - .await - .into_diagnostic()? - .into_inner(); - diagnostics.extend(response.diagnostics); - if response.updated { - println!("Updated provider profile."); - return Ok(()); - } - } - - print_profile_diagnostics(&diagnostics); - Err(miette!("provider profile update failed")) -} - -pub async fn provider_profile_lint( - server: &str, - file: Option<&Path>, - from: Option<&Path>, - workspace: &str, - tls: &TlsOptions, -) -> Result<()> { - let (items, mut diagnostics) = load_profile_import_items(file, from)?; - if items.is_empty() && diagnostics.is_empty() { - return Err(miette!("no provider profile files found")); - } - - if !items.is_empty() { - let mut client = grpc_client(server, tls).await?; - let response = client - .lint_provider_profiles(LintProviderProfilesRequest { - profiles: items, - workspace: workspace.to_string(), - }) - .await - .into_diagnostic()? - .into_inner(); - diagnostics.extend(response.diagnostics); - } - - if profile_diagnostics_have_errors(&diagnostics) { - print_profile_diagnostics(&diagnostics); - return Err(miette!("provider profile lint failed")); - } - - println!("Provider profile lint passed."); - Ok(()) -} - -pub async fn provider_profile_delete( - server: &str, - ids: &[String], - workspace: &str, - tls: &TlsOptions, -) -> Result<()> { - let mut client = grpc_client(server, tls).await?; - let mut failures = Vec::new(); - for id in ids { - let response = match client - .delete_provider_profile(DeleteProviderProfileRequest { - id: id.clone(), - workspace: workspace.to_string(), - }) - .await - { - Ok(response) => response.into_inner(), - Err(status) => { - eprintln!( - "{} Failed to delete provider profile {id}: {status}", - "!".red().bold() - ); - failures.push(id.clone()); - continue; - } - }; - if response.deleted { - println!("{} Deleted provider profile {id}", "✓".green().bold()); - } else { - println!("{} Provider profile {id} not found", "!".yellow()); - } - } - aggregate_delete_failures("provider profile", &failures) -} - -pub async fn provider_refresh_status( - server: &str, - name: &str, - credential_key: Option<&str>, - workspace: &str, - tls: &TlsOptions, -) -> Result<()> { - let mut client = grpc_client(server, tls).await?; - let response = client - .get_provider_refresh_status(GetProviderRefreshStatusRequest { - provider: name.to_string(), - credential_key: credential_key.unwrap_or_default().to_string(), - workspace: workspace.to_string(), - }) - .await - .into_diagnostic()? - .into_inner(); - - if response.credentials.is_empty() { - if let Some(credential_key) = credential_key { - println!( - "No refresh configuration found for provider '{name}' credential '{credential_key}'." - ); - } else { - println!("No refresh configurations found for provider '{name}'."); - } - return Ok(()); - } - - println!("{}", refresh_status_header()); - for status in response.credentials { - print_refresh_status_row(&status); - } - Ok(()) -} - -fn refresh_status_header() -> String { - format!( - "{:<24} {:<28} {:<28} {:<24} {:<18} {:<20} {:<20} {:<20} {:<44} {}", - "PROVIDER".bold(), - "CREDENTIAL_KEY".bold(), - "STRATEGY".bold(), - "STATUS".bold(), - "RECOVERY".bold(), - "EXPIRES_AT".bold(), - "NEXT_REFRESH".bold(), - "LAST_REFRESH".bold(), - "FAILURE_CODE".bold(), - "LAST_ERROR".bold(), - ) -} - -pub struct ProviderRefreshConfigInput<'a> { - pub name: &'a str, - pub credential_key: &'a str, - pub strategy: &'a str, - pub material: &'a [String], - pub secret_material_env: &'a [String], - pub secret_material_keys: &'a [String], - pub credential_expires_at_ms: Option, -} - -pub async fn provider_refresh_config( - server: &str, - input: ProviderRefreshConfigInput<'_>, - workspace: &str, - tls: &TlsOptions, -) -> Result<()> { - let strategy = provider_refresh_strategy(input.strategy)?; - let mut material = parse_key_value_pairs(input.material, "--material")?; - let mut secret_material_keys = input.secret_material_keys.to_vec(); - // Env-resolved secrets are auto-marked secret; duplicate keys are an - // error rather than a precedence order. - for (key, value) in parse_secret_material_env_pairs(input.secret_material_env)? { - if material.contains_key(&key) { - return Err(miette!( - "duplicate material key '{key}': supplied via both --material and --secret-material-env" - )); - } - if !secret_material_keys.contains(&key) { - secret_material_keys.push(key.clone()); - } - material.insert(key, value); - } - let mut client = grpc_client(server, tls).await?; - let status = client - .configure_provider_refresh(ConfigureProviderRefreshRequest { - provider: input.name.to_string(), - credential_key: input.credential_key.to_string(), - strategy: strategy as i32, - material, - secret_material_keys, - expires_at_ms: input.credential_expires_at_ms, - workspace: workspace.to_string(), - }) - .await - .into_diagnostic()? - .into_inner() - .status - .ok_or_else(|| miette!("provider refresh status missing from response"))?; - - println!( - "{} Configured refresh for {} {}", - "✓".green().bold(), - status.provider_name, - status.credential_key - ); - Ok(()) -} - -pub async fn provider_rotate( - server: &str, - name: &str, - credential_key: &str, - workspace: &str, - tls: &TlsOptions, -) -> Result<()> { - let mut client = grpc_client(server, tls).await?; - let status = client - .rotate_provider_credential(RotateProviderCredentialRequest { - provider: name.to_string(), - credential_key: credential_key.to_string(), - workspace: workspace.to_string(), - }) - .await - .into_diagnostic()? - .into_inner() - .status - .ok_or_else(|| miette!("provider refresh status missing from response"))?; - - if status.last_error.is_empty() { - println!( - "{} Rotation requested for {} {} ({})", - "✓".green().bold(), - status.provider_name, - status.credential_key, - status.status - ); - } else { - println!( - "Rotation request recorded for {} {} ({}): {}", - status.provider_name, status.credential_key, status.status, status.last_error - ); - } - Ok(()) -} - -pub async fn provider_refresh_delete( - server: &str, - name: &str, - credential_key: &str, - workspace: &str, - tls: &TlsOptions, -) -> Result<()> { - let mut client = grpc_client(server, tls).await?; - let response = client - .delete_provider_refresh(DeleteProviderRefreshRequest { - provider: name.to_string(), - credential_key: credential_key.to_string(), - workspace: workspace.to_string(), - }) - .await - .into_diagnostic()? - .into_inner(); - - if response.deleted { - println!( - "{} Deleted refresh config for {} {}", - "✓".green().bold(), - name, - credential_key - ); - } else { - println!("No refresh config found for provider '{name}' credential '{credential_key}'."); - } - Ok(()) -} - -fn provider_refresh_strategy(strategy: &str) -> Result { - match strategy { - "oauth2_refresh_token" => Ok(ProviderCredentialRefreshStrategy::Oauth2RefreshToken), - "oauth2_client_credentials" => { - Ok(ProviderCredentialRefreshStrategy::Oauth2ClientCredentials) - } - "google_service_account_jwt" => { - Ok(ProviderCredentialRefreshStrategy::GoogleServiceAccountJwt) - } - "aws_sts_assume_role" => Ok(ProviderCredentialRefreshStrategy::AwsStsAssumeRole), - _ => Err(miette!("unsupported provider refresh strategy: {strategy}")), - } -} - -fn print_refresh_status_row(status: &ProviderCredentialRefreshStatus) { - println!("{}", refresh_status_row(status)); -} - -fn refresh_status_row(status: &ProviderCredentialRefreshStatus) -> String { - let strategy = ProviderCredentialRefreshStrategy::try_from(status.strategy) - .unwrap_or(ProviderCredentialRefreshStrategy::Unspecified); - let recovery_action = ProviderCredentialRefreshRecoveryAction::try_from(status.recovery_action) - .unwrap_or(ProviderCredentialRefreshRecoveryAction::Unspecified); - format!( - "{:<24} {:<28} {:<28} {:<24} {:<18} {:<20} {:<20} {:<20} {:<44} {}", - status.provider_name, - status.credential_key, - provider_refresh_strategy_name(strategy), - status.status, - provider_refresh_recovery_action_name(recovery_action), - format_optional_epoch_ms(status.expires_at_ms), - format_refresh_next_at_ms(status.next_refresh_at_ms), - format_optional_epoch_ms(status.last_refresh_at_ms), - status.failure_code, - truncate_status_field(&status.last_error, 72), - ) -} - -fn format_refresh_next_at_ms(next_refresh_at_ms: i64) -> String { - if next_refresh_at_ms == i64::MAX { - "-".to_string() - } else { - format_optional_epoch_ms(next_refresh_at_ms) - } -} - -fn provider_refresh_recovery_action_name( - action: ProviderCredentialRefreshRecoveryAction, -) -> &'static str { - match action { - ProviderCredentialRefreshRecoveryAction::Retry => "retry", - ProviderCredentialRefreshRecoveryAction::Reauthorize => "reauthorize", - ProviderCredentialRefreshRecoveryAction::FixConfiguration => "fix_configuration", - ProviderCredentialRefreshRecoveryAction::Investigate => "investigate", - ProviderCredentialRefreshRecoveryAction::Unspecified => "-", - } -} - -fn provider_refresh_strategy_name(strategy: ProviderCredentialRefreshStrategy) -> &'static str { - match strategy { - ProviderCredentialRefreshStrategy::Static => "static", - ProviderCredentialRefreshStrategy::External => "external", - ProviderCredentialRefreshStrategy::Oauth2RefreshToken => "oauth2_refresh_token", - ProviderCredentialRefreshStrategy::Oauth2ClientCredentials => "oauth2_client_credentials", - ProviderCredentialRefreshStrategy::GoogleServiceAccountJwt => "google_service_account_jwt", - ProviderCredentialRefreshStrategy::AwsStsAssumeRole => "aws_sts_assume_role", - ProviderCredentialRefreshStrategy::Unspecified => "unspecified", - } -} - -fn load_profile_import_items( - file: Option<&Path>, - from: Option<&Path>, -) -> Result<( - Vec, - Vec, -)> { - let paths = profile_source_paths(file, from)?; - let mut items = Vec::new(); - let mut diagnostics = Vec::new(); - for path in paths { - match load_profile_import_item(&path) { - Ok(item) => items.push(item), - Err(diagnostic) => diagnostics.push(diagnostic), - } - } - Ok((items, diagnostics)) -} - -fn profile_source_paths(file: Option<&Path>, from: Option<&Path>) -> Result> { - if let Some(file) = file { - return Ok(vec![file.to_path_buf()]); - } - let Some(from) = from else { - return Ok(Vec::new()); - }; - let mut paths = Vec::new(); - for entry in std::fs::read_dir(from) - .into_diagnostic() - .wrap_err_with(|| format!("failed to read profile directory {}", from.display()))? - { - let entry = entry.into_diagnostic()?; - let path = entry.path(); - if path.is_file() && profile_extension_supported(&path) { - paths.push(path); - } - } - paths.sort(); - Ok(paths) -} - -fn profile_extension_supported(path: &Path) -> bool { - matches!( - path.extension().and_then(|ext| ext.to_str()), - Some("yaml" | "yml" | "json") - ) -} - -fn load_profile_import_item( - path: &Path, -) -> Result { - let source = path.display().to_string(); - let input = std::fs::read_to_string(path).map_err(|err| { - profile_file_diagnostic( - &source, - format!("failed to read provider profile file: {err}"), - ) - })?; - let profile = match path.extension().and_then(|ext| ext.to_str()) { - Some("yaml" | "yml") => parse_profile_yaml(&input), - Some("json") => parse_profile_json(&input), - _ => { - return Err(profile_file_diagnostic( - &source, - "unsupported provider profile file format".to_string(), - )); - } - } - .map_err(|err| profile_file_diagnostic(&source, err.to_string()))?; - - let pre_lower = profile.validate_before_lowering(&source); - if let Some(diag) = pre_lower.into_iter().find(|d| d.severity == "error") { - return Err(ProviderProfileDiagnostic { - source: diag.source, - profile_id: diag.profile_id, - field: diag.field, - message: diag.message, - severity: diag.severity, - }); - } - - Ok(ProviderProfileImportItem { - profile: Some(profile.to_proto()), - source, - }) -} - -fn profile_file_diagnostic(source: &str, message: String) -> ProviderProfileDiagnostic { - ProviderProfileDiagnostic { - source: source.to_string(), - profile_id: String::new(), - field: "file".to_string(), - message, - severity: "error".to_string(), - } -} - -fn print_profile_diagnostics(diagnostics: &[ProviderProfileDiagnostic]) { - if diagnostics.is_empty() { - return; - } - eprintln!("{}", "Provider profile diagnostics:".red().bold()); - for diagnostic in diagnostics { - let source = if diagnostic.source.is_empty() { - "" - } else { - &diagnostic.source - }; - let profile = if diagnostic.profile_id.is_empty() { - "-".to_string() - } else { - diagnostic.profile_id.clone() - }; - eprintln!( - " {} {} profile={} field={} {}", - diagnostic.severity.as_str().red(), - source, - profile, - diagnostic.field, - diagnostic.message - ); - } -} - -fn profile_diagnostics_have_errors(diagnostics: &[ProviderProfileDiagnostic]) -> bool { - diagnostics - .iter() - .any(|diagnostic| diagnostic.severity == "error") -} - -fn display_provider_category(category: i32) -> &'static str { - match ProviderProfileCategory::try_from(category).unwrap_or(ProviderProfileCategory::Other) { - ProviderProfileCategory::Inference => "INFERENCE", - ProviderProfileCategory::Agent => "AGENT", - ProviderProfileCategory::SourceControl => "SOURCE CONTROL", - ProviderProfileCategory::Messaging => "MESSAGING", - ProviderProfileCategory::Data => "DATA", - ProviderProfileCategory::Knowledge => "KNOWLEDGE", - ProviderProfileCategory::Other | ProviderProfileCategory::Unspecified => "OTHER", - } -} - -const PROVIDER_PROFILE_ID_MAX_WIDTH: usize = 32; -const PROVIDER_PROFILE_DISPLAY_MAX_WIDTH: usize = 40; -const PROVIDER_PROFILE_SOURCE_MAX_WIDTH: usize = 24; - -fn provider_profile_id_width(profiles: &[ProviderProfile]) -> usize { - profiles - .iter() - .map(|profile| { - profile - .id - .chars() - .count() - .min(PROVIDER_PROFILE_ID_MAX_WIDTH) - }) - .max() - .unwrap_or(2) - .max(2) -} - -fn provider_profile_display_width(profiles: &[ProviderProfile]) -> usize { - profiles - .iter() - .map(|profile| { - profile - .display_name - .chars() - .count() - .min(PROVIDER_PROFILE_DISPLAY_MAX_WIDTH) - }) - .max() - .unwrap_or(4) - .max(4) -} - -fn provider_profile_scope_width(profiles: &[ProviderProfile]) -> usize { - profiles - .iter() - .map(|profile| profile.scope.chars().count()) - .max() - .unwrap_or(5) - .max(5) -} - -fn provider_profile_source_width(profiles: &[ProviderProfile]) -> usize { - profiles - .iter() - .map(|profile| { - profile - .source - .chars() - .count() - .min(PROVIDER_PROFILE_SOURCE_MAX_WIDTH) - }) - .max() - .unwrap_or(6) - .max(6) -} - -fn print_provider_type_header( - id_width: usize, - scope_width: usize, - source_width: usize, - display_width: usize, -) { - let endpoints = "ENDPOINTS"; - println!( - " {: { - pub server: &'a str, - pub name: &'a str, - pub from_existing: bool, - pub from_oidc_token: bool, - pub credentials: &'a [String], - pub config: &'a [String], - pub credential_expires_at: &'a [String], - pub workspace: &'a str, - pub tls: &'a TlsOptions, -} - -pub async fn provider_update(options: ProviderUpdateOptions<'_>) -> Result<()> { - let ProviderUpdateOptions { - server, - name, - from_existing, - from_oidc_token, - credentials, - config, - credential_expires_at, - workspace, - tls, - } = options; - - if from_existing && !credentials.is_empty() { - return Err(miette::miette!( - "--from-existing cannot be combined with --credential" - )); - } - if from_existing && from_oidc_token { - return Err(miette::miette!( - "--from-existing cannot be combined with --from-oidc-token" - )); - } - - let mut client = grpc_client(server, tls).await?; - - // Look up the stored provider so the update can carry its type and profile - // workspace. Policy interceptors evaluate the request before the gateway - // merges it with stored state, so an update that omits them cannot be - // authorized against the profile that owns the provider. - // - // The read is best-effort. A caller holding `provider:write` without - // `provider:read` must still be able to rotate credentials, so a denied - // read keeps the previous behavior of sending empty metadata rather than - // failing the update. `--from-existing` and `--from-oidc-token` need the - // stored type, so they surface the error instead. - let existing = match client - .get_provider(GetProviderRequest { - name: name.to_string(), - workspace: workspace.to_string(), - }) - .await - { - Ok(response) => response.into_inner().provider, - Err(status) - if status.code() == Code::PermissionDenied && !from_existing && !from_oidc_token => - { - None - } - Err(status) => return Err(status).into_diagnostic(), - }; - - if existing.is_none() && (from_existing || from_oidc_token) { - return Err(miette::miette!("provider '{name}' not found")); - } - - let oidc_profile = if from_oidc_token { - let existing = existing.as_ref().expect("checked above"); - Some( - fetch_provider_profile(&mut client, &existing.r#type, &existing.profile_workspace) - .await?, - ) - } else { - None - }; - - let (mut credential_map, oidc_credential_expires_at_ms) = if from_oidc_token { - provider_credential_from_oidc_token(credentials, oidc_profile.as_ref(), tls).await? - } else { - (parse_credential_pairs(credentials)?, HashMap::new()) - }; - let mut config_map = parse_key_value_pairs(config, "--config")?; - let mut credential_expires_at_ms = parse_credential_expiry_pairs(credential_expires_at)?; - credential_expires_at_ms.extend(oidc_credential_expires_at_ms); - - if from_existing { - let stored = existing.as_ref().expect("checked above"); - let provider_type = stored.r#type.clone(); - let discovered = - discover_existing_provider_data(&mut client, &provider_type, &stored.profile_workspace) - .await?; - let Some(discovered) = discovered else { - return Err(miette::miette!( - "no existing local credentials/config found for provider type '{provider_type}'" - )); - }; - - for (key, value) in discovered.credentials { - credential_map.entry(key).or_insert(value); - } - for (key, value) in discovered.config { - config_map.entry(key).or_insert(value); - } - } - - let response = client - .update_provider(UpdateProviderRequest { - provider: Some(Provider { - metadata: Some(openshell_core::proto::datamodel::v1::ObjectMeta { - id: String::new(), - name: name.to_string(), - created_at_ms: 0, - labels: HashMap::new(), - resource_version: 0, - annotations: HashMap::new(), - workspace: workspace.to_string(), - deletion_timestamp_ms: 0, - }), - r#type: existing - .as_ref() - .map(|provider| provider.r#type.clone()) - .unwrap_or_default(), - credentials: credential_map, - config: config_map, - credential_expires_at_ms: HashMap::new(), - profile_workspace: existing - .as_ref() - .map(|provider| provider.profile_workspace.clone()) - .unwrap_or_default(), - credential_handles: HashMap::new(), - }), - credential_expires_at_ms, - workspace: workspace.to_string(), - }) - .await - .into_diagnostic()?; - - let provider = response - .into_inner() - .provider - .ok_or_else(|| miette::miette!("provider missing from response"))?; - - println!( - "{} Updated provider {}", - "✓".green().bold(), - provider.object_name() - ); - Ok(()) -} - -pub async fn provider_delete( - server: &str, - names: &[String], - workspace: &str, - tls: &TlsOptions, -) -> Result<()> { - let mut client = grpc_client(server, tls).await?; - let mut failures = Vec::new(); - for name in names { - let response = match client - .delete_provider(DeleteProviderRequest { - name: name.clone(), - workspace: workspace.to_string(), - }) - .await - { - Ok(response) => response, - Err(status) => { - eprintln!( - "{} Failed to delete provider {name}: {status}", - "!".red().bold() - ); - failures.push(name.clone()); - continue; - } - }; - if response.into_inner().deleted { - println!("{} Deleted provider {name}", "✓".green().bold()); - } else { - println!("{} Provider {name} not found", "!".yellow()); - } +fn service_display_name(service: &str) -> &str { + if service.is_empty() { "-" } else { service } +} + +/// Read gcloud Application Default Credentials from disk. +/// +/// Returns `(client_id, client_secret, refresh_token)`. +/// +/// Checks `GOOGLE_APPLICATION_CREDENTIALS` first; falls back to +/// `$CLOUDSDK_CONFIG/application_default_credentials.json` when set, then to +/// `~/.config/gcloud/application_default_credentials.json`. +fn service_url_for_gateway(service_url: &str, gateway_endpoint: &str) -> String { + let (Ok(mut service_url), Ok(gateway_endpoint)) = ( + url::Url::parse(service_url), + url::Url::parse(gateway_endpoint), + ) else { + return service_url.to_string(); + }; + + if service_url + .set_port(gateway_endpoint.port_or_known_default()) + .is_err() + { + return service_url.to_string(); } - aggregate_delete_failures("provider", &failures) + + service_url.to_string() } // --------------------------------------------------------------------------- @@ -8293,22 +5965,20 @@ fn format_endpoint(endpoint: &openshell_core::proto::NetworkEndpoint) -> String #[cfg(test)] mod tests { use super::{ - PolicyGetView, ProvisioningStep, attached_provider_to_json, build_sandbox_resource_limits, - dockerfile_sources_supported_for_gateway, format_endpoint, format_log_line, - format_provider_attachment_table, git_sync_files, has_main_process_result, - inferred_provider_type, parse_cli_setting_value, parse_credential_expiry_cli_value, - parse_credential_expiry_pairs, parse_credential_pairs, parse_driver_config_json, - parse_secret_material_env_pairs, policy_revision_list_json, policy_revision_to_json, - provider_profile_allows_empty_credentials, provisioning_timeout_message, - ready_false_condition_message, refresh_status_header, refresh_status_row, resolve_from, - sandbox_should_persist, sandbox_upload_plan, service_endpoint_to_json, + PolicyGetView, ProvisioningStep, build_sandbox_resource_limits, + dockerfile_sources_supported_for_gateway, format_endpoint, format_log_line, git_sync_files, + has_main_process_result, parse_cli_setting_value, parse_credential_expiry_cli_value, + parse_driver_config_json, parse_secret_material_env_pairs, policy_revision_list_json, + policy_revision_to_json, provisioning_timeout_message, ready_false_condition_message, + resolve_from, sandbox_should_persist, sandbox_upload_plan, service_endpoint_to_json, service_expose_status_error, service_url_for_gateway, workspace_member_to_json, }; use crate::TEST_ENV_LOCK; - use crate::commands::common::progress_step_from_metadata; + use crate::commands::common::{ + parse_credential_expiry_pairs, parse_credential_pairs, progress_step_from_metadata, + }; use crate::test_utils::EnvVarGuard; use std::fs; - use std::io::Write; use std::path::Path; use std::process::Command; use tonic::Status; @@ -8319,10 +5989,7 @@ mod tests { PROGRESS_STEP_STARTING_SANDBOX, }; use openshell_core::proto::{ - CredentialHandle, GetSandboxConfigResponse, GpuResourceRequirements, PolicySource, - PolicyStatus, Provider, ProviderCredentialRefresh, ProviderCredentialRefreshRecoveryAction, - ProviderCredentialRefreshStatus, ProviderCredentialRefreshStrategy, - ProviderCredentialTokenGrant, ProviderProfile, ProviderProfileCredential, + GetSandboxConfigResponse, GpuResourceRequirements, PolicySource, PolicyStatus, ResourceRequirements, Sandbox, SandboxCondition, SandboxPhase, SandboxPolicy, SandboxPolicyRevision, SandboxResources, SandboxStatus, SandboxWorkloadConfig, SandboxWorkloadTemplate, SandboxWorkloadTemplateProvenance, SandboxWorkloadTemplateSpec, @@ -8410,68 +6077,6 @@ mod tests { assert!(unknown[0].get("sandbox").is_none()); } - #[test] - fn attached_provider_json_is_sorted_and_secret_safe() { - let provider = Provider { - metadata: Some(ObjectMeta { - name: "github".to_string(), - ..Default::default() - }), - r#type: "github".to_string(), - credentials: std::collections::HashMap::from([ - ("Z_TOKEN".to_string(), "inline-secret".to_string()), - ("SHARED".to_string(), "shared-secret".to_string()), - ]), - config: std::collections::HashMap::from([ - ("Z_URL".to_string(), "https://secret.example".to_string()), - ("A_MODE".to_string(), "sensitive-config".to_string()), - ]), - credential_expires_at_ms: std::collections::HashMap::from([( - "Z_TOKEN".to_string(), - 123, - )]), - profile_workspace: "internal".to_string(), - credential_handles: std::collections::HashMap::from([ - ( - "A_HANDLE".to_string(), - CredentialHandle { - driver: "vault".to_string(), - handle: "opaque-secret-handle".to_string(), - metadata: std::collections::HashMap::from([( - "internal".to_string(), - "metadata-value".to_string(), - )]), - }, - ), - ("SHARED".to_string(), CredentialHandle::default()), - ]), - }; - - let value = attached_provider_to_json(&provider); - assert_eq!( - value, - serde_json::json!({ - "name": "github", - "type": "github", - "credential_keys": ["A_HANDLE", "SHARED", "Z_TOKEN"], - "config_keys": ["A_MODE", "Z_URL"], - }) - ); - let serialized = value.to_string(); - for secret in [ - "inline-secret", - "shared-secret", - "https://secret.example", - "sensitive-config", - "opaque-secret-handle", - "metadata-value", - "internal", - "123", - ] { - assert!(!serialized.contains(secret), "leaked {secret}"); - } - } - #[test] fn service_endpoint_json_has_raw_fields_and_normalized_url() { let response = ServiceEndpointResponse { @@ -8675,43 +6280,6 @@ mod tests { assert_eq!(parsed, 1_767_225_600_000); } - #[test] - fn provider_attachment_table_formats_provider_counts() { - let output = format_provider_attachment_table( - &[Provider { - metadata: Some(ObjectMeta { - name: "work-custom".to_string(), - ..Default::default() - }), - r#type: "custom-api".to_string(), - credentials: [ - ("CUSTOM_API_KEY".to_string(), "REDACTED".to_string()), - ("CUSTOM_API_SECRET".to_string(), "REDACTED".to_string()), - ] - .into_iter() - .collect(), - config: std::iter::once(( - "BASE_URL".to_string(), - "https://api.custom.example".to_string(), - )) - .collect(), - credential_expires_at_ms: std::collections::HashMap::new(), - profile_workspace: String::new(), - credential_handles: std::collections::HashMap::new(), - }], - false, - ); - - assert!(output.contains("NAME")); - assert!(output.contains("TYPE")); - assert!(output.contains("CREDENTIAL_KEYS")); - assert!(output.contains("CONFIG_KEYS")); - assert!(output.contains("work-custom")); - assert!(output.contains("custom-api")); - assert!(output.contains('2')); - assert!(output.contains('1')); - } - #[test] fn progress_step_metadata_values_map_to_cli_steps() { assert_eq!( @@ -8729,118 +6297,6 @@ mod tests { assert_eq!(progress_step_from_metadata("driver-private-step"), None); } - #[test] - fn refresh_status_table_includes_operational_fields() { - let header = refresh_status_header(); - assert!(header.contains("NEXT_REFRESH")); - assert!(header.contains("LAST_REFRESH")); - assert!(header.contains("RECOVERY")); - assert!(header.contains("FAILURE_CODE")); - assert!(header.contains("LAST_ERROR")); - - let row = refresh_status_row(&ProviderCredentialRefreshStatus { - provider_name: "my-graph".to_string(), - provider_id: "provider-id".to_string(), - credential_key: "MS_GRAPH_ACCESS_TOKEN".to_string(), - strategy: ProviderCredentialRefreshStrategy::Oauth2ClientCredentials as i32, - status: "error".to_string(), - expires_at_ms: 1_767_225_600_000, - next_refresh_at_ms: i64::MAX, - last_refresh_at_ms: 1_767_225_000_000, - last_error: "token endpoint returned a very long error message that should be truncated for table readability" - .to_string(), - recovery_action: ProviderCredentialRefreshRecoveryAction::Reauthorize as i32, - failure_code: "oauth_rotated_refresh_token_handle_missing".to_string(), - provider_error_subtype: "invalid_rapt".to_string(), - last_error_at_ms: 1_767_225_000_000, - }); - - assert!(row.contains("my-graph")); - assert!(row.contains("MS_GRAPH_ACCESS_TOKEN")); - assert!(row.contains("oauth2_client_credentials")); - assert!(row.contains("error")); - assert!(row.contains("reauthorize")); - assert!(row.contains("oauth_rotated_refresh_token_handle_missing")); - assert!(row.contains("2026-01-01 00:00:00")); - assert!(!row.contains("292278994")); - assert!(row.contains("...")); - } - - #[test] - fn empty_provider_credentials_require_all_required_credentials_to_be_runtime_resolvable() { - let refresh_token_profile = ProviderProfile { - credentials: vec![ProviderProfileCredential { - name: "MS_GRAPH_ACCESS_TOKEN".to_string(), - required: true, - refresh: Some(ProviderCredentialRefresh { - strategy: ProviderCredentialRefreshStrategy::Oauth2RefreshToken as i32, - ..Default::default() - }), - ..Default::default() - }], - ..Default::default() - }; - assert!(provider_profile_allows_empty_credentials( - &refresh_token_profile - )); - - let token_grant_profile = ProviderProfile { - credentials: vec![ProviderProfileCredential { - name: "ACCESS_TOKEN".to_string(), - required: true, - token_grant: Some(ProviderCredentialTokenGrant { - token_endpoint: "https://auth.example.com/token".to_string(), - ..Default::default() - }), - ..Default::default() - }], - ..Default::default() - }; - assert!(provider_profile_allows_empty_credentials( - &token_grant_profile - )); - - let mixed_static_profile = ProviderProfile { - credentials: vec![ - ProviderProfileCredential { - name: "ACCESS_TOKEN".to_string(), - required: true, - refresh: Some(ProviderCredentialRefresh { - strategy: ProviderCredentialRefreshStrategy::Oauth2ClientCredentials as i32, - ..Default::default() - }), - ..Default::default() - }, - ProviderProfileCredential { - name: "STATIC_API_KEY".to_string(), - required: true, - refresh: None, - ..Default::default() - }, - ], - ..Default::default() - }; - assert!(!provider_profile_allows_empty_credentials( - &mixed_static_profile - )); - - let optional_refresh_profile = ProviderProfile { - credentials: vec![ProviderProfileCredential { - name: "OPTIONAL_TOKEN".to_string(), - required: false, - refresh: Some(ProviderCredentialRefresh { - strategy: ProviderCredentialRefreshStrategy::GoogleServiceAccountJwt as i32, - ..Default::default() - }), - ..Default::default() - }], - ..Default::default() - }; - assert!(provider_profile_allows_empty_credentials( - &optional_refresh_profile - )); - } - #[test] fn parse_cli_setting_value_parses_bool_aliases() { let yes_value = parse_cli_setting_value("ocsf_json_enabled", "yes").expect("parse yes"); @@ -8971,42 +6427,6 @@ mod tests { ); } - #[test] - fn inferred_provider_type_returns_type_for_known_command() { - let result = inferred_provider_type(&["claude".to_string(), "--help".to_string()]); - assert_eq!(result, Some("claude-code".to_string())); - } - - #[test] - fn inferred_provider_type_returns_none_for_unknown_command() { - let result = inferred_provider_type(&["bash".to_string()]); - assert_eq!(result, None); - } - - #[test] - fn inferred_provider_type_returns_none_for_empty_command() { - let result = inferred_provider_type(&[]); - assert_eq!(result, None); - } - - #[test] - fn inferred_provider_type_normalizes_aliases() { - // Retired legacy types are not inferred, even when a custom profile - // with the same ID could be imported and attached explicitly. - let result = inferred_provider_type(&["glab".to_string()]); - assert_eq!(result, None); - - // `gh` should resolve to `github` - let result = inferred_provider_type(&["gh".to_string()]); - assert_eq!(result, Some("github".to_string())); - } - - #[test] - fn inferred_provider_type_handles_full_path() { - let result = inferred_provider_type(&["/usr/local/bin/claude".to_string()]); - assert_eq!(result, Some("claude-code".to_string())); - } - #[test] fn sandbox_should_persist_defaults_to_persistent() { assert!(sandbox_should_persist(true, None)); @@ -9490,306 +6910,6 @@ mod tests { ); } - #[test] - fn read_gcloud_adc_missing_file_errors() { - let _lock = TEST_ENV_LOCK - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - let _guard = EnvVarGuard::set( - "GOOGLE_APPLICATION_CREDENTIALS", - "/nonexistent/path/to/adc.json", - ); - let err = super::read_gcloud_adc().expect_err("missing file should error"); - assert!( - err.to_string().contains("failed to read gcloud ADC file"), - "unexpected error: {err}" - ); - } - - #[test] - fn read_gcloud_adc_wrong_type_errors() { - let _lock = TEST_ENV_LOCK - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - let tmp = tempfile::NamedTempFile::new().expect("tempfile"); - let json = serde_json::json!({ - "type": "service_account", - "project_id": "my-project", - "private_key_id": "key123" - }); - Write::write_all(&mut tmp.as_file(), json.to_string().as_bytes()).expect("write tempfile"); - let _guard = EnvVarGuard::set( - "GOOGLE_APPLICATION_CREDENTIALS", - tmp.path().to_str().expect("tempfile path"), - ); - let err = super::read_gcloud_adc().expect_err("wrong type should error"); - // The service_account type gets a targeted message directing the user - // to the real Vertex service-account credential flow instead of the - // generic authorized_user hint. - assert!( - err.to_string() - .contains("GOOGLE_VERTEX_AI_SERVICE_ACCOUNT_TOKEN"), - "error should mention the service-account token key, got: {err}" - ); - } - - #[test] - fn read_gcloud_adc_parses_user_creds() { - let _lock = TEST_ENV_LOCK - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - let tmp = tempfile::NamedTempFile::new().expect("tempfile"); - let json = serde_json::json!({ - "type": "authorized_user", - "client_id": "test-client-id.apps.googleusercontent.com", - "client_secret": "test-client-secret", - "refresh_token": "test-refresh-token" - }); - Write::write_all(&mut tmp.as_file(), json.to_string().as_bytes()).expect("write tempfile"); - let _guard = EnvVarGuard::set( - "GOOGLE_APPLICATION_CREDENTIALS", - tmp.path().to_str().expect("tempfile path"), - ); - let (client_id, client_secret, refresh_token) = - super::read_gcloud_adc().expect("valid ADC should parse"); - assert_eq!(client_id, "test-client-id.apps.googleusercontent.com"); - assert_eq!(client_secret, "test-client-secret"); - assert_eq!(refresh_token, "test-refresh-token"); - } - - #[test] - fn read_gcloud_adc_uses_cloudsdk_config_fallback() { - let _lock = TEST_ENV_LOCK - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - let dir = tempfile::tempdir().expect("tempdir"); - let adc_path = dir.path().join("application_default_credentials.json"); - let json = serde_json::json!({ - "type": "authorized_user", - "client_id": "cloudsdk-client-id.apps.googleusercontent.com", - "client_secret": "cloudsdk-client-secret", - "refresh_token": "cloudsdk-refresh-token" - }); - fs::write(&adc_path, json.to_string()).expect("write adc file"); - let _adc_guard = EnvVarGuard::unset("GOOGLE_APPLICATION_CREDENTIALS"); - let _cloudsdk_guard = - EnvVarGuard::set("CLOUDSDK_CONFIG", dir.path().to_str().expect("config path")); - - let (client_id, client_secret, refresh_token) = - super::read_gcloud_adc().expect("valid CLOUDSDK_CONFIG ADC should parse"); - assert_eq!(client_id, "cloudsdk-client-id.apps.googleusercontent.com"); - assert_eq!(client_secret, "cloudsdk-client-secret"); - assert_eq!(refresh_token, "cloudsdk-refresh-token"); - } - - #[test] - fn read_gcloud_adc_malformed_json_errors() { - let _lock = TEST_ENV_LOCK - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - let tmp = tempfile::NamedTempFile::new().expect("tempfile"); - Write::write_all(&mut tmp.as_file(), b"not valid json at all {{{{") - .expect("write tempfile"); - let _guard = EnvVarGuard::set( - "GOOGLE_APPLICATION_CREDENTIALS", - tmp.path().to_str().expect("tempfile path"), - ); - let result = super::read_gcloud_adc(); - assert!( - result.is_err(), - "malformed JSON should produce an error, got: {result:?}" - ); - let err = result.unwrap_err(); - let msg = format!("{err}"); - assert!( - msg.contains("parse") - || msg.contains("JSON") - || msg.contains("json") - || msg.contains("invalid") - || msg.contains("failed"), - "error message should mention parse/JSON failure, got: {msg}" - ); - } - - #[test] - fn empty_provider_credentials_allow_oauth2_refresh_token() { - use openshell_core::proto::{ - ProviderCredentialRefresh, ProviderCredentialRefreshStrategy, ProviderProfile, - ProviderProfileCredential, - }; - - let strategy = ProviderCredentialRefreshStrategy::Oauth2RefreshToken as i32; - let profile = ProviderProfile { - credentials: vec![ProviderProfileCredential { - required: true, - refresh: Some(ProviderCredentialRefresh { - strategy, - ..Default::default() - }), - ..Default::default() - }], - ..Default::default() - }; - assert!( - provider_profile_allows_empty_credentials(&profile), - "Oauth2RefreshToken should be allowed for refresh bootstrap" - ); - } - - #[test] - fn provider_to_json_includes_core_fields() { - let metadata = ObjectMeta { - id: "prov-123".to_string(), - name: "test-provider".to_string(), - ..Default::default() - }; - - let provider = Provider { - metadata: Some(metadata), - r#type: "anthropic".to_string(), - credentials: std::collections::HashMap::new(), - config: std::collections::HashMap::new(), - credential_expires_at_ms: std::collections::HashMap::new(), - profile_workspace: String::new(), - credential_handles: std::collections::HashMap::new(), - }; - - let json = super::provider_to_json(&provider); - - assert_eq!(json["id"], "prov-123"); - assert_eq!(json["name"], "test-provider"); - assert_eq!(json["workspace"], ""); - assert_eq!(json["type"], "anthropic"); - } - - #[test] - fn provider_to_json_exposes_credential_keys_not_values() { - let mut credentials = std::collections::HashMap::new(); - credentials.insert("ANTHROPIC_API_KEY".to_string(), "secret-value".to_string()); - credentials.insert("OTHER_KEY".to_string(), "other-secret".to_string()); - - let provider = Provider { - metadata: Some(ObjectMeta::default()), - r#type: "anthropic".to_string(), - credentials, - config: std::collections::HashMap::new(), - credential_expires_at_ms: std::collections::HashMap::new(), - profile_workspace: String::new(), - credential_handles: std::collections::HashMap::new(), - }; - - let json = super::provider_to_json(&provider); - let json_str = json.to_string(); - - // Assert credential keys are present - let keys = json["credential_keys"].as_array().unwrap(); - assert_eq!(keys.len(), 2); - assert!(keys.iter().any(|k| k.as_str() == Some("ANTHROPIC_API_KEY"))); - assert!(keys.iter().any(|k| k.as_str() == Some("OTHER_KEY"))); - - // Assert credential values are NOT in the output (SECURITY) - assert!( - !json_str.contains("secret-value"), - "credential values must not be exposed" - ); - assert!( - !json_str.contains("other-secret"), - "credential values must not be exposed" - ); - } - - #[test] - fn provider_to_json_exposes_config_keys_not_values() { - let mut config = std::collections::HashMap::new(); - config.insert("region".to_string(), "us-west".to_string()); - config.insert( - "endpoint".to_string(), - "https://api.example.com".to_string(), - ); - - let provider = Provider { - metadata: Some(ObjectMeta::default()), - r#type: "custom".to_string(), - credentials: std::collections::HashMap::new(), - config, - credential_expires_at_ms: std::collections::HashMap::new(), - profile_workspace: String::new(), - credential_handles: std::collections::HashMap::new(), - }; - - let json = super::provider_to_json(&provider); - let json_str = json.to_string(); - - // Assert config keys are present - let keys = json["config_keys"].as_array().unwrap(); - assert_eq!(keys.len(), 2); - assert!(keys.iter().any(|k| k.as_str() == Some("region"))); - assert!(keys.iter().any(|k| k.as_str() == Some("endpoint"))); - - // Assert config values are NOT in the output (SECURITY) - assert!( - !json_str.contains("us-west"), - "config values must not be exposed" - ); - assert!( - !json_str.contains("https://api.example.com"), - "config values must not be exposed" - ); - } - - #[test] - fn provider_to_json_omits_empty_config() { - let provider = Provider { - metadata: Some(ObjectMeta::default()), - r#type: "anthropic".to_string(), - credentials: std::collections::HashMap::new(), - config: std::collections::HashMap::new(), // Empty config - credential_expires_at_ms: std::collections::HashMap::new(), - profile_workspace: String::new(), - credential_handles: std::collections::HashMap::new(), - }; - - let json = super::provider_to_json(&provider); - - assert!( - json.get("config_keys").is_none(), - "empty config_keys should be omitted" - ); - } - - #[test] - fn provider_to_json_includes_metadata_fields_when_present() { - let mut labels = std::collections::HashMap::new(); - labels.insert("env".to_string(), "prod".to_string()); - - let metadata = ObjectMeta { - id: "prov-123".to_string(), - name: "test-provider".to_string(), - resource_version: 42, - created_at_ms: 1_234_567_890_000, - labels, - annotations: std::collections::HashMap::new(), - workspace: String::new(), - deletion_timestamp_ms: 0, - }; - - let provider = Provider { - metadata: Some(metadata), - r#type: "anthropic".to_string(), - credentials: std::collections::HashMap::new(), - config: std::collections::HashMap::new(), - credential_expires_at_ms: std::collections::HashMap::new(), - profile_workspace: String::new(), - credential_handles: std::collections::HashMap::new(), - }; - - let json = super::provider_to_json(&provider); - - assert_eq!(json["resource_version"], 42); - assert_eq!(json["created_at"], "2009-02-13 23:31:30"); - assert_eq!(json["labels"]["env"], "prod"); - } - #[test] fn sandbox_template_to_json_includes_metadata_labels_and_annotations() { let template = SandboxWorkloadTemplate { @@ -9858,94 +6978,6 @@ mod tests { assert_eq!(json["resources"]["gpu"], 2); } - #[test] - fn provider_to_json_omits_zero_metadata_fields() { - let metadata = ObjectMeta { - id: "prov-123".to_string(), - name: "test-provider".to_string(), - // resource_version and created_at_ms are 0 - // labels is empty - ..Default::default() - }; - - let provider = Provider { - metadata: Some(metadata), - r#type: "anthropic".to_string(), - credentials: std::collections::HashMap::new(), - config: std::collections::HashMap::new(), - credential_expires_at_ms: std::collections::HashMap::new(), - profile_workspace: String::new(), - credential_handles: std::collections::HashMap::new(), - }; - - let json = super::provider_to_json(&provider); - - assert!( - json.get("resource_version").is_none(), - "zero resource_version should be omitted" - ); - assert!( - json.get("created_at").is_none(), - "zero created_at should be omitted" - ); - assert!( - json.get("labels").is_none(), - "empty labels should be omitted" - ); - } - - #[test] - fn provider_to_json_includes_credential_expiration() { - let mut credential_expires_at_ms = std::collections::HashMap::new(); - credential_expires_at_ms.insert("ACCESS_TOKEN".to_string(), 1_234_567_890); - - let provider = Provider { - metadata: Some(ObjectMeta::default()), - r#type: "oauth".to_string(), - credentials: std::collections::HashMap::new(), - config: std::collections::HashMap::new(), - credential_expires_at_ms, - profile_workspace: String::new(), - credential_handles: std::collections::HashMap::new(), - }; - - let json = super::provider_to_json(&provider); - - assert_eq!( - json["credential_expires_at_ms"]["ACCESS_TOKEN"], - 1_234_567_890 - ); - } - - #[test] - fn provider_to_json_formats_created_at_as_human_readable() { - let metadata = ObjectMeta { - id: "prov-123".to_string(), - name: "test-provider".to_string(), - created_at_ms: 1_609_459_200_000, // 2021-01-01 00:00:00 - ..Default::default() - }; - - let provider = Provider { - metadata: Some(metadata), - r#type: "anthropic".to_string(), - credentials: std::collections::HashMap::new(), - config: std::collections::HashMap::new(), - credential_expires_at_ms: std::collections::HashMap::new(), - profile_workspace: String::new(), - credential_handles: std::collections::HashMap::new(), - }; - - let json = super::provider_to_json(&provider); - - // Should format as human-readable datetime, not raw milliseconds - assert_eq!(json["created_at"], "2021-01-01 00:00:00"); - assert!( - json.get("created_at_ms").is_none(), - "raw milliseconds field should not exist" - ); - } - #[test] fn sandbox_detail_to_json_includes_policy_fields() { let mut sandbox = Sandbox { diff --git a/crates/openshell-core/src/lib.rs b/crates/openshell-core/src/lib.rs index 03ae8a30fd..7acb72dd6f 100644 --- a/crates/openshell-core/src/lib.rs +++ b/crates/openshell-core/src/lib.rs @@ -45,6 +45,7 @@ pub mod provider_credentials; pub mod sandbox_env; pub mod secrets; pub mod settings; +pub mod shell; pub mod spiffe; pub mod telemetry; pub mod time; diff --git a/crates/openshell-core/src/sandbox_env.rs b/crates/openshell-core/src/sandbox_env.rs index 99ac55fe6e..2ce8e4b058 100644 --- a/crates/openshell-core/src/sandbox_env.rs +++ b/crates/openshell-core/src/sandbox_env.rs @@ -38,6 +38,9 @@ const MAIN_PROCESS_SPEC_BASE64URL_PREFIX: &str = "base64url:"; #[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] pub struct MainProcessConfig { pub version: u32, + /// Canonical command. Empty means "no command supplied": the supervisor + /// resolves the default login shell against the sandbox image. A non-empty + /// command is the exact program+args and is run verbatim. pub command: Vec, pub tty: bool, #[serde(default)] @@ -47,11 +50,15 @@ pub struct MainProcessConfig { impl MainProcessConfig { pub const VERSION: u32 = 1; + /// Default config for a sandbox created without a command. The command is + /// left empty on purpose: the supervisor picks a login shell that exists in + /// the sandbox image (bash when present, otherwise `/bin/sh`). A TTY is + /// requested because the default is an interactive login shell. #[must_use] pub fn scratch() -> Self { Self { version: Self::VERSION, - command: vec!["/bin/bash".to_string(), "-l".to_string()], + command: Vec::new(), tty: true, await_main_process_attachment: false, } @@ -91,8 +98,13 @@ impl MainProcessConfig { config.version )); } - if config.command.is_empty() || config.command[0].is_empty() { - return Err(format!("{MAIN_PROCESS_SPEC} command must not be empty")); + // An empty command is valid: it means "no command supplied", and the + // supervisor resolves the default login shell. Only a present-but-blank + // program is rejected. + if !config.command.is_empty() && config.command[0].is_empty() { + return Err(format!( + "{MAIN_PROCESS_SPEC} command program must not be empty" + )); } Ok(config) } @@ -283,4 +295,40 @@ mod tests { let encoded = serde_json::to_string(&config).unwrap(); assert_eq!(MainProcessConfig::decode(&encoded).unwrap(), config); } + + #[test] + fn omitted_command_stays_empty_for_supervisor_resolution() { + // No command supplied → empty command; the supervisor resolves the + // default login shell against the sandbox image. + let empty = crate::proto::compute::v1::DriverSandboxSpec::default(); + assert!( + MainProcessConfig::from_driver_spec(Some(&empty)) + .command + .is_empty() + ); + assert!(MainProcessConfig::from_driver_spec(None).command.is_empty()); + + // An explicit command is preserved verbatim and never rewritten. + let explicit = crate::proto::compute::v1::DriverSandboxSpec { + command: vec!["/bin/bash".into(), "-l".into()], + tty: true, + ..Default::default() + }; + assert_eq!( + MainProcessConfig::from_driver_spec(Some(&explicit)).command, + vec!["/bin/bash".to_string(), "-l".to_string()] + ); + + // An empty command survives the transport round-trip. + let encoded = serde_json::to_string(&MainProcessConfig::scratch()).unwrap(); + assert!( + MainProcessConfig::decode(&encoded) + .unwrap() + .command + .is_empty() + ); + + // A present-but-blank program is still rejected. + assert!(MainProcessConfig::decode(r#"{"version":1,"command":[""],"tty":false}"#).is_err()); + } } diff --git a/crates/openshell-core/src/shell.rs b/crates/openshell-core/src/shell.rs new file mode 100644 index 0000000000..09610afe1a --- /dev/null +++ b/crates/openshell-core/src/shell.rs @@ -0,0 +1,107 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Login-shell resolution for sandbox images. +//! +//! The default sandbox command and the interactive SSH session need a shell, +//! but not every base image ships the same one. Debian-based images provide +//! `bash`; minimal images such as Alpine only provide `/bin/sh` (`BusyBox` +//! `ash`). Hard-coding `/bin/bash` makes sandbox startup fail on those images +//! with an opaque `No such file or directory`. +//! +//! These helpers resolve a shell that actually exists in the current root +//! filesystem. They must run inside the sandbox (i.e. in the supervisor), not +//! on the gateway, because the answer depends on the sandbox image's contents. + +/// Preferred interactive shell when the image provides it. +pub const BASH: &str = "/bin/bash"; + +/// Preferred interactive shell on `usr`-merged images where `/bin` is not a +/// top-level directory. +pub const USR_BASH: &str = "/usr/bin/bash"; + +/// POSIX shell. Guaranteed on virtually every image, including Alpine/`BusyBox`. +/// Used as the ultimate fallback. +pub const POSIX_SH: &str = "/bin/sh"; + +/// Shell paths tried, in preference order, by [`detect_login_shell`]. +pub const SHELL_CANDIDATES: &[&str] = &[BASH, USR_BASH, POSIX_SH]; + +/// Return `true` if `path` is a regular, executable file in the current root +/// filesystem. +#[must_use] +pub fn is_executable(path: &str) -> bool { + let Ok(meta) = std::fs::metadata(path) else { + return false; + }; + if !meta.is_file() { + return false; + } + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + meta.permissions().mode() & 0o111 != 0 + } + #[cfg(not(unix))] + { + true + } +} + +/// Resolve a login shell that exists in the current root filesystem. +/// +/// Tries [`SHELL_CANDIDATES`] in order and falls back to [`POSIX_SH`]. Because +/// this inspects the filesystem, call it from the supervisor (inside the +/// sandbox), never on the gateway. +/// +/// `$SHELL` is intentionally not consulted: it is image/user-controlled, the +/// result is later invoked with `-lc`, and an executable that is not a +/// compatible shell (e.g. `SHELL=/bin/false`) would pass the executable check +/// yet break command execution. Resolving only from known shell paths avoids +/// that footgun. +#[must_use] +pub fn detect_login_shell() -> String { + SHELL_CANDIDATES + .iter() + .find(|candidate| is_executable(candidate)) + .map_or_else( + || POSIX_SH.to_string(), + |candidate| (*candidate).to_string(), + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + // These assume a Unix root filesystem (`/bin/sh`, POSIX permission bits) and + // are skipped on the Windows workspace lane where openshell-core also builds. + #[cfg(unix)] + #[test] + fn posix_sh_exists_on_test_host() { + // /bin/sh is present on all supported Unix CI hosts (Linux and macOS). + assert!(is_executable(POSIX_SH)); + } + + #[test] + fn missing_path_is_not_executable() { + assert!(!is_executable("/nonexistent/definitely/not/here")); + } + + #[cfg(unix)] + #[test] + fn non_file_is_not_executable() { + // A directory is not an executable shell. + assert!(!is_executable("/")); + } + + #[cfg(unix)] + #[test] + fn detect_returns_an_executable_shell() { + let shell = detect_login_shell(); + assert!( + is_executable(&shell), + "detected shell {shell} is not executable" + ); + } +} diff --git a/crates/openshell-driver-docker/src/tests.rs b/crates/openshell-driver-docker/src/tests.rs index 71855ed4b5..98e7cd1c37 100644 --- a/crates/openshell-driver-docker/src/tests.rs +++ b/crates/openshell-driver-docker/src/tests.rs @@ -37,7 +37,7 @@ fn test_sandbox() -> DriverSandbox { log_level: "debug".to_string(), environment: HashMap::from([("SPEC_ENV".to_string(), "spec".to_string())]), template: Some(DriverSandboxTemplate { - image: "ghcr.io/nvidia/openshell/sandbox:dev".to_string(), + image: "ghcr.io/nvidia/openshell-community/sandboxes/base:latest".to_string(), agent_socket_path: String::new(), labels: HashMap::new(), environment: HashMap::from([("TEMPLATE_ENV".to_string(), "template".to_string())]), @@ -1227,7 +1227,9 @@ fn build_environment_sets_docker_tls_paths() { }) .expect("main-process transport"); let main = openshell_core::sandbox_env::MainProcessConfig::decode(&encoded).unwrap(); - assert_eq!(main.command, vec!["/bin/bash", "-l"]); + // An omitted command is forwarded empty; the supervisor resolves the default + // login shell against the sandbox image at startup. + assert!(main.command.is_empty()); assert!(main.tty); } diff --git a/crates/openshell-ocsf/tests/roundtrip.rs b/crates/openshell-ocsf/tests/roundtrip.rs index 1c8a8bb307..e7d37c9036 100644 --- a/crates/openshell-ocsf/tests/roundtrip.rs +++ b/crates/openshell-ocsf/tests/roundtrip.rs @@ -22,7 +22,7 @@ fn ctx() -> SandboxContext { SandboxContext { sandbox_id: "sb-7f3a9c2e14b8".to_string(), sandbox_name: "agent-workspace-01".to_string(), - container_image: "ghcr.io/nvidia/openshell/sandbox:0.42.1".to_string(), + container_image: "ghcr.io/nvidia/openshell-community/sandboxes/base:latest".to_string(), hostname: "openshell-sb-7f3a9c2e14b8".to_string(), product_version: "0.42.1".to_string(), proxy_ip: IpAddr::V4(Ipv4Addr::LOCALHOST), diff --git a/crates/openshell-sandbox/src/main.rs b/crates/openshell-sandbox/src/main.rs index 7108378654..e7a0948718 100644 --- a/crates/openshell-sandbox/src/main.rs +++ b/crates/openshell-sandbox/src/main.rs @@ -111,7 +111,9 @@ impl std::str::FromStr for Mode { #[command(about = "Process sandbox and monitor", long_about = None)] struct Args { /// Command to execute in the sandbox. - /// Defaults to `/bin/bash -l` if neither this nor the driver specification is provided. + /// Defaults to a login shell if neither this nor the driver specification is + /// provided: `/bin/bash -l` when available, otherwise a shell detected in the + /// sandbox image (e.g. `/bin/sh` on Alpine). #[arg(trailing_var_arg = true)] command: Vec, @@ -678,6 +680,12 @@ fn main() -> Result<()> { ) }; + // An omitted command (the gateway leaves the default empty rather than + // baking a shell it cannot verify) is resolved to a login shell here, in + // the supervisor, so it matches the sandbox image: bash when present, + // otherwise /bin/sh (e.g. Alpine). An explicit command is used verbatim. + let command = resolve_default_command(command); + info!(command = ?command, "Starting sandbox"); // Note: "Starting sandbox" stays as plain info!() since the OCSF context // is not yet initialized at this point (run_sandbox hasn't been called). @@ -718,6 +726,20 @@ fn main() -> Result<()> { std::process::exit(exit_code); } +/// Resolve an omitted canonical command to a login shell that exists in this +/// sandbox image. Empty means "use the default": the gateway leaves an omitted +/// command empty rather than persisting a shell it cannot verify, so the +/// supervisor picks one here against the real sandbox filesystem (bash when +/// present, otherwise `/bin/sh`). An explicit command is returned unchanged. +fn resolve_default_command(command: Vec) -> Vec { + if !command.is_empty() { + return command; + } + let shell = openshell_core::shell::detect_login_shell(); + info!(shell = %shell, "no command specified; resolved default login shell"); + vec![shell, "-l".to_string()] +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/openshell-server/Cargo.toml b/crates/openshell-server/Cargo.toml index 898eef334d..2619fee5cc 100644 --- a/crates/openshell-server/Cargo.toml +++ b/crates/openshell-server/Cargo.toml @@ -122,10 +122,10 @@ bundled-z3 = ["openshell-prover/bundled-z3"] test-support = [] [dev-dependencies] +base64 = { workspace = true } hyper-rustls = { version = "0.27", default-features = false, features = ["native-tokio", "http1", "tls12", "logging", "ring"] } rcgen = { version = "0.13", features = ["crypto", "pem"] } rsa = { version = "0.9", features = ["pem"] } -base64 = { workspace = true } tokio-tungstenite = { workspace = true } futures-util = "0.3" wiremock = "0.6" diff --git a/crates/openshell-server/src/auth/oidc.rs b/crates/openshell-server/src/auth/oidc.rs index 475c52ebec..d50ad32f3f 100644 --- a/crates/openshell-server/src/auth/oidc.rs +++ b/crates/openshell-server/src/auth/oidc.rs @@ -18,12 +18,13 @@ use jsonwebtoken::{Algorithm, DecodingKey, Validation, decode, decode_header}; use openshell_core::OidcConfig; use reqwest::Client; use serde::Deserialize; -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; +use std::str::FromStr; use std::sync::Arc; use std::time::{Duration, Instant}; use tokio::sync::RwLock; use tonic::Status; -use tracing::{debug, info, warn}; +use tracing::{debug, error, info, warn}; /// Path prefixes that bypass OIDC validation (gRPC reflection, health probes). /// @@ -40,16 +41,34 @@ pub fn is_unauthenticated_method(path: &str) -> bool { .any(|prefix| path.starts_with(prefix)) } +/// How long previously-cached keys stay trusted after a refresh starts +/// returning zero usable keys, expressed as a multiple of the configured +/// TTL. Bounds exposure to keys the issuer may have deliberately revoked, +/// while still tolerating a transient empty or bad JWKS response. +const STALE_KEY_GRACE_MULTIPLIER: u32 = 3; + +/// Minimum interval between kid-miss-triggered refreshes. Bounds how much +/// a burst or steady stream of unknown-`kid` lookups can amplify requests +/// against the issuer's JWKS endpoint. +const KID_MISS_REFRESH_COOLDOWN: Duration = Duration::from_secs(1); + /// Cached JWKS key set fetched from the OIDC issuer. /// /// A `refresh_mutex` ensures that only one refresh runs at a time, /// preventing a "thundering herd" when the TTL expires or a new `kid` /// is encountered under concurrent load. pub struct JwksCache { - keys: Arc>>, + keys: Arc>>, jwks_uri: String, ttl: Duration, last_refresh: Arc>, + /// Timestamp of the last refresh that yielded at least one usable key. + /// Bounds how long a fully-empty or fully-unusable JWKS response can + /// keep serving stale cached keys before they're evicted. + last_nonempty_refresh: Arc>, + /// Timestamp of the last refresh triggered by an unknown `kid`, as + /// opposed to the regular TTL cadence. See `KID_MISS_REFRESH_COOLDOWN`. + last_kid_miss_refresh: Arc>, /// Serializes JWKS refresh operations so concurrent requests coalesce /// into a single HTTP fetch rather than stampeding the OIDC provider. refresh_mutex: tokio::sync::Mutex<()>, @@ -88,6 +107,218 @@ struct JwkKey { n: String, #[serde(default)] e: String, + #[serde(default)] + x: String, + #[serde(default)] + y: String, + #[serde(default)] + crv: String, + #[serde(default)] + alg: Option, + #[serde(rename = "use", default)] + use_: Option, + #[serde(default)] + key_ops: Vec, +} + +enum SkipReason { + MissingKid, + MissingComponents, + UnsupportedKeyType { + kty: String, + crv: Option, + }, + ParseError(String), + AlgMismatch { + declared: String, + derived: Algorithm, + }, + UseEnc, + UseNotSig, + KeyOpsNotForVerify, +} + +/// The RSA signature algorithms `jsonwebtoken` supports. Used to decide +/// whether a JWK's declared `alg` is a legitimate RSA algorithm selection +/// (see the RSA arm of `parse_jwk`) as opposed to an absent, unparseable, or +/// non-RSA value. +fn is_rsa_algorithm(algorithm: Algorithm) -> bool { + matches!( + algorithm, + Algorithm::RS256 + | Algorithm::RS384 + | Algorithm::RS512 + | Algorithm::PS256 + | Algorithm::PS384 + | Algorithm::PS512 + ) +} + +/// Log why a JWK was excluded from the cache, with the fields relevant to +/// diagnosing that specific `SkipReason`. +fn warn_skip(key: &JwkKey, reason: SkipReason) { + match reason { + SkipReason::MissingKid => { + warn!(kty = %key.kty, crv = %key.crv, "Skipping JWK without kid"); + } + SkipReason::MissingComponents => { + warn!( + kid = ?key.kid, + kty = %key.kty, + crv = %key.crv, + "Skipping JWK with missing key components" + ); + } + SkipReason::UnsupportedKeyType { kty, crv } => { + warn!(kid = ?key.kid, kty = %kty, crv = ?crv, "Skipping unsupported JWK key type"); + } + SkipReason::ParseError(error) => { + warn!(kid = ?key.kid, kty = %key.kty, error = %error, "Failed to parse JWK"); + } + SkipReason::AlgMismatch { declared, derived } => { + warn!( + kid = ?key.kid, + kty = %key.kty, + declared_alg = %declared, + derived_alg = ?derived, + "Skipping JWK with alg mismatch" + ); + } + SkipReason::UseEnc => { + warn!(kid = ?key.kid, kty = %key.kty, "Skipping encryption JWK (use: enc)"); + } + SkipReason::UseNotSig => { + warn!( + kid = ?key.kid, + kty = %key.kty, + use_ = ?key.use_, + "Skipping JWK with use not suitable for verify" + ); + } + SkipReason::KeyOpsNotForVerify => { + warn!(kid = ?key.kid, kty = %key.kty, "Skipping JWK with key_ops not suitable for verify"); + } + } +} + +/// Validate and decode a single JWK, returning its `kid`, decoding key, and +/// pinned algorithm, or the reason it must be excluded from the cache. +fn parse_jwk(key: &JwkKey) -> Result<(String, DecodingKey, Algorithm), SkipReason> { + // Must run before any early return below, not just before the + // `DecodingKey::from_*` calls further down: a JWKS response whose keys + // are all skipped by these checks would otherwise leave the process-wide + // crypto provider never installed on this path, and a caller reaching + // its own first `jsonwebtoken` operation without having installed one + // itself would panic. + crate::install_jsonwebtoken_crypto_provider(); + + // Subsumed by the `use_ != "sig"` check below (`"enc" != "sig"`); kept + // separate only to produce a more specific log line for the common + // `use: enc` case. + if key.use_.as_deref() == Some("enc") { + return Err(SkipReason::UseEnc); + } + if let Some(use_) = key.use_.as_deref().filter(|u| !u.is_empty()) + && use_ != "sig" + { + return Err(SkipReason::UseNotSig); + } + + // The gateway only ever verifies signatures, never creates them, so a + // key advertising `key_ops` must include "verify" — mirroring the + // strictness of the `use: "sig"` check above. `["sign"]` alone is + // semantically incoherent for a public verification key (RFC 7517 §4.3 + // treats "sign" and "verify" as distinct operations). + if !key.key_ops.is_empty() && !key.key_ops.iter().any(|op| op == "verify") { + return Err(SkipReason::KeyOpsNotForVerify); + } + + let kid = key.kid.as_deref().filter(|k| !k.is_empty()); + let Some(kid) = kid else { + return Err(SkipReason::MissingKid); + }; + + let (decoding_key, algorithm) = match key.kty.as_str() { + "RSA" => { + if key.n.is_empty() || key.e.is_empty() { + return Err(SkipReason::MissingComponents); + } + let dk = DecodingKey::from_rsa_components(&key.n, &key.e) + .map_err(|e| SkipReason::ParseError(e.to_string()))?; + // Select the algorithm from the JWK's declared `alg` when it + // names one of the RSA family; default to RS256 otherwise (most + // issuers, e.g. Microsoft Entra ID, omit `alg` entirely). The + // mismatch check below still rejects genuinely contradictory + // declarations (e.g. an RSA key declaring "ES256"). + let algorithm = key + .alg + .as_deref() + .and_then(|declared| Algorithm::from_str(declared).ok()) + .filter(|declared| is_rsa_algorithm(*declared)) + .unwrap_or(Algorithm::RS256); + (dk, algorithm) + } + "EC" => { + if key.x.is_empty() || key.y.is_empty() || key.crv.is_empty() { + return Err(SkipReason::MissingComponents); + } + let algorithm = match key.crv.as_str() { + "P-256" => Algorithm::ES256, + "P-384" => Algorithm::ES384, + _ => { + return Err(SkipReason::UnsupportedKeyType { + kty: key.kty.clone(), + crv: Some(key.crv.clone()), + }); + } + }; + let dk = DecodingKey::from_ec_components(&key.x, &key.y) + .map_err(|e| SkipReason::ParseError(e.to_string()))?; + (dk, algorithm) + } + "OKP" => { + if key.x.is_empty() || key.crv.is_empty() { + return Err(SkipReason::MissingComponents); + } + if key.crv != "Ed25519" { + return Err(SkipReason::UnsupportedKeyType { + kty: key.kty.clone(), + crv: Some(key.crv.clone()), + }); + } + let dk = DecodingKey::from_ed_components(&key.x) + .map_err(|e| SkipReason::ParseError(e.to_string()))?; + (dk, Algorithm::EdDSA) + } + other => { + return Err(SkipReason::UnsupportedKeyType { + kty: other.to_string(), + crv: if key.crv.is_empty() { + None + } else { + Some(key.crv.clone()) + }, + }); + } + }; + + if let Some(ref declared) = key.alg { + match Algorithm::from_str(declared) { + Ok(parsed) if parsed == algorithm => {} + // Either the declared algorithm genuinely contradicts the + // derived one, or it's an unrecognized string — in both cases + // we can't be sure the key is safe to use, so skip it rather + // than silently accepting our own default. + _ => { + return Err(SkipReason::AlgMismatch { + declared: declared.clone(), + derived: algorithm, + }); + } + } + } + + Ok((kid.to_string(), decoding_key, algorithm)) } /// Claims extracted from a validated JWT. @@ -168,6 +399,14 @@ impl JwksCache { /// Create a new JWKS cache, discovering the JWKS URI and fetching the /// initial key set. pub async fn new(config: &OidcConfig) -> Result { + if config.jwks_ttl_secs == 0 { + return Err( + "jwks_ttl_secs must be greater than zero (0 would refresh on every request and \ + collapse the stale-key grace period to zero)" + .to_string(), + ); + } + let http = Client::builder() .timeout(Duration::from_secs(10)) .build() @@ -209,6 +448,18 @@ impl JwksCache { .checked_sub(Duration::from_secs(config.jwks_ttl_secs + 1)) .unwrap_or_else(Instant::now), )), + // Placeholder value: the grace-period check is only reachable + // once `self.keys` has been non-empty, at which point this + // field always holds a freshly-stamped real value instead (see + // `refresh_keys`), so the value here is never actually read. + last_nonempty_refresh: Arc::new(RwLock::new(Instant::now())), + // Backdated beyond the cooldown so the very first kid-miss + // refresh is never throttled. + last_kid_miss_refresh: Arc::new(RwLock::new( + Instant::now() + .checked_sub(KID_MISS_REFRESH_COOLDOWN + Duration::from_secs(1)) + .unwrap_or_else(Instant::now), + )), refresh_mutex: tokio::sync::Mutex::new(()), http, config: config.clone(), @@ -233,26 +484,76 @@ impl JwksCache { .map_err(|e| format!("JWKS parse failed: {e}"))?; let mut new_keys = HashMap::new(); + let mut poisoned_kids = HashSet::new(); + let total = jwk_set.keys.len(); + for key in &jwk_set.keys { - if key.kty != "RSA" { + if let Some(kid) = key.kid.as_ref().filter(|k| !k.is_empty()) + && poisoned_kids.contains(kid) + { continue; } - let Some(ref kid) = key.kid else { - continue; - }; - crate::install_jsonwebtoken_crypto_provider(); - match DecodingKey::from_rsa_components(&key.n, &key.e) { - Ok(dk) => { - new_keys.insert(kid.clone(), dk); - } - Err(e) => { - warn!(kid = %kid, error = %e, "Failed to parse JWK"); + + match parse_jwk(key) { + Ok((kid, dk, alg)) => { + if let Some((_, existing_alg)) = new_keys.get(&kid) { + if *existing_alg == alg { + warn!( + kid = %kid, + algorithm = ?alg, + "Duplicate JWK kid, keeping first entry" + ); + continue; + } + let existing_alg = *existing_alg; + new_keys.remove(&kid); + poisoned_kids.insert(kid.clone()); + warn!( + kid = %kid, + existing_alg = ?existing_alg, + conflicting_alg = ?alg, + "Duplicate JWK kid with conflicting algorithms, poison-pilling kid" + ); + continue; + } + new_keys.insert(kid, (dk, alg)); } + Err(reason) => warn_skip(key, reason), } } - info!(count = new_keys.len(), "JWKS keys loaded"); - *self.keys.write().await = new_keys; + if new_keys.is_empty() { + // A refresh with zero usable keys must not immediately wipe a + // working cache, since that would turn a degraded issuer into a + // total outage. Keys stay trusted until a later refresh + // succeeds or the grace period expires. With no existing keys + // to fall back to (the first load, or after eviction), the + // empty set is committed immediately. + let grace = self.ttl.saturating_mul(STALE_KEY_GRACE_MULTIPLIER); + if self.keys.read().await.is_empty() { + error!( + total, + "JWKS has zero usable signing keys and no previous keys to fall back to" + ); + *self.keys.write().await = new_keys; + } else if self.last_nonempty_refresh.read().await.elapsed() > grace { + error!( + total, + grace_secs = grace.as_secs(), + "JWKS has had zero usable signing keys past the grace period; evicting cached keys" + ); + *self.keys.write().await = new_keys; + } else { + error!( + total, + "JWKS refresh loaded zero usable signing keys; keeping previous key set within grace period" + ); + } + } else { + info!(count = new_keys.len(), "JWKS keys loaded"); + *self.keys.write().await = new_keys; + *self.last_nonempty_refresh.write().await = Instant::now(); + } *self.last_refresh.write().await = Instant::now(); Ok(()) } @@ -276,9 +577,20 @@ impl JwksCache { self.refresh_keys().await } - /// Refresh keys unconditionally, coalescing concurrent callers. + /// Refresh keys on a kid-miss lookup, coalescing concurrent callers and + /// throttling how often such refreshes may hit the issuer. + /// + /// Without a cooldown, a caller presenting an unknown or fast-rotating + /// `kid` could force a fresh HTTP fetch on every single request. Only + /// the first kid-miss refresh within `KID_MISS_REFRESH_COOLDOWN` does + /// real work; the rest reuse its result. async fn refresh_keys_coalesced(&self) -> Result<(), String> { let _guard = self.refresh_mutex.lock().await; + let last = *self.last_kid_miss_refresh.read().await; + if last.elapsed() < KID_MISS_REFRESH_COOLDOWN { + return Ok(()); + } + *self.last_kid_miss_refresh.write().await = Instant::now(); self.refresh_keys().await } @@ -305,28 +617,39 @@ impl JwksCache { Status::unauthenticated("invalid token: missing kid") })?; - // Look up the key in cache. - let keys = self.keys.read().await; - let decoding_key = if let Some(k) = keys.get(&kid) { - k.clone() - } else { - // Key not found -- try refreshing once (key rotation). - drop(keys); + // Refresh once on kid miss. + let mut keys_guard = self.keys.read().await; + if !keys_guard.contains_key(&kid) { + drop(keys_guard); self.refresh_keys_coalesced().await.map_err(|e| { warn!(error = %e, "JWKS refresh on kid miss failed"); Status::internal("OIDC key refresh failed") })?; - let keys = self.keys.read().await; - keys.get(&kid).cloned().ok_or_else(|| { + keys_guard = self.keys.read().await; + } + + let (decoding_key, cached_algorithm) = keys_guard + .get(&kid) + .map(|(dk, alg)| (dk.clone(), *alg)) + .ok_or_else(|| { debug!(kid = %kid, "JWT kid not found in JWKS"); Status::unauthenticated("invalid token: unknown signing key") - })? - }; + })?; + drop(keys_guard); + + if header.alg != cached_algorithm { + debug!( + header_alg = ?header.alg, + expected = ?cached_algorithm, + "JWT algorithm mismatch for cached signing key" + ); + return Err(Status::unauthenticated("invalid token")); + } - // Validate the JWT. - let mut validation = Validation::new(Algorithm::RS256); + let mut validation = Validation::new(cached_algorithm); validation.set_issuer(&[&self.config.issuer]); validation.set_audience(&[&self.config.audience]); + validation.set_required_spec_claims(&["iss", "aud", "exp", "sub"]); let token_data = decode::(token, &decoding_key, &validation).map_err(|e| { debug!(error = %e, "JWT validation failed"); @@ -768,4 +1091,690 @@ mod tests { .await .expect_err("a token naming a kid absent from the JWKS must be rejected"); } + + mod jwks_validation { + use super::*; + use base64::Engine; + use base64::engine::general_purpose::URL_SAFE_NO_PAD; + use jsonwebtoken::{EncodingKey, Header, encode}; + use openshell_core::OidcConfig; + use rcgen::{KeyPair, PKCS_ECDSA_P256_SHA256, PKCS_ECDSA_P384_SHA384, PKCS_ED25519}; + use rsa::traits::PublicKeyParts; + use std::time::{SystemTime, UNIX_EPOCH}; + use wiremock::matchers::{method, path}; + use wiremock::{Mock, MockServer, ResponseTemplate}; + + struct TestSigningKey { + kid: String, + jwk: serde_json::Value, + encoding_key: EncodingKey, + algorithm: Algorithm, + } + + fn now_secs() -> i64 { + i64::try_from( + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_secs(), + ) + .unwrap() + } + + fn ec_coords_from_spki(spki: &[u8], coord_len: usize) -> (String, String) { + // The uncompressed EC point (a 0x04 tag byte followed by X and Y) + // is always the tail of an SPKI DER encoding, so slice it + // directly at the known offset instead of scanning for the tag + // byte (which could false-match a coordinate byte at the wrong + // offset). + let point_len = 1 + 2 * coord_len; + let point = &spki[spki.len() - point_len..]; + assert_eq!(point[0], 0x04, "expected uncompressed EC point marker"); + let x = URL_SAFE_NO_PAD.encode(&point[1..=coord_len]); + let y = URL_SAFE_NO_PAD.encode(&point[1 + coord_len..point_len]); + (x, y) + } + + // Precomputed 2048-bit RSA keys (PKCS8 PEM). Generating a fresh RSA + // key per test call site is the dominant cost of this test module + // (~7s across ~15 call sites); two static fixtures are deterministic + // and effectively free to parse. Two distinct keys are kept because + // a couple of tests (key rotation, duplicate-kid poisoning) need + // genuinely different key material, not just different `kid`s. + const RSA_TEST_KEY_PEM_PRIMARY: &str = "-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDFDsXUQjvihWzC\nA8UfdQ+QiQrAt8RBEMXXxiYHTn+EwDl4umH+OFURRGIlGgZ8cFrewKDotaJylEal\nnRq+urYCS3JjoerIS1lc9XZFp5ri7XB+5fB0bZQPNX4KIJ7MlbP2XG0zqvawww1A\nZQ4w9Ni8X+pptB7QlGWldALlNiOPvlVNaRFRzvY4wc2JqwlWj0ZD/5fqVaO/7oa6\nyyKuZzXQ3ps0PMbt7sz9FcyMEgkQCm0eNIOancjeQKhFNFh5VN71PhyfnhN9Xkwn\n0vaV24SRrOurLZAH4vhum0aDQLFC0yDVCKEfwW1Wl7Cs0ns6kS/IbG+RPBGH4Snr\nRoI9OaiLAgMBAAECggEAWOS9IW9vjFQcJ7mDpxkrmEv56c38Xk2ushPU+97Rb5U3\nV9rccc3/sfZjP9Fps6ELnQjQjanCSmXRKMyiT//yMz7Nr1xPiWNUQLcKT4m4OT5b\nTSN1QVBdRi8fWHo2qJuvvycarAAnoL2csLvllvgc/X1XRa/XZshKwkR/Od8eU60C\nMHuCmks+NCpUL/lMIZecAbWFyQDYJqwB/lnJdEO5oDaIcGclAOQJzj3+xCfFnLLh\nYt/7tCxOboIeyP/fLh5OyqC6NppRUSwtfWNQNwgQWw7WWVd5TW9d2wjycgQKrm6P\n1tnbs8yRJ2h8jemJR65OukW1QOfdN7QFWBAoD8BEwQKBgQDiIXhmre2qw/d4aOZV\nqDzjlHFCAG9XCAWF8pio2Uy0SUXAI4CcK6d+Njm/U7CaKNUfbNyip0iv3YoADwAv\nDlI6kqo1DOGXYgo2z0zfmxWTixQsCvZHtLrSk4Z1sxiSlFXfbTsR3vBd7qLXgKQ/\nWR9b2chPYlGew8DBRTNa0aQ/KQKBgQDfFjVKMibXSi69x704LQ9QoO0SR+pgdyw6\nJ5auf0N3ACqIOTqdD001Dn1zNO35RdTbV3vYDCq24yED5xro+fpSSbZ2+ZpMjhEk\nZjLGSlTSwsjzXx4l41f8wX7Br5OgTjA9B23NNDTf/RaD+ui5mfVA3BJyoXMkHCC2\nIV5ZZt7EkwKBgHu8Xtqor5UymDaOCAO1BGRvdK3t+P7Bh+wsvDYgeaVpNr6VbqmG\nBae9WkoELG2ejEge1Hg4W0DIU9wGWU5mYr5kRLi0rLieUAJ/2ou8m8jZYJddBDhm\nf5f8W6YJ8xc6DectKRZ1TEfJ7ddIMBft14f2GnK91PWwHchj6l72ug5JAoGAd1Hc\njOPILIyL9YvY5CwNrfV097spXBFBwZUdHhYJkqOvHA9oD0t44zDt3mnoAtTb5bmk\nDslrK0jOhtTcatIRlmPAyV/1rI6sEojrDW4CcnwmmS095cv0asdfsd7kGfDYEjxf\n+Uq8ITWwDkVspqD3MYrD/zXlbOHyiRfN7Al+iysCgYEA4Q8+8d5UwF1jzUQFmSEt\nMjlGyycrLpzadgWTG9EjQN0FuSJFK8nyEyqcfzFm+rSsReZ37JwPTCQ/Ck4g4IXY\n3VvHY+6wj0NYwRwjKCZeqN8IAANsj5Xsh5pz4ETSwnwd0bUlGP6Bcqoc5edLnB85\nEMcbZoGCXLCoi/qf8T334k4=\n-----END PRIVATE KEY-----\n"; + const RSA_TEST_KEY_PEM_SECONDARY: &str = "-----BEGIN PRIVATE KEY-----\nMIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCnRp9lR8xbtsXp\nCTTBkyAkhYji4Hp5FnAXxZF5DGfyw3I9ol0J8Hoe9RSBkQVIKXQe5Gfi+L7o9G6v\nVcucrzILxSJ4dCPKgNaj53G4zwkySpTsVO0XjxKanozQqdRbkAGaz9AsuzfGWB9m\n1AiC0JxKmOo8Ifxi4oj0hIBV4Mp3TCfHX8vFCIn5AZ/31Y29vT1mPzoCxwGw4Yxd\nh4kYQgIIWoAekebWeJ8iowgOvbV8rmT1geMWu7JRdpcStN9PWVZKUiZplILz9ci2\n+owm8UyxdQvBt6csEJFNdbAGUR1/Ywv/unoTQfrPvwQ4of5viywRra+iCMM0SrSA\nUO6Fu5a/AgMBAAECggEATDSTzD+73XJ0Ujhz9NYSeCDvnjBXC1AKDAJhRiy9NG8O\n3f5YdX09HVpYl7haGChuct5qZ5Ab5SPqQu2Kn5x+57bM/+QlJA2y+yOm/uMvFN6+\nXrZH9woilxcxHqSoDniaCo2vEJnQDIe78owZPoNMGH32hCOVh/UdIIw2rSkGA/eM\nYHHQXxx3sbi0AxCnlDzkgST15igP1baAZKUM2vIHVdg2Ccx2CnUiLM5BgvlWd98f\nS6GmTMk4WUWvmYYFZx+5GEhMmgz64xnyjIe+tRT1iP4p5NaCZc2CWLQdycEaEeKp\nmWFjxe7t/eXLUE3h1BBf/qZvcekpYbDGjw8JSaa00QKBgQDcctFl9P4npQUkoq0M\nDWeKSITsSwOVNKBLrQv5C4inz7QGPglGgIF8G6O7mvQ9ZulzDsvWfzxS0JE6ADkU\nHAkMY4/6Rfm7XKk8Yg1QoxCqsoI85nVQOhsmvVmIwXBDdINMY+g9jez9psiiiQiC\nh0nt3n9LPKu/YCzve50YTvR/bwKBgQDCQJSmZTFVsTC29e0CCgS1Zp9z4IAcZgth\nEJsaenE/ksQriH8gl3I4bwfI1p/xquBeWO40A016T67laCUBPTCwuZTGyqUiOtAw\nV5CoUiCvu38lNW6dk/RgouR0WoIQVvKq+5NKcnQtwbDHCt4U+hnB8c6EbT8dG2XU\noAamLcq1sQKBgADYI7srPAn01Nc2FEmWh439Bx1MkD/zCqYfjIswox5ZakwX0rtF\nZLmP9YmTZ1oQ2dYJ+Xfh1t5OVDAPrihIjzRP8U45FGLGUROdIIXtifPNaThIfayH\n/HCiiwQ+EWsAuDwDqfEKaRzzlZMhyTmOwRa7ImusWNAL00A7jfd43fDbAoGAa5u8\n/USXhOIIm4I2zmdgXmFAOcAHGDRLX3UEhzGHJPGX7InL6vEanDqdtFt49TZ03q8j\nHfsqY3Ra7ci4nywXmf7kdQ9zVTgBdpY7k5MTemZCtAkagv6gZRw3tGEjJgwUmDWP\nTbGDvIlM9aaGilZWCIN8pQ2j5er0iUoxBMPfRLECgYBu8/kcgM/sEeYh5vN5QqAh\n3/ezl+xboYDGGY1SLRwAzEsyIm9lyvvrFc+zGLpHqIP7jtrnu7CTqjxX0FQ2ECnd\nLIqNx0WMFZPq+GAD0hyUpYcqGFpHLGZGIOm8YhQUYvUL6ZWU4UQaND6gEq4ZYk9g\nk4dfOCu/AeloLlC3LUC9fw==\n-----END PRIVATE KEY-----\n"; + + enum RsaFixture { + Primary, + Secondary, + } + + /// Build an RSA `TestSigningKey` from a precomputed fixture, with an + /// optional declared `alg` and an explicit signing algorithm — used + /// by tests that exercise algorithm selection from the JWK's `alg` + /// field (RS256 default vs. a declared RS384/RS512/etc). + fn rsa_test_key_from( + kid: &str, + fixture: RsaFixture, + declared_alg: Option<&str>, + sign_algorithm: Algorithm, + ) -> TestSigningKey { + use rsa::pkcs8::DecodePrivateKey; + + let pem = match fixture { + RsaFixture::Primary => RSA_TEST_KEY_PEM_PRIMARY, + RsaFixture::Secondary => RSA_TEST_KEY_PEM_SECONDARY, + }; + let private_key = + rsa::RsaPrivateKey::from_pkcs8_pem(pem).expect("valid static test RSA key"); + let encoding_key = EncodingKey::from_rsa_pem(pem.as_bytes()).unwrap(); + let public_key = private_key.to_public_key(); + let n = URL_SAFE_NO_PAD.encode(public_key.n().to_bytes_be()); + let e = URL_SAFE_NO_PAD.encode(public_key.e().to_bytes_be()); + let mut jwk = serde_json::json!({ + "kty": "RSA", + "kid": kid, + "n": n, + "e": e, + "use": "sig", + }); + if let Some(alg) = declared_alg { + jwk["alg"] = serde_json::json!(alg); + } + TestSigningKey { + kid: kid.to_string(), + jwk, + encoding_key, + algorithm: sign_algorithm, + } + } + + fn rsa_test_key(kid: &str) -> TestSigningKey { + rsa_test_key_from(kid, RsaFixture::Primary, None, Algorithm::RS256) + } + + /// Distinct key material from `rsa_test_key`, for tests that need + /// two genuinely different RSA keys (e.g. key rotation, duplicate + /// `kid` poisoning) rather than just different `kid` labels. + fn rsa_test_key_secondary(kid: &str) -> TestSigningKey { + rsa_test_key_from(kid, RsaFixture::Secondary, None, Algorithm::RS256) + } + + fn ec_test_key(kid: &str, curve: &str) -> TestSigningKey { + let (key_pair, algorithm, coord_len) = match curve { + "P-256" => ( + KeyPair::generate_for(&PKCS_ECDSA_P256_SHA256).unwrap(), + Algorithm::ES256, + 32, + ), + "P-384" => ( + KeyPair::generate_for(&PKCS_ECDSA_P384_SHA384).unwrap(), + Algorithm::ES384, + 48, + ), + other => panic!("unsupported curve {other}"), + }; + let encoding_key = + EncodingKey::from_ec_pem(key_pair.serialize_pem().as_bytes()).unwrap(); + let (x, y) = ec_coords_from_spki(&key_pair.public_key_der(), coord_len); + let jwk = serde_json::json!({ + "kty": "EC", + "kid": kid, + "crv": curve, + "x": x, + "y": y, + "use": "sig", + }); + TestSigningKey { + kid: kid.to_string(), + jwk, + encoding_key, + algorithm, + } + } + + fn ed25519_test_key(kid: &str) -> TestSigningKey { + let key_pair = KeyPair::generate_for(&PKCS_ED25519).unwrap(); + let encoding_key = + EncodingKey::from_ed_pem(key_pair.serialize_pem().as_bytes()).unwrap(); + let spki = key_pair.public_key_der(); + let x = URL_SAFE_NO_PAD.encode(&spki[spki.len() - 32..]); + let jwk = serde_json::json!({ + "kty": "OKP", + "kid": kid, + "crv": "Ed25519", + "x": x, + "use": "sig", + }); + TestSigningKey { + kid: kid.to_string(), + jwk, + encoding_key, + algorithm: Algorithm::EdDSA, + } + } + + fn token_with_header_alg(token: &str, algorithm: Algorithm) -> String { + let mut parts: Vec = token.split('.').map(str::to_string).collect(); + assert_eq!(parts.len(), 3); + let header_bytes = URL_SAFE_NO_PAD.decode(&parts[0]).unwrap(); + let mut header: serde_json::Value = serde_json::from_slice(&header_bytes).unwrap(); + header["alg"] = serde_json::json!(match algorithm { + Algorithm::HS256 => "HS256", + other => panic!("unsupported test algorithm {other:?}"), + }); + parts[0] = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&header).unwrap()); + parts.join(".") + } + + fn sign_token(key: &TestSigningKey, issuer: &str, audience: &str, sub: &str) -> String { + let mut header = Header::new(key.algorithm); + header.kid = Some(key.kid.clone()); + let claims = serde_json::json!({ + "sub": sub, + "iss": issuer, + "aud": audience, + "exp": now_secs() + 3600, + }); + encode(&header, &claims, &key.encoding_key).unwrap() + } + + fn test_oidc_config(issuer: &str) -> OidcConfig { + OidcConfig { + issuer: issuer.to_string(), + audience: "test-audience".to_string(), + jwks_ttl_secs: 3600, + roles_claim: "roles".to_string(), + admin_role: "admin".to_string(), + user_role: "user".to_string(), + scopes_claim: String::new(), + } + } + + async fn mount_oidc(server: &MockServer, jwks: serde_json::Value) -> (String, OidcConfig) { + let issuer = format!("{}/issuer", server.uri()); + let jwks_uri = format!("{issuer}/jwks"); + Mock::given(method("GET")) + .and(path("/issuer/.well-known/openid-configuration")) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "issuer": issuer, + "jwks_uri": jwks_uri, + }))) + .mount(server) + .await; + Mock::given(method("GET")) + .and(path("/issuer/jwks")) + .respond_with(ResponseTemplate::new(200).set_body_json(jwks)) + .mount(server) + .await; + (issuer.clone(), test_oidc_config(&issuer)) + } + + async fn cache_from_jwks(jwks: serde_json::Value) -> (JwksCache, String, OidcConfig) { + let server = MockServer::start().await; + let (issuer, config) = mount_oidc(&server, jwks).await; + let cache = JwksCache::new(&config).await.unwrap(); + (cache, issuer, config) + } + + #[tokio::test] + async fn validate_rsa_es256_es384_eddsa_tokens() { + let rsa = rsa_test_key("rsa-key"); + let es256 = ec_test_key("es256-key", "P-256"); + let es384 = ec_test_key("es384-key", "P-384"); + let eddsa = ed25519_test_key("eddsa-key"); + let jwks = serde_json::json!({ + "keys": [rsa.jwk, es256.jwk, es384.jwk, eddsa.jwk] + }); + let (cache, issuer, config) = cache_from_jwks(jwks).await; + + for (name, key) in [ + ("rsa", &rsa), + ("es256", &es256), + ("es384", &es384), + ("eddsa", &eddsa), + ] { + let token = sign_token(key, &issuer, &config.audience, "user-1"); + let result = cache.validate_token(&token).await; + assert!(result.is_ok(), "validation failed for {name}: {result:?}"); + assert_eq!(result.unwrap().subject, "user-1"); + } + } + + #[tokio::test] + async fn unsupported_curve_is_skipped() { + let signing = rsa_test_key("good"); + let jwks = serde_json::json!({ + "keys": [ + { "kty": "EC", "kid": "p521", "crv": "P-521", "x": "abc", "y": "def" }, + signing.jwk, + ] + }); + let (cache, issuer, config) = cache_from_jwks(jwks).await; + let token = sign_token(&signing, &issuer, &config.audience, "user-1"); + assert!(cache.validate_token(&token).await.is_ok()); + } + + #[tokio::test] + async fn kid_miss_triggers_refresh() { + let initial = rsa_test_key("initial"); + let rotated = rsa_test_key_secondary("rotated"); + let server = MockServer::start().await; + let issuer = format!("{}/issuer", server.uri()); + let jwks_uri = format!("{issuer}/jwks"); + Mock::given(method("GET")) + .and(path("/issuer/.well-known/openid-configuration")) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "issuer": issuer, + "jwks_uri": jwks_uri, + }))) + .mount(&server) + .await; + + Mock::given(method("GET")) + .and(path("/issuer/jwks")) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "keys": [initial.jwk] + }))) + .up_to_n_times(1) + .mount(&server) + .await; + Mock::given(method("GET")) + .and(path("/issuer/jwks")) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "keys": [rotated.jwk] + }))) + .mount(&server) + .await; + + let config = test_oidc_config(&issuer); + let cache = JwksCache::new(&config).await.unwrap(); + let initial_token = sign_token(&initial, &issuer, &config.audience, "user-initial"); + assert!(cache.validate_token(&initial_token).await.is_ok()); + + let rotated_token = sign_token(&rotated, &issuer, &config.audience, "user-rotated"); + let identity = cache.validate_token(&rotated_token).await.unwrap(); + assert_eq!(identity.subject, "user-rotated"); + } + + /// Shared setup for the "a refresh yields no usable keys" family of + /// regression tests: an initially-working cache, then a refresh + /// (triggered by an unknown `kid`) whose response is `bad_jwks`. + /// Asserts the previously cached key remains usable afterward. + async fn assert_refresh_preserves_cache(bad_jwks: serde_json::Value) { + let good = rsa_test_key("good"); + let server = MockServer::start().await; + let issuer = format!("{}/issuer", server.uri()); + let jwks_uri = format!("{issuer}/jwks"); + Mock::given(method("GET")) + .and(path("/issuer/.well-known/openid-configuration")) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "issuer": issuer, + "jwks_uri": jwks_uri, + }))) + .mount(&server) + .await; + + Mock::given(method("GET")) + .and(path("/issuer/jwks")) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "keys": [good.jwk] + }))) + .up_to_n_times(1) + .mount(&server) + .await; + Mock::given(method("GET")) + .and(path("/issuer/jwks")) + .respond_with(ResponseTemplate::new(200).set_body_json(bad_jwks)) + .mount(&server) + .await; + + let config = test_oidc_config(&issuer); + let cache = JwksCache::new(&config).await.unwrap(); + let token = sign_token(&good, &issuer, &config.audience, "user-1"); + assert!(cache.validate_token(&token).await.is_ok()); + + // An unknown kid triggers an unconditional refresh against the + // bad response, so this specific lookup still fails, but the + // previously cached key must remain usable afterward: the bad + // refresh must not have wiped it. + let mut header = Header::new(Algorithm::RS256); + header.kid = Some("unknown".to_string()); + let claims = serde_json::json!({ + "sub": "user-2", + "iss": issuer, + "aud": config.audience, + "exp": now_secs() + 3600, + }); + let unknown_kid_token = encode(&header, &claims, &good.encoding_key).unwrap(); + let err = cache.validate_token(&unknown_kid_token).await.unwrap_err(); + assert_eq!(err.code(), tonic::Code::Unauthenticated); + + assert!(cache.validate_token(&token).await.is_ok()); + } + + #[tokio::test] + async fn refresh_keeps_previous_keys_when_new_jwks_fully_unusable() { + // An issuer-side metadata change (e.g. every key switches to + // `use: "enc"`) must not wipe a previously-working key cache — + // otherwise a single bad JWKS response turns "working" into + // "every OIDC request rejected". + assert_refresh_preserves_cache(serde_json::json!({ + "keys": [{ "kty": "RSA", "kid": "good", "n": "abc", "e": "AQAB", "use": "enc" }] + })) + .await; + } + + #[tokio::test] + async fn refresh_keeps_previous_keys_when_new_jwks_response_empty() { + // A literally empty JWKS response (`total == 0`, as opposed to + // keys present but all filtered out) must be just as harmless + // to an existing cache as the fully-unusable case above. + assert_refresh_preserves_cache(serde_json::json!({ "keys": [] })).await; + } + + #[tokio::test] + async fn stale_keys_evicted_after_grace_period() { + // A JWKS that goes empty and stays empty must eventually stop + // being trusted; otherwise a key the issuer revoked could + // remain valid indefinitely behind a permanently broken JWKS + // endpoint. + let good = rsa_test_key("good"); + let server = MockServer::start().await; + let issuer = format!("{}/issuer", server.uri()); + let jwks_uri = format!("{issuer}/jwks"); + Mock::given(method("GET")) + .and(path("/issuer/.well-known/openid-configuration")) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "issuer": issuer, + "jwks_uri": jwks_uri, + }))) + .mount(&server) + .await; + Mock::given(method("GET")) + .and(path("/issuer/jwks")) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "keys": [good.jwk] + }))) + .up_to_n_times(1) + .mount(&server) + .await; + Mock::given(method("GET")) + .and(path("/issuer/jwks")) + .respond_with( + ResponseTemplate::new(200).set_body_json(serde_json::json!({ "keys": [] })), + ) + .mount(&server) + .await; + + let mut config = test_oidc_config(&issuer); + config.jwks_ttl_secs = 1; // 1s TTL -> 3s grace period. + let cache = JwksCache::new(&config).await.unwrap(); + let token = sign_token(&good, &issuer, &config.audience, "user-1"); + assert!(cache.validate_token(&token).await.is_ok()); + + // Past the TTL but within the grace period: a scheduled refresh + // sees the now-empty JWKS, but the cached key stays trusted. + tokio::time::sleep(Duration::from_millis(1200)).await; + assert!(cache.validate_token(&token).await.is_ok()); + + // Past the grace period with the JWKS still empty: the stale + // key must finally be evicted. + tokio::time::sleep(Duration::from_millis(2500)).await; + let err = cache.validate_token(&token).await.unwrap_err(); + assert_eq!(err.code(), tonic::Code::Unauthenticated); + } + + #[tokio::test] + async fn zero_ttl_rejected_at_construction() { + // A `jwks_ttl_secs` of 0 would refresh on every request and + // collapse the stale-key grace period to zero, so it's rejected + // outright rather than silently tolerated. This is consistent + // with how `AuthzPolicy::validate` rejects OIDC RBAC + // misconfiguration before the server starts, instead of + // working around it later. The check runs before any network + // I/O, so no mock server is needed here. + let mut config = test_oidc_config("http://unused.invalid"); + config.jwks_ttl_secs = 0; + let err = JwksCache::new(&config).await.unwrap_err(); + assert!( + err.contains("jwks_ttl_secs"), + "error should name the offending field: {err}" + ); + } + + #[tokio::test] + async fn kid_miss_refresh_throttled_within_cooldown() { + // Repeated lookups for an unknown kid within the cooldown + // window must not each trigger a fresh fetch. Otherwise, a + // burst (or steady stream) of unknown-kid requests could + // amplify load on the issuer's JWKS endpoint without bound. + let good = rsa_test_key("good"); + let server = MockServer::start().await; + let issuer = format!("{}/issuer", server.uri()); + let jwks_uri = format!("{issuer}/jwks"); + Mock::given(method("GET")) + .and(path("/issuer/.well-known/openid-configuration")) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "issuer": issuer, + "jwks_uri": jwks_uri, + }))) + .mount(&server) + .await; + Mock::given(method("GET")) + .and(path("/issuer/jwks")) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "keys": [good.jwk] + }))) + .mount(&server) + .await; + + let config = test_oidc_config(&issuer); + let cache = JwksCache::new(&config).await.unwrap(); + + let mut header = Header::new(Algorithm::RS256); + header.kid = Some("unknown".to_string()); + let claims = serde_json::json!({ + "sub": "user-2", + "iss": issuer, + "aud": config.audience, + "exp": now_secs() + 3600, + }); + let unknown_kid_token = encode(&header, &claims, &good.encoding_key).unwrap(); + + for _ in 0..5 { + let err = cache.validate_token(&unknown_kid_token).await.unwrap_err(); + assert_eq!(err.code(), tonic::Code::Unauthenticated); + } + + let requests = server.received_requests().await.unwrap(); + let jwks_hits = requests + .iter() + .filter(|r| r.url.path() == "/issuer/jwks") + .count(); + // One fetch for the initial load, one more for the first + // kid-miss lookup; the remaining four must be throttled. + assert_eq!(jwks_hits, 2); + } + + #[tokio::test] + async fn header_alg_mismatch_rejected() { + let ec = ec_test_key("ec", "P-256"); + let jwks = serde_json::json!({ "keys": [ec.jwk] }); + let (cache, issuer, config) = cache_from_jwks(jwks).await; + let token = sign_token(&ec, &issuer, &config.audience, "user-1"); + let forged = token_with_header_alg(&token, Algorithm::HS256); + let err = cache.validate_token(&forged).await.unwrap_err(); + assert_eq!(err.code(), tonic::Code::Unauthenticated); + } + + #[tokio::test] + async fn missing_sub_claim_rejected() { + let key = rsa_test_key("rsa"); + let jwks = serde_json::json!({ "keys": [key.jwk] }); + let (cache, issuer, config) = cache_from_jwks(jwks).await; + let mut header = Header::new(key.algorithm); + header.kid = Some(key.kid.clone()); + let claims = serde_json::json!({ + "iss": issuer, + "aud": config.audience, + "exp": now_secs() + 3600, + }); + let token = encode(&header, &claims, &key.encoding_key).unwrap(); + let err = cache.validate_token(&token).await.unwrap_err(); + assert_eq!(err.code(), tonic::Code::Unauthenticated); + } + + #[tokio::test] + async fn jwk_alg_mismatch_skipped() { + let signing = rsa_test_key("rsa"); + let mut bad = signing.jwk.clone(); + bad["alg"] = serde_json::json!("ES256"); + let jwks = serde_json::json!({ "keys": [bad] }); + let (cache, issuer, config) = cache_from_jwks(jwks).await; + let token = sign_token(&signing, &issuer, &config.audience, "user-1"); + let err = cache.validate_token(&token).await.unwrap_err(); + assert_eq!(err.code(), tonic::Code::Unauthenticated); + } + + #[tokio::test] + async fn rsa_declared_alg_rs512_selected_and_pinned() { + // An RSA JWK declaring "alg": "RS512" is validated as RS512, not + // vetoed against a hardcoded RS256 default that would silently + // discard the declared algorithm. + let key = rsa_test_key_from( + "rsa-rs512", + RsaFixture::Primary, + Some("RS512"), + Algorithm::RS512, + ); + let jwks = serde_json::json!({ "keys": [key.jwk.clone()] }); + let (cache, issuer, config) = cache_from_jwks(jwks).await; + + let token = sign_token(&key, &issuer, &config.audience, "user-1"); + let result = cache.validate_token(&token).await; + assert!(result.is_ok(), "RS512 token should validate: {result:?}"); + + // The cached algorithm is pinned to RS512, not re-derived from + // the header — a token for the same kid claiming RS256 must + // still be rejected. + let mut rs256_variant = key; + rs256_variant.algorithm = Algorithm::RS256; + let mismatched = sign_token(&rs256_variant, &issuer, &config.audience, "user-1"); + let err = cache.validate_token(&mismatched).await.unwrap_err(); + assert_eq!(err.code(), tonic::Code::Unauthenticated); + } + + #[tokio::test] + async fn rsa_missing_alg_defaults_to_rs256() { + // No "alg" field at all (e.g. Microsoft Entra ID's JWKS) must + // still default to RS256, not be treated as unusable. + let key = rsa_test_key("rsa-no-alg"); + assert!(key.jwk.get("alg").is_none()); + let jwks = serde_json::json!({ "keys": [key.jwk.clone()] }); + let (cache, issuer, config) = cache_from_jwks(jwks).await; + let token = sign_token(&key, &issuer, &config.audience, "user-1"); + assert!(cache.validate_token(&token).await.is_ok()); + } + + #[tokio::test] + async fn key_ops_verify_accepted_sign_only_rejected() { + // The gateway only ever verifies signatures, so `key_ops` must + // include "verify" — `["sign"]` alone (without "verify") on a + // public key is semantically incoherent per RFC 7517 §4.3 and + // must be rejected, not treated as interchangeable with "verify". + let mut verify_key = rsa_test_key("verify-key"); + verify_key.jwk["key_ops"] = serde_json::json!(["verify"]); + let mut sign_key = rsa_test_key_secondary("sign-key"); + sign_key.jwk["key_ops"] = serde_json::json!(["sign"]); + let jwks = serde_json::json!({ "keys": [verify_key.jwk, sign_key.jwk] }); + let (cache, issuer, config) = cache_from_jwks(jwks).await; + + let verify_token = sign_token(&verify_key, &issuer, &config.audience, "verify-user"); + assert!(cache.validate_token(&verify_token).await.is_ok()); + + let sign_token_str = sign_token(&sign_key, &issuer, &config.audience, "sign-user"); + let err = cache.validate_token(&sign_token_str).await.unwrap_err(); + assert_eq!(err.code(), tonic::Code::Unauthenticated); + } + + #[tokio::test] + async fn key_ops_sign_and_encrypt_rejected() { + // RFC 7517 §4.3 permits "sign" with "verify" but not "sign" with + // "encrypt" ("other combinations SHOULD NOT be used"). Since + // "verify" is absent here, the key must be skipped. + let mut key = rsa_test_key("mixed-ops"); + key.jwk["key_ops"] = serde_json::json!(["sign", "encrypt"]); + let jwks = serde_json::json!({ "keys": [key.jwk] }); + let (cache, issuer, config) = cache_from_jwks(jwks).await; + let token = sign_token(&key, &issuer, &config.audience, "user-1"); + let err = cache.validate_token(&token).await.unwrap_err(); + assert_eq!(err.code(), tonic::Code::Unauthenticated); + } + + #[tokio::test] + async fn key_ops_encrypt_only_skipped() { + let signing = rsa_test_key("good"); + let mut enc_ops = signing.jwk.clone(); + enc_ops["kid"] = serde_json::json!("enc-ops"); + enc_ops["key_ops"] = serde_json::json!(["encrypt"]); + let jwks = serde_json::json!({ "keys": [enc_ops, signing.jwk] }); + let (cache, issuer, config) = cache_from_jwks(jwks).await; + let token = sign_token(&signing, &issuer, &config.audience, "user-1"); + assert!(cache.validate_token(&token).await.is_ok()); + } + + #[tokio::test] + async fn encryption_jwk_skipped_but_sig_key_works() { + let signing = rsa_test_key("sig"); + let mut enc = signing.jwk.clone(); + enc["use"] = serde_json::json!("enc"); + enc["kid"] = serde_json::json!("enc-key"); + let jwks = serde_json::json!({ "keys": [enc, signing.jwk] }); + let (cache, issuer, config) = cache_from_jwks(jwks).await; + let token = sign_token(&signing, &issuer, &config.audience, "user-1"); + assert!(cache.validate_token(&token).await.is_ok()); + } + + #[tokio::test] + async fn duplicate_kid_same_algorithm_keeps_first() { + let first = rsa_test_key("dup"); + let second = rsa_test_key_secondary("other"); + let mut second_jwk = second.jwk.clone(); + second_jwk["kid"] = serde_json::json!("dup"); + let jwks = serde_json::json!({ "keys": [first.jwk, second_jwk] }); + let (cache, issuer, config) = cache_from_jwks(jwks).await; + + let first_token = sign_token(&first, &issuer, &config.audience, "first-user"); + assert!(cache.validate_token(&first_token).await.is_ok()); + + let mut header = Header::new(second.algorithm); + header.kid = Some("dup".to_string()); + let claims = serde_json::json!({ + "sub": "second-user", + "iss": issuer, + "aud": config.audience, + "exp": now_secs() + 3600, + }); + let second_token = encode(&header, &claims, &second.encoding_key).unwrap(); + let err = cache.validate_token(&second_token).await.unwrap_err(); + assert_eq!(err.code(), tonic::Code::Unauthenticated); + } + + #[tokio::test] + async fn duplicate_kid_conflicting_algorithms_poison_pill() { + let rsa = rsa_test_key("conflict"); + let eddsa = ed25519_test_key("conflict"); + let jwks = serde_json::json!({ "keys": [rsa.jwk, eddsa.jwk] }); + let (cache, issuer, config) = cache_from_jwks(jwks).await; + + let rsa_token = sign_token(&rsa, &issuer, &config.audience, "rsa-user"); + let err = cache.validate_token(&rsa_token).await.unwrap_err(); + assert_eq!(err.code(), tonic::Code::Unauthenticated); + + let eddsa_token = sign_token(&eddsa, &issuer, &config.audience, "eddsa-user"); + let err = cache.validate_token(&eddsa_token).await.unwrap_err(); + assert_eq!(err.code(), tonic::Code::Unauthenticated); + } + } } diff --git a/crates/openshell-server/src/compute/mod.rs b/crates/openshell-server/src/compute/mod.rs index 86ac0b5e88..5f7524f838 100644 --- a/crates/openshell-server/src/compute/mod.rs +++ b/crates/openshell-server/src/compute/mod.rs @@ -10806,7 +10806,7 @@ mod tests { ..Default::default() }), template: Some(SandboxTemplate { - image: "ghcr.io/nvidia/openshell/sandbox:test".to_string(), + image: "ghcr.io/nvidia/openshell-community/sandboxes/base:latest".to_string(), driver_config: Some(prost_types::Struct { fields: [ ( diff --git a/crates/openshell-server/src/config_file.rs b/crates/openshell-server/src/config_file.rs index 65709748b1..64ac953624 100644 --- a/crates/openshell-server/src/config_file.rs +++ b/crates/openshell-server/src/config_file.rs @@ -522,7 +522,7 @@ sandbox_namespace = "agents" grpc_rate_limit_requests = 120 grpc_rate_limit_window_seconds = 60 policy_validation_failure_mode = "retain_last_valid" -default_image = "ghcr.io/nvidia/openshell/sandbox:latest" +default_image = "ghcr.io/nvidia/openshell-community/sandboxes/base:latest" supervisor_image = "ghcr.io/nvidia/openshell/supervisor:latest" client_tls_secret_name = "openshell-sandbox-tls" service_account_name = "openshell-sandbox" @@ -549,7 +549,7 @@ namespace = "agents" assert_eq!(gw.log_level.as_deref(), Some("info")); assert_eq!( gw.default_image.as_deref(), - Some("ghcr.io/nvidia/openshell/sandbox:latest") + Some("ghcr.io/nvidia/openshell-community/sandboxes/base:latest") ); assert_eq!(gw.grpc_rate_limit_requests, Some(120)); assert_eq!(gw.grpc_rate_limit_window_seconds, Some(60)); @@ -943,7 +943,9 @@ version = 2 #[test] fn driver_table_inherits_gateway_defaults() { let gateway = GatewayFileSection { - default_image: Some("ghcr.io/nvidia/openshell/sandbox:0.9".to_string()), + default_image: Some( + "ghcr.io/nvidia/openshell-community/sandboxes/base:latest".to_string(), + ), supervisor_image: Some("ghcr.io/nvidia/openshell/supervisor:0.9".to_string()), ..Default::default() }; @@ -963,7 +965,7 @@ version = 2 ); assert_eq!( table.get("default_image").and_then(|v| v.as_str()), - Some("ghcr.io/nvidia/openshell/sandbox:0.9") + Some("ghcr.io/nvidia/openshell-community/sandboxes/base:latest") ); assert_eq!( table.get("supervisor_image").and_then(|v| v.as_str()), @@ -975,7 +977,9 @@ version = 2 fn registered_driver_table_inherits_selected_gateway_defaults() { let gateway = GatewayFileSection { sandbox_namespace: Some("agents".to_string()), - default_image: Some("ghcr.io/nvidia/openshell/sandbox:0.9".to_string()), + default_image: Some( + "ghcr.io/nvidia/openshell-community/sandboxes/base:latest".to_string(), + ), host_gateway_ip: Some("10.0.0.1".to_string()), ..Default::default() }; @@ -992,7 +996,7 @@ version = 2 ); assert_eq!( table.get("default_image").and_then(|v| v.as_str()), - Some("ghcr.io/nvidia/openshell/sandbox:0.9") + Some("ghcr.io/nvidia/openshell-community/sandboxes/base:latest") ); assert_eq!( table.get("host_gateway_ip").and_then(|v| v.as_str()), @@ -1003,7 +1007,9 @@ version = 2 #[test] fn registered_driver_table_can_select_network_defaults() { let gateway = GatewayFileSection { - default_image: Some("ghcr.io/nvidia/openshell/sandbox:0.9".to_string()), + default_image: Some( + "ghcr.io/nvidia/openshell-community/sandboxes/base:latest".to_string(), + ), host_gateway_ip: Some("192.168.127.254".to_string()), ..Default::default() }; @@ -1016,7 +1022,7 @@ version = 2 let table = merged.as_table().expect("table"); assert_eq!( table.get("default_image").and_then(|v| v.as_str()), - Some("ghcr.io/nvidia/openshell/sandbox:0.9") + Some("ghcr.io/nvidia/openshell-community/sandboxes/base:latest") ); assert_eq!( table.get("host_gateway_ip").and_then(|v| v.as_str()), diff --git a/crates/openshell-server/src/grpc/sandbox.rs b/crates/openshell-server/src/grpc/sandbox.rs index d4d08da251..b941502c62 100644 --- a/crates/openshell-server/src/grpc/sandbox.rs +++ b/crates/openshell-server/src/grpc/sandbox.rs @@ -297,11 +297,12 @@ async fn handle_create_sandbox_inner( (resolved, Some(provenance)) }; - // Every newly persisted sandbox has one explicit canonical process. This - // portable default also preserves compatibility with callers compiled - // before the main-process field was introduced. + // Leave an omitted command empty rather than persisting a concrete shell: + // the supervisor resolves the default login shell against the sandbox image + // (bash when present, otherwise /bin/sh on minimal images like Alpine), + // which the gateway cannot do since it does not see the sandbox filesystem. + // The default is an interactive login shell, so request a TTY. if spec.command.is_empty() { - spec.command = vec!["/bin/bash".to_string(), "-l".to_string()]; spec.tty = true; } diff --git a/crates/openshell-supervisor-process/src/process.rs b/crates/openshell-supervisor-process/src/process.rs index 52557493cd..0ab1dd3187 100644 --- a/crates/openshell-supervisor-process/src/process.rs +++ b/crates/openshell-supervisor-process/src/process.rs @@ -225,11 +225,14 @@ fn apply_canonical_process_environment( user_environment: &HashMap, ) { let (session_user, session_home) = session_user_and_home(policy, workspace.home()); + // Resolve a shell present in the sandbox image (minimal images such as + // Alpine ship only `/bin/sh`, not bash). Runs in the supervisor. + let shell = openshell_core::shell::detect_login_shell(); for (key, value) in [ ("HOME", session_home.as_str()), ("USER", session_user.as_str()), - ("SHELL", "/bin/bash"), + ("SHELL", shell.as_str()), ( "TERM", if interactive { @@ -900,15 +903,19 @@ impl ProcessHandle { } } + // Name the program in the error: a bare "No such file or directory" + // here is otherwise indistinguishable from a missing working directory + // or interpreter, and is a common failure on images that lack the + // requested shell/binary (e.g. bash on Alpine). #[cfg(target_os = "linux")] let mut child = spawn_command_with_supervisor_identity_namespace(cmd) .into_diagnostic() - .wrap_err("failed to spawn sandbox entrypoint process")?; + .wrap_err_with(|| format!("failed to spawn sandbox entrypoint process '{program}'"))?; #[cfg(not(target_os = "linux"))] let mut child = cmd .spawn() .into_diagnostic() - .wrap_err("failed to spawn sandbox entrypoint process")?; + .wrap_err_with(|| format!("failed to spawn sandbox entrypoint process '{program}'"))?; let pid = child.id().unwrap_or(0); managed_children::register(pid); @@ -2475,7 +2482,10 @@ mod tests { Some(¤t_user.dir.to_string_lossy().as_ref()) ); assert_eq!(variables.get("USER"), Some(¤t_user.name.as_str())); - assert_eq!(variables.get("SHELL"), Some(&"/bin/bash")); + // SHELL is the shell detected in the current root filesystem, not a + // hardcoded path (bash-less images resolve to /bin/sh). + let expected_shell = openshell_core::shell::detect_login_shell(); + assert_eq!(variables.get("SHELL"), Some(&expected_shell.as_str())); assert_eq!(variables.get("TERM"), Some(&"xterm-256color")); } diff --git a/crates/openshell-supervisor-process/src/ssh.rs b/crates/openshell-supervisor-process/src/ssh.rs index 357969fb52..fbd6d9275b 100644 --- a/crates/openshell-supervisor-process/src/ssh.rs +++ b/crates/openshell-supervisor-process/src/ssh.rs @@ -1208,7 +1208,7 @@ fn apply_child_env( .env(openshell_core::sandbox_env::SANDBOX, "1") .env("HOME", session_home) .env("USER", session_user) - .env("SHELL", "/bin/bash") + .env("SHELL", openshell_core::shell::detect_login_shell()) .env("PATH", &path) .env("TERM", term); @@ -1242,6 +1242,33 @@ const fn login_shell_flag(no_login_shell: bool) -> &'static str { if no_login_shell { "-c" } else { "-lc" } } +/// Build the shell command for an SSH session using a shell that exists in the +/// sandbox image (minimal images such as Alpine ship only `/bin/sh`, not bash). +/// +/// `no_command_arg` is appended only when no explicit command is given: `-i` +/// for an interactive PTY session, or `None` for the non-PTY stdin path (a +/// bare shell already reads piped stdin line-by-line). With an explicit +/// command the login-shell flag is used per `no_login_shell`. +fn build_ssh_shell_command( + shell: &str, + command: Option, + no_login_shell: bool, + no_command_arg: Option<&str>, +) -> Command { + let mut cmd = Command::new(shell); + match command { + None => { + if let Some(arg) = no_command_arg { + cmd.arg(arg); + } + } + Some(command) => { + cmd.arg(login_shell_flag(no_login_shell)).arg(command); + } + } + cmd +} + #[allow(clippy::too_many_arguments)] fn spawn_pty_shell( policy: &SandboxPolicy, @@ -1276,18 +1303,11 @@ fn spawn_pty_shell( let mut reader = master.try_clone()?; let mut writer = master.try_clone()?; - let mut cmd = command.map_or_else( - || { - let mut c = Command::new("/bin/bash"); - c.arg("-i"); - c - }, - |command| { - let mut c = Command::new("/bin/bash"); - c.arg(login_shell_flag(no_login_shell)).arg(command); - c - }, - ); + // Resolve a shell present in the sandbox image; interactive PTY sessions + // pass `-i` when no command is given. Runs in the supervisor, so it + // inspects the sandbox filesystem. + let shell = openshell_core::shell::detect_login_shell(); + let mut cmd = build_ssh_shell_command(&shell, command, no_login_shell, Some("-i")); let term = if pty.term.is_empty() { "xterm-256color" @@ -1435,25 +1455,15 @@ fn spawn_pipe_exec( resolved_identity: ResolvedProcessIdentity, enforcement_mode: ProcessEnforcementMode, ) -> anyhow::Result>> { - let mut cmd = command.map_or_else( - || { - // No command — read from stdin. Do *not* pass `-i`; interactive - // mode reads .bashrc, writes prompts to stderr, and can introduce - // just enough latency for VS Code Remote-SSH's platform detection - // to time out and fall back to "windows". Plain `bash` with piped - // stdin already reads commands line-by-line (script mode), which is - // exactly what VS Code's local server expects. - Command::new("/bin/bash") - }, - |command| { - let mut c = Command::new("/bin/bash"); - // Login shell (-l) sources .profile/.bashrc so tool env vars - // (VIRTUAL_ENV, etc.) are available. Callers that need a predictable - // environment opt out via OPENSHELL_NO_LOGIN_SHELL → plain -c. - c.arg(login_shell_flag(no_login_shell)).arg(command); - c - }, - ); + // Resolve a shell present in the sandbox image; minimal images (e.g. Alpine) + // don't ship bash, only `/bin/sh`. Runs in the supervisor, so it inspects + // the sandbox filesystem. No command → read from stdin with no `-i`: + // interactive mode reads .bashrc, writes prompts to stderr, and can add + // just enough latency for VS Code Remote-SSH's platform detection to time + // out and fall back to "windows". A plain shell with piped stdin already + // reads commands line-by-line (script mode), which is what VS Code expects. + let shell = openshell_core::shell::detect_login_shell(); + let mut cmd = build_ssh_shell_command(&shell, command, no_login_shell, None); let (session_user, session_home) = session_user_and_home(policy, workspace.home()); apply_child_env( @@ -1797,8 +1807,40 @@ fn is_loopback_host(host: &str) -> bool { )] mod tests { use super::*; + use std::ffi::OsStr; use std::process::Stdio; + /// Regression test: SSH sessions run the shell they are given, never a + /// hardcoded bash, so sh-only images (e.g. Alpine) work. Covers both the + /// interactive PTY path (`-i` when no command) and the non-PTY path. + #[test] + fn build_ssh_shell_command_uses_given_shell() { + // PTY, no command → given shell + interactive flag. + let cmd = build_ssh_shell_command("/bin/sh", None, false, Some("-i")); + assert_eq!(cmd.get_program(), OsStr::new("/bin/sh")); + assert_eq!(cmd.get_args().collect::>(), vec![OsStr::new("-i")]); + + // Non-PTY, no command → bare shell, no args (reads piped stdin). + let cmd = build_ssh_shell_command("/bin/sh", None, false, None); + assert_eq!(cmd.get_program(), OsStr::new("/bin/sh")); + assert_eq!(cmd.get_args().count(), 0); + + // Explicit command → login-shell flag + command, still on the given shell. + let cmd = build_ssh_shell_command("/bin/sh", Some("echo hi".into()), false, Some("-i")); + assert_eq!(cmd.get_program(), OsStr::new("/bin/sh")); + assert_eq!( + cmd.get_args().collect::>(), + vec![OsStr::new("-lc"), OsStr::new("echo hi")] + ); + + // OPENSHELL_NO_LOGIN_SHELL → plain -c. + let cmd = build_ssh_shell_command("/bin/sh", Some("echo hi".into()), true, None); + assert_eq!( + cmd.get_args().collect::>(), + vec![OsStr::new("-c"), OsStr::new("echo hi")] + ); + } + /// Regression test: the direct-tcpip connect path sets `TCP_NODELAY`. #[tokio::test] async fn connect_in_netns_sets_tcp_nodelay() { diff --git a/deploy/helm/openshell/README.md b/deploy/helm/openshell/README.md index 7dbd7964d0..fb3161a604 100644 --- a/deploy/helm/openshell/README.md +++ b/deploy/helm/openshell/README.md @@ -266,7 +266,7 @@ discovery endpoint or its TLS CA. | server.oidc.audience | string | `"openshell-cli"` | Expected audience claim for the API resource server. This should match the server's --oidc-audience, NOT the CLI client ID. | | server.oidc.caConfigMapName | string | `""` | Name of a ConfigMap containing a CA certificate bundle (key: ca.crt) for verifying the OIDC issuer's TLS certificate. Required when the issuer uses a non-public CA (e.g. OpenShift ingress, private PKI). | | server.oidc.issuer | string | `""` | OIDC issuer URL (e.g. https://keycloak.example.com/realms/openshell). | -| server.oidc.jwksTtl | int | `3600` | JWKS key cache TTL in seconds. | +| server.oidc.jwksTtl | int | `3600` | JWKS key cache TTL in seconds. Must be greater than zero. | | server.oidc.rolesClaim | string | `""` | Dot-separated path to the roles array in the JWT claims. Keycloak: "realm_access.roles", Entra ID: "roles", Okta: "groups". | | server.oidc.scopesClaim | string | `""` | Dot-separated path to the scopes array in the JWT claims. | | server.oidc.userRole | string | `""` | Role name for standard user access. | diff --git a/deploy/helm/openshell/values.yaml b/deploy/helm/openshell/values.yaml index 8f5b6fa51a..453654f790 100644 --- a/deploy/helm/openshell/values.yaml +++ b/deploy/helm/openshell/values.yaml @@ -413,7 +413,7 @@ server: # -- Expected audience claim for the API resource server. # This should match the server's --oidc-audience, NOT the CLI client ID. audience: "openshell-cli" - # -- JWKS key cache TTL in seconds. + # -- JWKS key cache TTL in seconds. Must be greater than zero. jwksTtl: 3600 # -- Dot-separated path to the roles array in the JWT claims. # Keycloak: "realm_access.roles", Entra ID: "roles", Okta: "groups". diff --git a/docs/kubernetes/access-control.mdx b/docs/kubernetes/access-control.mdx index 549cc6679f..3fd7a66ecb 100644 --- a/docs/kubernetes/access-control.mdx +++ b/docs/kubernetes/access-control.mdx @@ -31,7 +31,7 @@ The gateway verifies supervisor JWT-SVIDs with JWT bundles fetched from the SPIF ## OIDC User Authentication -Set `server.oidc.issuer` to enable OIDC. The gateway validates the `Authorization: Bearer ` header on every request against the issuer's JWKS endpoint. +Set `server.oidc.issuer` to enable OIDC. The gateway validates the `Authorization: Bearer ` header on every request against the issuer's JWKS endpoint. It accepts JWTs signed with RS256, RS384, RS512, PS256, PS384, PS512, ES256, ES384, or EdDSA (Ed25519) keys published in the issuer JWKS. Okta tenants that sign access tokens with ES256 work without additional gateway configuration. ```shell helm upgrade openshell \ @@ -53,7 +53,7 @@ The `audience` value must match the client ID configured in your identity provid |---|---|---| | `server.oidc.issuer` | `""` | OIDC issuer URL. Empty disables OIDC. | | `server.oidc.audience` | `openshell-cli` | Expected `aud` claim in the JWT. | -| `server.oidc.jwksTtl` | `3600` | JWKS key cache TTL in seconds. | +| `server.oidc.jwksTtl` | `3600` | JWKS key cache TTL in seconds. Must be greater than zero. | | `server.oidc.rolesClaim` | `""` | Dot-separated path to the roles array in JWT claims. | | `server.oidc.adminRole` | `""` | Role name that grants admin access. | | `server.oidc.userRole` | `""` | Role name that grants standard user access. | diff --git a/docs/reference/gateway-auth.mdx b/docs/reference/gateway-auth.mdx index 5969c43e64..ebfd5c7cbc 100644 --- a/docs/reference/gateway-auth.mdx +++ b/docs/reference/gateway-auth.mdx @@ -91,7 +91,7 @@ The same settings are available through environment variables: |---|---|---| | `OPENSHELL_OIDC_ISSUER` | OIDC issuer URL. The gateway discovers `/.well-known/openid-configuration` from this URL. | None | | `OPENSHELL_OIDC_AUDIENCE` | Expected JWT `aud` claim. | `openshell-cli` | -| `OPENSHELL_OIDC_JWKS_TTL` | JWKS cache TTL in seconds. The gateway also refreshes on an unknown key ID. | `3600` | +| `OPENSHELL_OIDC_JWKS_TTL` | JWKS cache TTL in seconds. The gateway also refreshes on an unknown key ID. Must be greater than zero. | `3600` | | `OPENSHELL_OIDC_ROLES_CLAIM` | Dot-separated claim path containing roles. | `realm_access.roles` | | `OPENSHELL_OIDC_ADMIN_ROLE` | Role required for admin operations. | `openshell-admin` | | `OPENSHELL_OIDC_USER_ROLE` | Role required for standard user operations. | `openshell-user` | @@ -182,13 +182,32 @@ For a headless environment, set `OPENSHELL_NO_BROWSER=1` before registering or l 1. The CLI loads the stored OIDC token bundle. 2. If the access token is expired and a refresh token is available, the CLI refreshes it with the OIDC scopes saved in the gateway metadata. 3. The CLI connects to the gateway and attaches `authorization: Bearer ` metadata to each gRPC request. -4. The gateway validates the JWT signature, issuer, audience, expiration, and key ID against the issuer's JWKS. +4. The gateway validates the JWT signature, issuer, audience, expiration, subject, and key ID against the issuer's JWKS. 5. The gateway extracts roles and optional scopes from the configured claim paths. 6. The gateway authorizes the gRPC method. Platform-scoped methods require the configured admin role. Workspace-scoped methods require the configured user role and a sufficient membership in the target workspace. Admin role holders satisfy user-role checks and bypass workspace membership checks. For the Platform Admin, Workspace Admin, and Workspace User permissions, refer to [Manage Workspaces and Access](/sandboxes/manage-workspaces). +#### JWT validation + +The gateway validates OIDC access tokens against the issuer's JWKS endpoint. It derives the signing algorithm from each JWK's `kty` and `crv` fields, not from the JWT header: + +| JWK `kty` | `crv` | Algorithm | +|---|---|---| +| RSA | — | RS256, RS384, RS512, PS256, PS384, or PS512 | +| EC | P-256 | ES256 | +| EC | P-384 | ES384 | +| OKP | Ed25519 | EdDSA (Ed25519) | + +For EC and OKP keys, `crv` fully determines the algorithm. For RSA keys, the algorithm is selected from the JWK's declared `alg` field when it names one of the six RSA algorithms above; if `alg` is absent (as with Microsoft Entra ID, which omits it entirely), the gateway defaults to RS256. If `alg` names a non-RSA algorithm, the key is treated as contradictory and skipped (see below) rather than falling back to RS256. + +The gateway rejects tokens when the JWT header `alg` does not match the algorithm pinned from the JWK. Tokens must include `iss`, `aud`, `exp`, and `sub` claims. The `iss` and `aud` values must match the configured issuer and audience. + +JWKs with `use: enc`, an `alg` that genuinely contradicts the derived algorithm (for example an RSA key declaring `ES256`), or `key_ops` that excludes `verify` are skipped. The gateway refreshes the JWKS cache when it encounters an unknown key ID, throttled to at most once per second to bound how much an unknown-`kid` lookup can amplify requests against the issuer. If a refresh yields zero usable keys, the gateway keeps serving the previous key set rather than dropping all signing keys and failing every request, but only for up to three times the configured TTL. If the JWKS is still empty after that grace period, the cached keys are evicted and all tokens are rejected until the issuer recovers. + +Common identity providers such as Keycloak (RS256), Microsoft Entra ID (RSA), and Okta (often ES256) publish compatible signing keys. + If `OPENSHELL_OIDC_SCOPES_CLAIM` is set, the gateway also enforces scopes. It accepts space-delimited scope strings such as `scope: "openid sandbox:read"` and JSON arrays such as `scp: ["sandbox:read"]`. Standard OIDC scopes such as `openid`, `profile`, `email`, and `offline_access` are ignored for authorization. `openshell:all` grants access to all scoped methods. Supervisor-to-gateway RPCs do not use user OIDC tokens or mTLS user identity. Each sandbox supervisor presents a gateway-minted `Authorization: Bearer` token scoped to its sandbox ID. On Kubernetes, the Kubernetes compute driver validates the projected ServiceAccount token with TokenReview, verifies the live pod UID and controlling `Sandbox` ownerReference, and returns the authenticated sandbox ID to the gateway. The gateway verifies that sandbox still exists before minting its JWT. Log upload, policy status, credential environment lookup, inference bundle lookup, and sandbox config sync run with sandbox-restricted scope, while CLI users authenticate with OIDC, edge auth, local mTLS user authentication, or an explicitly enabled unauthenticated local developer mode. `GetInferenceBundle` returns route material that includes provider credentials, so it requires a sandbox principal; user callers manage inference configuration through the user-facing inference APIs instead. diff --git a/docs/reference/gateway-config.mdx b/docs/reference/gateway-config.mdx index fa7d17a417..1c846c29a8 100644 --- a/docs/reference/gateway-config.mdx +++ b/docs/reference/gateway-config.mdx @@ -105,7 +105,7 @@ disable_tls = false # Shared driver defaults. These inherit into [openshell.drivers.] tables # when the driver-specific table does not override them. -default_image = "ghcr.io/nvidia/openshell/sandbox:latest" +default_image = "ghcr.io/nvidia/openshell-community/sandboxes/base:latest" # Defaults to the gateway version; override to pin a specific build. # supervisor_image = "ghcr.io/nvidia/openshell/supervisor:" client_tls_secret_name = "openshell-client-tls" @@ -174,7 +174,7 @@ service_name = "openshell-gateway" [openshell.gateway.oidc] issuer = "https://idp.example.com/realms/openshell" audience = "openshell-cli" -jwks_ttl_secs = 3600 +jwks_ttl_secs = 3600 # Must be greater than zero. roles_claim = "realm_access.roles" admin_role = "openshell-admin" user_role = "openshell-user" @@ -481,7 +481,7 @@ workspace_mode = "shared" # gateway_id = "openshell" namespace = "agents" service_account_name = "openshell-sandbox" -default_image = "ghcr.io/nvidia/openshell/sandbox:latest" +default_image = "ghcr.io/nvidia/openshell-community/sandboxes/base:latest" image_pull_policy = "IfNotPresent" image_pull_secrets = ["regcred"] # Defaults to the gateway version; override to pin a specific build. @@ -604,7 +604,7 @@ compute_drivers = ["docker"] [openshell.drivers.docker] socket_path = "/var/run/docker.sock" -default_image = "ghcr.io/nvidia/openshell/sandbox:latest" +default_image = "ghcr.io/nvidia/openshell-community/sandboxes/base:latest" # Docker vocabulary: Always | IfNotPresent | Never. Empty behaves like IfNotPresent. image_pull_policy = "IfNotPresent" sandbox_namespace = "docker-dev" @@ -648,7 +648,7 @@ compute_drivers = ["podman"] # asks the podman CLI where its socket is, and fails to start if neither finds # one. Set this to pin a specific Podman machine instead. socket_path = "/run/user/1000/podman/podman.sock" -default_image = "ghcr.io/nvidia/openshell/sandbox:latest" +default_image = "ghcr.io/nvidia/openshell-community/sandboxes/base:latest" image_pull_policy = "missing" # always | missing | never | newer grpc_endpoint = "https://host.containers.internal:17670" # The gateway overwrites gateway_port from bind_address at runtime. @@ -781,10 +781,10 @@ compute_drivers = ["vm"] state_dir = "/var/lib/openshell/vm" # Where the gateway looks for the openshell-driver-vm subprocess binary. driver_dir = "/usr/local/libexec/openshell" -default_image = "ghcr.io/nvidia/openshell/sandbox:latest" +default_image = "ghcr.io/nvidia/openshell-community/sandboxes/base:latest" grpc_endpoint = "https://host.containers.internal:17670" # Empty falls back to default_image. -bootstrap_image = "ghcr.io/nvidia/openshell/sandbox:latest" +bootstrap_image = "ghcr.io/nvidia/openshell-community/sandboxes/base:latest" krun_log_level = 1 vcpus = 2 mem_mib = 2048 diff --git a/docs/sandboxes/manage-sandboxes.mdx b/docs/sandboxes/manage-sandboxes.mdx index 96538eeeaa..31c7182e5f 100644 --- a/docs/sandboxes/manage-sandboxes.mdx +++ b/docs/sandboxes/manage-sandboxes.mdx @@ -23,9 +23,11 @@ openshell sandbox create -- claude The trailing command is the sandbox's canonical main process. OpenShell starts it once, streams its output, and returns its exit status. Exit code 0 leaves a retained sandbox in `Completed`; a nonzero exit leaves it in `Error` with a -`MainProcessFailed` condition. With no trailing command, OpenShell -starts `/bin/bash -l` in a retained pseudo-terminal. Add `--detach` to create -the sandbox without attaching: +`MainProcessFailed` condition. With no trailing command, OpenShell starts a +login shell in a retained pseudo-terminal: `/bin/bash -l` when the image +provides bash, otherwise a shell detected in the image such as `/bin/sh` on +minimal bases like Alpine. Add `--detach` to create the sandbox without +attaching: ```shell openshell sandbox create --name worker --detach -- ./worker diff --git a/examples/spiffe-token-exchange-demo/podman/README.md b/examples/spiffe-token-exchange-demo/podman/README.md index d8fdde4b4b..b30c4830dd 100644 --- a/examples/spiffe-token-exchange-demo/podman/README.md +++ b/examples/spiffe-token-exchange-demo/podman/README.md @@ -109,7 +109,7 @@ TOKEN_ISSUER_PORT=18080 MANAGED_GATEWAY_PORT=18082 MANAGED_GATEWAY_HEALTH_PORT=18083 GATEWAY_IMAGE=ghcr.io/nvidia/openshell/gateway:latest -SANDBOX_IMAGE=ghcr.io/nvidia/openshell/sandbox:latest +SANDBOX_IMAGE=ghcr.io/nvidia/openshell-community/sandboxes/base:latest SUPERVISOR_IMAGE=ghcr.io/nvidia/openshell/supervisor:latest SANDBOX_IMAGE_PULL_POLICY=missing PODMAN_STOP_TIMEOUT_SECS=3 diff --git a/rfc/0003-gateway-configuration/README.md b/rfc/0003-gateway-configuration/README.md index 2b7c095065..d6d4750f25 100644 --- a/rfc/0003-gateway-configuration/README.md +++ b/rfc/0003-gateway-configuration/README.md @@ -118,7 +118,7 @@ scopes_claim = "" # empty disables scope enforcement [openshell.drivers.kubernetes] namespace = "openshell" -default_image = "ghcr.io/nvidia/openshell/sandbox:latest" +default_image = "ghcr.io/nvidia/openshell-community/sandboxes/base:latest" image_pull_policy = "IfNotPresent" supervisor_image = "ghcr.io/nvidia/openshell/supervisor:latest" supervisor_image_pull_policy = "IfNotPresent" @@ -128,7 +128,7 @@ host_gateway_ip = "10.0.0.1" ssh_socket_path = "/run/openshell/ssh.sock" [openshell.drivers.docker] -default_image = "ghcr.io/nvidia/openshell/sandbox:latest" +default_image = "ghcr.io/nvidia/openshell-community/sandboxes/base:latest" image_pull_policy = "IfNotPresent" sandbox_namespace = "docker-dev" grpc_endpoint = "https://host.openshell.internal:8080" @@ -141,7 +141,7 @@ guest_tls_key = "/etc/openshell/certs/client-key.pem" [openshell.drivers.podman] socket_path = "/run/podman/podman.sock" -default_image = "ghcr.io/nvidia/openshell/sandbox:latest" +default_image = "ghcr.io/nvidia/openshell-community/sandboxes/base:latest" image_pull_policy = "missing" # Podman vocabulary: always | missing | never | newer supervisor_image = "ghcr.io/nvidia/openshell/supervisor:latest" network_name = "openshell" @@ -229,7 +229,7 @@ compute_drivers = ["kubernetes"] [openshell.drivers.kubernetes] namespace = "agents" -default_image = "ghcr.io/nvidia/openshell/sandbox:0.9.0" +default_image = "ghcr.io/nvidia/openshell-community/sandboxes/base:latest" supervisor_image = "ghcr.io/nvidia/openshell/supervisor:0.9.0" grpc_endpoint = "https://openshell-gateway.agents.svc:8080" ``` @@ -254,7 +254,7 @@ gateway: drivers: kubernetes: namespace: agents - default_image: ghcr.io/nvidia/openshell/sandbox:0.9.0 + default_image: ghcr.io/nvidia/openshell-community/sandboxes/base:latest supervisor_image: ghcr.io/nvidia/openshell/supervisor:0.9.0 ```