diff --git a/.github/workflows/e2e-test.yml b/.github/workflows/e2e-test.yml index eae744f252..d8f33f7016 100644 --- a/.github/workflows/e2e-test.yml +++ b/.github/workflows/e2e-test.yml @@ -310,6 +310,12 @@ jobs: socat \ zstd + - name: Validate VM host tools + run: | + command -v mke2fs + command -v mkfs.ext4 + command -v debugfs + - name: Install mise run: | curl https://mise.run | MISE_VERSION=v2026.4.25 sh diff --git a/Cargo.lock b/Cargo.lock index b412467610..268da3982d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4354,6 +4354,7 @@ version = "0.0.0" dependencies = [ "base64 0.22.1", "crossterm 0.28.1", + "indexmap", "miette", "openshell-bootstrap", "openshell-core", diff --git a/Cargo.toml b/Cargo.toml index 7081fe97e2..4ec6a0d44f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -110,6 +110,7 @@ pin-project-lite = "0.2" tokio-stream = "0.1" protobuf-src = "1.1.0" url = "2" +indexmap = "2" # Database sqlx = { version = "0.8", features = ["runtime-tokio-rustls", "postgres", "sqlite", "migrate"] } diff --git a/crates/openshell-cli/src/commands/common.rs b/crates/openshell-cli/src/commands/common.rs new file mode 100644 index 0000000000..7fa5cd1fec --- /dev/null +++ b/crates/openshell-cli/src/commands/common.rs @@ -0,0 +1,950 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Shared helpers, types, and parsing utilities used across CLI command groups. + +use chrono::DateTime; +use dialoguer::{Confirm, theme::ColorfulTheme}; +use indicatif::{MultiProgress, ProgressBar, ProgressStyle}; +use miette::{IntoDiagnostic, Result}; +use openshell_core::progress::{ + PROGRESS_ACTIVE_DETAIL_KEY, PROGRESS_ACTIVE_STEP_KEY, PROGRESS_COMPLETE_LABEL_KEY, + PROGRESS_COMPLETE_STEP_KEY, PROGRESS_STEP_PULLING_IMAGE, PROGRESS_STEP_REQUESTING_SANDBOX, + PROGRESS_STEP_STARTING_SANDBOX, +}; +use openshell_core::proto::{ + PlatformEvent, SandboxPhase, SandboxPolicy, SettingValue, setting_value, +}; +use openshell_core::settings::{self, SettingValueKind}; +use owo_colors::OwoColorize; +use std::collections::HashMap; +use std::io::IsTerminal; +use std::process::Command; +use std::time::{Duration, Instant}; + +// --------------------------------------------------------------------------- +// View types +// --------------------------------------------------------------------------- + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum PolicyGetView { + Metadata, + Base, + Full, +} + +impl PolicyGetView { + pub fn from_flags(base: bool, full: bool) -> Self { + match (base, full) { + (true, _) => Self::Base, + (false, true) => Self::Full, + (false, false) => Self::Metadata, + } + } + + pub(crate) fn includes_policy(self) -> bool { + matches!(self, Self::Base | Self::Full) + } +} + +// --------------------------------------------------------------------------- +// Formatting / display helpers +// --------------------------------------------------------------------------- + +/// Convert a sandbox phase integer to a human-readable string. +pub fn phase_name(phase: i32) -> &'static str { + match SandboxPhase::try_from(phase) { + Ok(SandboxPhase::Unspecified) => "Unspecified", + Ok(SandboxPhase::Provisioning) => "Provisioning", + Ok(SandboxPhase::Ready) => "Ready", + Ok(SandboxPhase::Error) => "Error", + Ok(SandboxPhase::Deleting) => "Deleting", + Ok(SandboxPhase::Unknown) | Err(_) => "Unknown", + } +} + +/// Format milliseconds since Unix epoch as a `YYYY-MM-DD HH:MM:SS` UTC string. +pub fn format_epoch_ms(ms: i64) -> String { + use std::time::UNIX_EPOCH; + + let Ok(ms_u64) = u64::try_from(ms) else { + return "-".to_string(); + }; + let Ok(time) = UNIX_EPOCH + .checked_add(Duration::from_millis(ms_u64)) + .ok_or(()) + else { + return "-".to_string(); + }; + let Ok(dur) = time.duration_since(UNIX_EPOCH) else { + return "-".to_string(); + }; + + let secs = dur.as_secs(); + let days = secs / 86400; + let time_of_day = secs % 86400; + let hours = time_of_day / 3600; + let minutes = (time_of_day % 3600) / 60; + let seconds = time_of_day % 60; + + let (y, m, d) = civil_from_days(days); + format!("{y:04}-{m:02}-{d:02} {hours:02}:{minutes:02}:{seconds:02}") +} + +/// Convert days since 1970-01-01 to (year, month, day). +/// Algorithm from Howard Hinnant's `chrono`-compatible date library. +fn civil_from_days(days: u64) -> (i64, u64, u64) { + let z = days.cast_signed() + 719_468; + let era = if z >= 0 { z } else { z - 146_096 } / 146_097; + let doe = (z - era * 146_097).cast_unsigned(); + let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365; + let y = yoe.cast_signed() + era * 400; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let d = doy - (153 * mp + 2) / 5 + 1; + let m = if mp < 10 { mp + 3 } else { mp - 9 }; + let y = if m <= 2 { y + 1 } else { y }; + (y, m, d) +} + +pub fn format_optional_epoch_ms(ms: i64) -> String { + if ms > 0 { + format_epoch_ms(ms) + } else { + "-".to_string() + } +} + +/// Format a duration as a compact elapsed time string, e.g. `(3s)` or `(1m 12s)`. +pub fn format_elapsed(d: Duration) -> String { + let secs = d.as_secs(); + if secs < 60 { + format!("({secs}s)") + } else { + let mins = secs / 60; + let rem = secs % 60; + format!("({mins}m {rem}s)") + } +} + +/// Format a total elapsed time for non-interactive mode timestamps. +pub fn format_timestamp(d: Duration) -> String { + let secs = d.as_secs_f64(); + format!("[{secs:.1}s]") +} + +/// Format a millisecond timestamp into a readable string. +pub fn format_timestamp_ms(ms: i64) -> String { + if ms <= 0 { + return "-".to_string(); + } + let secs = ms / 1000; + let mins = (secs / 60) % 60; + let hours = (secs / 3600) % 24; + let days = secs / 86400; + if days > 0 { + format!("{days}d {hours:02}:{mins:02}") + } else { + format!("{hours:02}:{mins:02}") + } +} + +pub fn truncate_status_field(value: &str, max_chars: usize) -> String { + if value.is_empty() { + return "-".to_string(); + } + let mut chars = value.chars(); + let truncated = chars.by_ref().take(max_chars).collect::(); + if chars.next().is_some() { + format!("{truncated}...") + } else { + truncated + } +} + +pub fn truncate_display(value: &str, max_width: usize) -> String { + if value.chars().count() <= max_width { + return value.to_string(); + } + + let keep = max_width.saturating_sub(3); + let mut truncated = value.chars().take(keep).collect::(); + truncated.push_str("..."); + truncated +} + +pub fn short_hash(hash: &str) -> &str { + if hash.len() >= 12 { &hash[..12] } else { hash } +} + +pub fn non_empty_or<'a>(value: &'a str, fallback: &'a str) -> &'a str { + if value.is_empty() { fallback } else { value } +} + +pub fn format_setting_value(value: Option<&SettingValue>) -> String { + let Some(value) = value.and_then(|v| v.value.as_ref()) else { + return "".to_string(); + }; + match value { + setting_value::Value::StringValue(v) => v.clone(), + setting_value::Value::BoolValue(v) => v.to_string(), + setting_value::Value::IntValue(v) => v.to_string(), + setting_value::Value::BytesValue(v) => format!("", v.len()), + } +} + +// --------------------------------------------------------------------------- +// YAML / policy display +// --------------------------------------------------------------------------- + +pub fn print_yaml_line(line: &str) { + let trimmed = line.trim_start(); + let indent = &line[..line.len() - trimmed.len()]; + + if let Some(rest) = trimmed.strip_prefix("- ") { + print!("{indent}"); + print!("{}", "- ".dimmed()); + print!("{rest}"); + println!(); + return; + } + + if let Some(colon_pos) = trimmed.find(':') { + let key = &trimmed[..colon_pos]; + let after_colon = &trimmed[colon_pos + 1..]; + + print!("{indent}"); + print!("{}", key.dimmed()); + print!("{}", ":".dimmed()); + + if after_colon.is_empty() { + // Key with nested content (no value on this line) + } else if let Some(value) = after_colon.strip_prefix(' ') { + print!(" {value}"); + } else { + print!("{after_colon}"); + } + println!(); + return; + } + + println!("{line}"); +} + +/// Print sandbox policy as YAML with dimmed keys. +pub fn print_sandbox_policy(policy: &SandboxPolicy) { + println!("{}", "Policy:".cyan().bold()); + println!(); + if let Ok(yaml_str) = openshell_policy::serialize_sandbox_policy(policy) { + for line in yaml_str.lines() { + if line == "---" { + continue; + } + print!(" "); + print_yaml_line(line); + } + } +} + +pub fn print_policy_merge_warnings(warnings: &[openshell_policy::PolicyMergeWarning]) { + for warning in warnings { + eprintln!("{} {}", "!".yellow().bold(), warning); + } +} + +// --------------------------------------------------------------------------- +// Provisioning display +// --------------------------------------------------------------------------- + +/// Known provisioning steps derived from Kubernetes events and sandbox lifecycle. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +pub enum ProvisioningStep { + /// Sandbox CRD created, waiting for pod to be scheduled. + RequestingSandbox, + /// Pulling the sandbox container image. + PullingSandboxImage, + /// Container is starting up. + StartingSandbox, +} + +impl ProvisioningStep { + /// Human-readable label for a completed step. + pub fn completed_label(self) -> &'static str { + match self { + Self::RequestingSandbox => "Sandbox allocated", + Self::PullingSandboxImage => "Image pulled", + Self::StartingSandbox => "Sandbox ready", + } + } + + /// Human-readable label for an in-progress step (shown on the spinner). + pub fn active_label(self) -> &'static str { + match self { + Self::RequestingSandbox => "Requesting sandbox...", + Self::PullingSandboxImage => "Pulling image...", + Self::StartingSandbox => "Starting sandbox...", + } + } +} + +/// Live-updating display showing a provisioning step checklist with spinner. +/// +/// Completed steps are printed as static `✓ Step` lines. The current +/// in-progress step is shown on a spinner with elapsed time. +pub struct ProvisioningDisplay { + mp: MultiProgress, + spinner: ProgressBar, + /// Blank line below the spinner so progress doesn't sit flush against + /// the bottom of the terminal. + spacer: ProgressBar, + /// Steps that have been completed, in order. + completed_steps: Vec, + /// Progress bars for completed steps (so they can be cleared). + completed_bars: Vec, + /// The currently active step label (shown on the spinner). + active_label: String, + /// Detail text shown next to the active step (e.g. image name). + active_detail: String, + /// When the current active step started (for elapsed time). + step_start: Instant, +} + +impl ProvisioningDisplay { + pub fn new() -> Self { + let mp = MultiProgress::new(); + + let spinner = mp.add(ProgressBar::new_spinner()); + spinner.set_style( + ProgressStyle::with_template("{spinner:.cyan} {msg} ({elapsed})") + .unwrap_or_else(|_| ProgressStyle::default_spinner()), + ); + spinner.enable_steady_tick(Duration::from_millis(120)); + + let spacer = mp.add(ProgressBar::new(0)); + spacer.set_style( + ProgressStyle::with_template("{msg}").unwrap_or_else(|_| ProgressStyle::default_bar()), + ); + spacer.set_message(""); + + let now = Instant::now(); + Self { + mp, + spinner, + spacer, + completed_steps: Vec::new(), + completed_bars: Vec::new(), + active_label: ProvisioningStep::RequestingSandbox + .active_label() + .to_string(), + active_detail: String::new(), + step_start: now, + } + } + + /// Record a completed provisioning step with a custom label. + pub fn complete_step_with_label(&mut self, step: ProvisioningStep, label: &str) { + if self.completed_steps.contains(&step) { + return; + } + self.completed_steps.push(step); + + let elapsed = self.step_start.elapsed(); + let elapsed_str = format_elapsed(elapsed); + + let bar = self.mp.insert_before(&self.spinner, ProgressBar::new(0)); + bar.set_style( + ProgressStyle::with_template("{msg}").unwrap_or_else(|_| ProgressStyle::default_bar()), + ); + bar.set_message(format!( + "{} {} {}", + "\u{2713}".green().bold(), + label, + elapsed_str.dimmed() + )); + bar.finish(); + self.completed_bars.push(bar); + + self.step_start = Instant::now(); + self.spinner.reset_elapsed(); + self.active_detail.clear(); + } + + /// Set the active (in-progress) step shown on the spinner. + pub fn set_active(&mut self, label: &str) { + self.active_label = label.to_string(); + self.active_detail.clear(); + self.spinner.reset_elapsed(); + self.step_start = Instant::now(); + self.update_spinner(); + } + + /// Set the active step from a known provisioning step enum. + pub fn set_active_step(&mut self, step: ProvisioningStep) { + self.set_active(step.active_label()); + } + + /// Set detail text shown alongside the active step (e.g. image name). + pub fn set_active_detail(&mut self, detail: &str) { + self.active_detail = detail.to_string(); + self.update_spinner(); + } + + fn update_spinner(&self) { + let msg = if self.active_detail.is_empty() { + self.active_label.clone() + } else { + format!("{} {}", self.active_label, self.active_detail.dimmed()) + }; + self.spinner.set_message(msg); + } + + /// Finish with an error message shown on the last step line. + pub fn finish_error(&self, msg: &str) { + let _ = self + .mp + .println(format!("{} {}", "\u{2717}".red().bold(), msg.red())); + self.spinner.finish_and_clear(); + } + + /// Print a line above the progress bars (for static header content). + pub fn println(&self, msg: &str) { + let _ = self.mp.println(msg); + } + + /// Clear all progress output (spinner, spacer, and completed step lines). + pub fn clear(&self) { + self.spacer.finish_and_clear(); + self.spinner.finish_and_clear(); + for bar in &self.completed_bars { + bar.finish_and_clear(); + } + } +} + +// --------------------------------------------------------------------------- +// Provisioning progress event handling +// --------------------------------------------------------------------------- + +pub fn progress_step_from_metadata(value: &str) -> Option { + match value { + PROGRESS_STEP_REQUESTING_SANDBOX => Some(ProvisioningStep::RequestingSandbox), + PROGRESS_STEP_PULLING_IMAGE => Some(ProvisioningStep::PullingSandboxImage), + PROGRESS_STEP_STARTING_SANDBOX => Some(ProvisioningStep::StartingSandbox), + _ => None, + } +} + +pub fn noninteractive_active_label(step: ProvisioningStep) -> String { + step.active_label().trim_end_matches('.').to_string() +} + +pub fn handle_platform_progress_event( + event: &PlatformEvent, + display: &mut Option, + provision_start: Instant, +) -> bool { + let completed_step = event + .metadata + .get(PROGRESS_COMPLETE_STEP_KEY) + .and_then(|step| progress_step_from_metadata(step)); + let active_step = event + .metadata + .get(PROGRESS_ACTIVE_STEP_KEY) + .and_then(|step| progress_step_from_metadata(step)); + let active_detail = event + .metadata + .get(PROGRESS_ACTIVE_DETAIL_KEY) + .filter(|detail| !detail.is_empty()); + + let handled = completed_step.is_some() || active_step.is_some() || active_detail.is_some(); + if !handled { + return false; + } + + if let Some(step) = completed_step { + let label = event + .metadata + .get(PROGRESS_COMPLETE_LABEL_KEY) + .map_or_else(|| step.completed_label(), String::as_str); + if let Some(d) = display.as_mut() { + d.complete_step_with_label(step, label); + } else { + let ts = format_timestamp(provision_start.elapsed()); + println!("{} {}", ts.dimmed(), label); + } + } + + if let Some(step) = active_step + && let Some(d) = display.as_mut() + { + d.set_active_step(step); + } + + if let Some(detail) = active_detail { + if let Some(d) = display.as_mut() { + d.set_active_detail(detail); + } else { + let ts = format_timestamp(provision_start.elapsed()); + if let Some(step) = active_step { + println!( + "{} {} {}", + ts.dimmed(), + noninteractive_active_label(step), + detail + ); + } else { + println!("{} {}", ts.dimmed(), detail); + } + } + } + + true +} + +pub fn is_provisioning_progress_event(event: &PlatformEvent) -> bool { + if event.metadata.contains_key(PROGRESS_COMPLETE_STEP_KEY) + || event.metadata.contains_key(PROGRESS_ACTIVE_STEP_KEY) + || event.metadata.contains_key(PROGRESS_ACTIVE_DETAIL_KEY) + { + return true; + } + + event.source == "vm" + && matches!( + event.reason.as_str(), + "PullingLayer" + | "ResolvingImage" + | "AuthenticatingRegistry" + | "FetchingManifest" + | "CacheHit" + | "CacheMiss" + | "WaitingForImageCacheLock" + | "ExportingRootfs" + | "PreparingRootfs" + | "CreatingRootDisk" + | "PreparingOverlay" + | "Started" + ) +} + +// --------------------------------------------------------------------------- +// Sandbox header +// --------------------------------------------------------------------------- + +pub fn print_sandbox_header( + sandbox: &openshell_core::proto::Sandbox, + display: Option<&ProvisioningDisplay>, +) { + use openshell_core::ObjectName; + + let lines = [ + String::new(), + format!( + "{} {}", + "Created sandbox:".cyan().bold(), + sandbox.object_name().bold() + ), + String::new(), + ]; + match display { + Some(d) => { + for line in lines { + d.println(&line); + } + } + None => { + for line in lines { + println!("{line}"); + } + } + } +} + +// --------------------------------------------------------------------------- +// Sandbox provisioning helpers +// --------------------------------------------------------------------------- + +pub fn ready_false_condition_message( + status: Option<&openshell_core::proto::SandboxStatus>, +) -> Option { + let condition = status?.conditions.iter().find(|condition| { + condition.r#type == "Ready" && condition.status.eq_ignore_ascii_case("false") + })?; + + if condition.message.is_empty() { + if condition.reason.is_empty() { + None + } else { + Some(condition.reason.clone()) + } + } else if condition.reason.is_empty() { + Some(condition.message.clone()) + } else { + Some(format!("{}: {}", condition.reason, condition.message)) + } +} + +pub fn provisioning_timeout_message( + timeout_secs: u64, + resource_requirements: Option<&openshell_core::proto::ResourceRequirements>, + condition_message: Option<&str>, +) -> String { + let mut message = format!("sandbox provisioning timed out after {timeout_secs}s"); + + if let Some(condition_message) = condition_message.filter(|msg| !msg.is_empty()) { + message.push_str(". Last reported status: "); + message.push_str(condition_message); + } + + if resource_requirements.is_some_and(|requirements| requirements.gpu.is_some()) { + message.push_str( + ". Hint: this may be because the available GPU is already in use by another sandbox.", + ); + } + + message +} + +// --------------------------------------------------------------------------- +// Settings helpers +// --------------------------------------------------------------------------- + +pub fn parse_cli_setting_value(key: &str, raw_value: &str) -> Result { + let setting = settings::setting_for_key(key).ok_or_else(|| { + miette::miette!( + "unknown setting key '{}'. Allowed keys: {}", + key, + settings::registered_keys_csv() + ) + })?; + + let value = match setting.kind { + SettingValueKind::String => { + // Reject typos client-side so `openshell settings set ... + // proposal_approval_mode autom` errors immediately instead of + // round-tripping through the server. The server enforces the + // same check independently for non-CLI callers. + setting + .validate_string_value(raw_value) + .map_err(|allowed| { + miette::miette!( + "invalid value '{}' for key '{}'; expected one of: {}", + raw_value, + key, + allowed.join(", ") + ) + })?; + setting_value::Value::StringValue(raw_value.to_string()) + } + SettingValueKind::Int => { + let parsed = raw_value.trim().parse::().map_err(|_| { + miette::miette!( + "invalid int value '{}' for key '{}'; expected base-10 integer", + raw_value, + key + ) + })?; + setting_value::Value::IntValue(parsed) + } + SettingValueKind::Bool => { + let parsed = settings::parse_bool_like(raw_value).ok_or_else(|| { + miette::miette!( + "invalid bool value '{}' for key '{}'; expected one of: true,false,yes,no,1,0", + raw_value, + key + ) + })?; + setting_value::Value::BoolValue(parsed) + } + }; + + Ok(SettingValue { value: Some(value) }) +} + +pub fn confirm_global_setting_takeover(key: &str, yes: bool) -> Result<()> { + if yes { + return Ok(()); + } + + if !std::io::stdin().is_terminal() || !std::io::stdout().is_terminal() { + return Err(miette::miette!( + "global setting updates require confirmation; pass --yes in non-interactive mode" + )); + } + + let proceed = Confirm::with_theme(&ColorfulTheme::default()) + .with_prompt(format!( + "Setting '{key}' globally will disable sandbox-level management for this key. Continue?" + )) + .default(false) + .interact() + .into_diagnostic()?; + + if !proceed { + return Err(miette::miette!("aborted by user")); + } + + Ok(()) +} + +pub fn confirm_global_setting_delete(key: &str, yes: bool) -> Result<()> { + if yes { + return Ok(()); + } + + if !std::io::stdin().is_terminal() || !std::io::stdout().is_terminal() { + return Err(miette::miette!( + "global setting deletes require confirmation; pass --yes in non-interactive mode" + )); + } + + let proceed = Confirm::with_theme(&ColorfulTheme::default()) + .with_prompt(format!( + "Deleting global setting '{key}' re-enables sandbox-level management for this key. Continue?" + )) + .default(false) + .interact() + .into_diagnostic()?; + + if !proceed { + return Err(miette::miette!("aborted by user")); + } + + Ok(()) +} + +/// Parse a duration string like "5m", "1h", "30s" into milliseconds. +pub fn parse_duration_to_ms(s: &str) -> Result { + let s = s.trim(); + if s.is_empty() { + return Err(miette::miette!("empty duration string")); + } + let (num_str, unit) = s.split_at(s.len() - 1); + let num: i64 = num_str + .parse() + .map_err(|_| miette::miette!("invalid duration: {s} (expected e.g. 5m, 1h, 30s)"))?; + let multiplier = match unit { + "s" => 1_000, + "m" => 60_000, + "h" => 3_600_000, + _ => { + return Err(miette::miette!( + "unknown duration unit: {unit} (use s, m, or h)" + )); + } + }; + Ok(num * multiplier) +} + +// --------------------------------------------------------------------------- +// Parsing utilities +// --------------------------------------------------------------------------- + +pub fn parse_key_value_pairs(items: &[String], flag: &str) -> Result> { + let mut map = HashMap::new(); + + for item in items { + let Some((key, value)) = item.split_once('=') else { + return Err(miette::miette!("{flag} expects KEY=VALUE, got '{item}'")); + }; + + let key = key.trim(); + if key.is_empty() { + return Err(miette::miette!("{flag} key cannot be empty")); + } + + map.insert(key.to_string(), value.to_string()); + } + + Ok(map) +} + +pub fn parse_env_pairs(items: &[String]) -> Result> { + let map = parse_key_value_pairs(items, "--env")?; + for key in map.keys() { + if !is_valid_env_name(key) { + return Err(miette::miette!( + "--env key must match [A-Za-z_][A-Za-z0-9_]*; got '{key}'" + )); + } + if key.starts_with("OPENSHELL_") { + return Err(miette::miette!( + "--env keys starting with OPENSHELL_ are reserved; got '{key}'" + )); + } + } + Ok(map) +} + +/// Resolve `--secret-material-env KEY[=ENVVAR]` values from the CLI process +/// environment (`ENVVAR` defaults to `KEY`) so secrets never transit argv. +pub fn parse_secret_material_env_pairs(items: &[String]) -> Result> { + let mut map = HashMap::new(); + + for item in items { + let (key, env_name) = match item.split_once('=') { + Some((key, env_name)) => (key.trim(), env_name.trim()), + None => (item.trim(), item.trim()), + }; + if key.is_empty() { + return Err(miette::miette!("--secret-material-env key cannot be empty")); + } + if env_name.is_empty() { + return Err(miette::miette!( + "--secret-material-env {key} names an empty environment variable" + )); + } + + let value = std::env::var(env_name).map_err(|_| { + miette::miette!( + "--secret-material-env {key} requires local env var '{env_name}' to be set to a non-empty value" + ) + })?; + if value.trim().is_empty() { + return Err(miette::miette!( + "--secret-material-env {key} requires local env var '{env_name}' to be set to a non-empty value" + )); + } + + if map.contains_key(key) { + return Err(miette::miette!( + "--secret-material-env key '{key}' supplied more than once" + )); + } + map.insert(key.to_string(), value); + } + + Ok(map) +} + +pub fn is_valid_env_name(key: &str) -> bool { + let mut bytes = key.bytes(); + let Some(first) = bytes.next() else { + return false; + }; + if !(first == b'_' || first.is_ascii_alphabetic()) { + return false; + } + bytes.all(|b| b == b'_' || b.is_ascii_alphanumeric()) +} + +pub fn parse_credential_pairs(items: &[String]) -> Result> { + let mut map = HashMap::new(); + + for item in items { + if let Some((key, value)) = item.split_once('=') { + let key = key.trim(); + if key.is_empty() { + return Err(miette::miette!("--credential key cannot be empty")); + } + map.insert(key.to_string(), value.to_string()); + continue; + } + + let key = item.trim(); + if key.is_empty() { + return Err(miette::miette!("--credential key cannot be empty")); + } + + let value = std::env::var(key).map_err(|_| { + miette::miette!( + "--credential {key} requires local env var '{key}' to be set to a non-empty value" + ) + })?; + + if value.trim().is_empty() { + return Err(miette::miette!( + "--credential {key} requires local env var '{key}' to be set to a non-empty value" + )); + } + + map.insert(key.to_string(), value); + } + + Ok(map) +} + +pub fn parse_credential_expiry_cli_value(value: &str) -> std::result::Result { + parse_credential_expiry_value(value, None).map_err(|err| err.to_string()) +} + +fn credential_expiry_value_error(key: Option<&str>, detail: &str) -> miette::Report { + key.map_or_else( + || miette::miette!("--credential-expires-at value {detail}"), + |key| miette::miette!("--credential-expires-at value for '{key}' {detail}"), + ) +} + +pub fn parse_credential_expiry_value(value: &str, key: Option<&str>) -> Result { + let value = value.trim(); + if value.is_empty() { + return Err(credential_expiry_value_error(key, "cannot be empty")); + } + + if let Ok(value_ms) = value.parse::() { + if value_ms < 0 { + return Err(credential_expiry_value_error( + key, + "must be greater than or equal to 0", + )); + } + return Ok(value_ms); + } + + let parsed = DateTime::parse_from_rfc3339(value).map_err(|_| { + credential_expiry_value_error( + key, + "must be a Unix epoch millisecond timestamp or RFC3339 timestamp", + ) + })?; + let value_ms = parsed.timestamp_millis(); + if value_ms < 0 { + return Err(credential_expiry_value_error( + key, + "must be greater than or equal to 0", + )); + } + + Ok(value_ms) +} + +pub fn parse_credential_expiry_pairs(items: &[String]) -> Result> { + let mut map = HashMap::new(); + + for item in items { + let Some((key, value)) = item.split_once('=') else { + return Err(miette::miette!( + "--credential-expires-at expects KEY=TIMESTAMP, got '{item}'" + )); + }; + let key = key.trim(); + if key.is_empty() { + return Err(miette::miette!( + "--credential-expires-at key cannot be empty" + )); + } + let value = parse_credential_expiry_value(value, Some(key))?; + map.insert(key.to_string(), value); + } + + Ok(map) +} + +// --------------------------------------------------------------------------- +// Git environment helpers +// --------------------------------------------------------------------------- + +pub fn scrub_git_env(command: &mut Command) -> &mut Command { + for key in [ + "GIT_DIR", + "GIT_WORK_TREE", + "GIT_INDEX_FILE", + "GIT_PREFIX", + "GIT_COMMON_DIR", + "GIT_OBJECT_DIRECTORY", + "GIT_ALTERNATE_OBJECT_DIRECTORIES", + ] { + command.env_remove(key); + } + command +} diff --git a/crates/openshell-cli/src/commands/mod.rs b/crates/openshell-cli/src/commands/mod.rs new file mode 100644 index 0000000000..ab20f224db --- /dev/null +++ b/crates/openshell-cli/src/commands/mod.rs @@ -0,0 +1,4 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +pub mod common; diff --git a/crates/openshell-cli/src/lib.rs b/crates/openshell-cli/src/lib.rs index 156668951a..ecdf54f28f 100644 --- a/crates/openshell-cli/src/lib.rs +++ b/crates/openshell-cli/src/lib.rs @@ -9,6 +9,7 @@ pub(crate) static TEST_ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); pub mod auth; +pub(crate) mod commands; pub mod completers; pub mod edge_tunnel; pub mod oidc_auth; diff --git a/crates/openshell-cli/src/run.rs b/crates/openshell-cli/src/run.rs index 7b68487ea1..f9a7035226 100644 --- a/crates/openshell-cli/src/run.rs +++ b/crates/openshell-cli/src/run.rs @@ -3,20 +3,34 @@ //! CLI command implementations. +pub use crate::commands::common::{ + PolicyGetView, parse_credential_expiry_cli_value, parse_env_pairs, parse_key_value_pairs, + parse_secret_material_env_pairs, +}; +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, + 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, +}; + use crate::policy_update::build_policy_update_plan; use crate::tls::{ TlsOptions, build_insecure_rustls_config, build_rustls_config, grpc_client, grpc_inference_client, require_tls_materials, }; use bytes::Bytes; -use chrono::DateTime; use dialoguer::{Confirm, Select, theme::ColorfulTheme}; use futures::StreamExt; use http_body_util::Full; use hyper::{Request, StatusCode}; use hyper_rustls::HttpsConnectorBuilder; use hyper_util::{client::legacy::Client, rt::TokioExecutor}; -use indicatif::{MultiProgress, ProgressBar, ProgressStyle}; +use indicatif::{ProgressBar, ProgressStyle}; use miette::{IntoDiagnostic, Result, WrapErr, miette}; use openshell_bootstrap::{ GatewayMetadata, clear_active_gateway, clear_last_sandbox_if_matches, @@ -27,11 +41,6 @@ use openshell_bootstrap::{ use openshell_bootstrap::{ GatewayMetadataSource, ListedGateway, gateway_metadata_source, list_gateways_with_source, }; -use openshell_core::progress::{ - PROGRESS_ACTIVE_DETAIL_KEY, PROGRESS_ACTIVE_STEP_KEY, PROGRESS_COMPLETE_LABEL_KEY, - PROGRESS_COMPLETE_STEP_KEY, PROGRESS_STEP_PULLING_IMAGE, PROGRESS_STEP_REQUESTING_SANDBOX, - PROGRESS_STEP_STARTING_SANDBOX, -}; use openshell_core::proto::ProviderProfileCategory; use openshell_core::proto::{ ApproveAllDraftChunksRequest, ApproveDraftChunkRequest, AttachSandboxProviderRequest, @@ -46,17 +55,16 @@ use openshell_core::proto::{ GpuResourceRequirements, HealthRequest, ImportProviderProfilesRequest, LintProviderProfilesRequest, ListProviderProfilesRequest, ListProvidersRequest, ListSandboxPoliciesRequest, ListSandboxProvidersRequest, ListSandboxesRequest, - ListServicesRequest, PlatformEvent, PolicySource, PolicyStatus, Provider, - ProviderCredentialRefreshStatus, ProviderCredentialRefreshStrategy, ProviderProfile, - ProviderProfileDiagnostic, ProviderProfileImportItem, RejectDraftChunkRequest, - ResourceRequirements, RevokeSshSessionRequest, RotateProviderCredentialRequest, Sandbox, - SandboxPhase, SandboxPolicy, SandboxSpec, SandboxTemplate, ServiceEndpointResponse, - ServiceStatus, SetInferenceRouteRequest, SettingScope, SettingValue, TcpForwardFrame, - TcpForwardInit, TcpRelayTarget, UpdateConfigRequest, UpdateProviderProfilesRequest, - UpdateProviderRequest, WatchSandboxRequest, exec_sandbox_event, setting_value, - tcp_forward_init, + ListServicesRequest, PolicySource, PolicyStatus, Provider, ProviderCredentialRefreshStatus, + ProviderCredentialRefreshStrategy, ProviderProfile, ProviderProfileDiagnostic, + ProviderProfileImportItem, RejectDraftChunkRequest, ResourceRequirements, + RevokeSshSessionRequest, RotateProviderCredentialRequest, Sandbox, SandboxPhase, SandboxPolicy, + SandboxSpec, SandboxTemplate, ServiceEndpointResponse, ServiceStatus, SetInferenceRouteRequest, + SettingScope, TcpForwardFrame, TcpForwardInit, TcpRelayTarget, UpdateConfigRequest, + UpdateProviderProfilesRequest, UpdateProviderRequest, WatchSandboxRequest, exec_sandbox_event, + setting_value, tcp_forward_init, }; -use openshell_core::settings::{self, SettingValueKind}; +use openshell_core::settings; use openshell_core::{ObjectId, ObjectName, ObjectWorkspace}; use openshell_providers::{ ProviderRegistry, ProviderTypeProfile, RealDiscoveryContext, detect_provider_from_command, @@ -82,27 +90,6 @@ pub use openshell_core::forward::{ ForwardSpec, find_forward_by_port, list_forwards, stop_forward, stop_forwards_for_sandbox, }; -#[derive(Clone, Copy, Debug, Eq, PartialEq)] -pub enum PolicyGetView { - Metadata, - Base, - Full, -} - -impl PolicyGetView { - pub fn from_flags(base: bool, full: bool) -> Self { - match (base, full) { - (true, _) => Self::Base, - (false, true) => Self::Full, - (false, false) => Self::Metadata, - } - } - - fn includes_policy(self) -> bool { - matches!(self, Self::Base | Self::Full) - } -} - #[derive(Debug, PartialEq, Eq)] enum SandboxUploadPlan { GitAware { @@ -113,419 +100,6 @@ enum SandboxUploadPlan { GitFilteredEmpty, } -/// Convert a sandbox phase integer to a human-readable string. -fn phase_name(phase: i32) -> &'static str { - match SandboxPhase::try_from(phase) { - Ok(SandboxPhase::Unspecified) => "Unspecified", - Ok(SandboxPhase::Provisioning) => "Provisioning", - Ok(SandboxPhase::Ready) => "Ready", - Ok(SandboxPhase::Error) => "Error", - Ok(SandboxPhase::Deleting) => "Deleting", - Ok(SandboxPhase::Unknown) | Err(_) => "Unknown", - } -} - -fn ready_false_condition_message( - status: Option<&openshell_core::proto::SandboxStatus>, -) -> Option { - let condition = status?.conditions.iter().find(|condition| { - condition.r#type == "Ready" && condition.status.eq_ignore_ascii_case("false") - })?; - - if condition.message.is_empty() { - if condition.reason.is_empty() { - None - } else { - Some(condition.reason.clone()) - } - } else if condition.reason.is_empty() { - Some(condition.message.clone()) - } else { - Some(format!("{}: {}", condition.reason, condition.message)) - } -} - -fn provisioning_timeout_message( - timeout_secs: u64, - resource_requirements: Option<&ResourceRequirements>, - condition_message: Option<&str>, -) -> String { - let mut message = format!("sandbox provisioning timed out after {timeout_secs}s"); - - if let Some(condition_message) = condition_message.filter(|msg| !msg.is_empty()) { - message.push_str(". Last reported status: "); - message.push_str(condition_message); - } - - if resource_requirements.is_some_and(|requirements| requirements.gpu.is_some()) { - message.push_str( - ". Hint: this may be because the available GPU is already in use by another sandbox.", - ); - } - - message -} - -/// Format milliseconds since Unix epoch as a `YYYY-MM-DD HH:MM:SS` UTC string. -fn format_epoch_ms(ms: i64) -> String { - use std::time::UNIX_EPOCH; - - let Ok(ms_u64) = u64::try_from(ms) else { - return "-".to_string(); - }; - let Ok(time) = UNIX_EPOCH - .checked_add(Duration::from_millis(ms_u64)) - .ok_or(()) - else { - return "-".to_string(); - }; - let Ok(dur) = time.duration_since(UNIX_EPOCH) else { - return "-".to_string(); - }; - - let secs = dur.as_secs(); - let days = secs / 86400; - let time_of_day = secs % 86400; - let hours = time_of_day / 3600; - let minutes = (time_of_day % 3600) / 60; - let seconds = time_of_day % 60; - - // Convert days since epoch to year-month-day using a basic civil calendar algorithm. - let (y, m, d) = civil_from_days(days); - format!("{y:04}-{m:02}-{d:02} {hours:02}:{minutes:02}:{seconds:02}") -} - -/// Convert days since 1970-01-01 to (year, month, day). -/// Algorithm from Howard Hinnant's `chrono`-compatible date library. -fn civil_from_days(days: u64) -> (i64, u64, u64) { - let z = days.cast_signed() + 719_468; - let era = if z >= 0 { z } else { z - 146_096 } / 146_097; - let doe = (z - era * 146_097).cast_unsigned(); - let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365; - let y = yoe.cast_signed() + era * 400; - let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); - let mp = (5 * doy + 2) / 153; - let d = doy - (153 * mp + 2) / 5 + 1; - let m = if mp < 10 { mp + 3 } else { mp - 9 }; - let y = if m <= 2 { y + 1 } else { y }; - (y, m, d) -} - -/// Known provisioning steps derived from Kubernetes events and sandbox lifecycle. -#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] -enum ProvisioningStep { - /// Sandbox CRD created, waiting for pod to be scheduled. - RequestingSandbox, - /// Pulling the sandbox container image. - PullingSandboxImage, - /// Container is starting up. - StartingSandbox, -} - -impl ProvisioningStep { - /// Human-readable label for a completed step. - fn completed_label(self) -> &'static str { - match self { - Self::RequestingSandbox => "Sandbox allocated", - Self::PullingSandboxImage => "Image pulled", - Self::StartingSandbox => "Sandbox ready", - } - } - - /// Human-readable label for an in-progress step (shown on the spinner). - fn active_label(self) -> &'static str { - match self { - Self::RequestingSandbox => "Requesting sandbox...", - Self::PullingSandboxImage => "Pulling image...", - Self::StartingSandbox => "Starting sandbox...", - } - } -} - -/// Live-updating display showing a provisioning step checklist with spinner. -/// -/// Completed steps are printed as static `✓ Step` lines. The current -/// in-progress step is shown on a spinner with elapsed time. -struct ProvisioningDisplay { - mp: MultiProgress, - spinner: ProgressBar, - /// Blank line below the spinner so progress doesn't sit flush against - /// the bottom of the terminal. - spacer: ProgressBar, - /// Steps that have been completed, in order. - completed_steps: Vec, - /// Progress bars for completed steps (so they can be cleared). - completed_bars: Vec, - /// The currently active step label (shown on the spinner). - active_label: String, - /// Detail text shown next to the active step (e.g. image name). - active_detail: String, - /// When the current active step started (for elapsed time). - step_start: Instant, -} - -impl ProvisioningDisplay { - fn new() -> Self { - let mp = MultiProgress::new(); - - let spinner = mp.add(ProgressBar::new_spinner()); - spinner.set_style( - ProgressStyle::with_template("{spinner:.cyan} {msg} ({elapsed})") - .unwrap_or_else(|_| ProgressStyle::default_spinner()), - ); - spinner.enable_steady_tick(Duration::from_millis(120)); - - // Always keep a blank line below the spinner so the progress area - // doesn't sit flush against the bottom of the terminal. - let spacer = mp.add(ProgressBar::new(0)); - spacer.set_style( - ProgressStyle::with_template("{msg}").unwrap_or_else(|_| ProgressStyle::default_bar()), - ); - spacer.set_message(""); - - let now = Instant::now(); - Self { - mp, - spinner, - spacer, - completed_steps: Vec::new(), - completed_bars: Vec::new(), - active_label: ProvisioningStep::RequestingSandbox - .active_label() - .to_string(), - active_detail: String::new(), - step_start: now, - } - } - - /// Record a completed provisioning step with a custom label. - fn complete_step_with_label(&mut self, step: ProvisioningStep, label: &str) { - // Don't duplicate steps we've already printed. - if self.completed_steps.contains(&step) { - return; - } - self.completed_steps.push(step); - - let elapsed = self.step_start.elapsed(); - let elapsed_str = format_elapsed(elapsed); - - // Use a progress bar instead of println so we can clear it later. - let bar = self.mp.insert_before(&self.spinner, ProgressBar::new(0)); - bar.set_style( - ProgressStyle::with_template("{msg}").unwrap_or_else(|_| ProgressStyle::default_bar()), - ); - bar.set_message(format!( - "{} {} {}", - "\u{2713}".green().bold(), - label, - elapsed_str.dimmed() - )); - bar.finish(); - self.completed_bars.push(bar); - - // Reset step timer for the next step. - self.step_start = Instant::now(); - self.spinner.reset_elapsed(); - self.active_detail.clear(); - } - - /// Set the active (in-progress) step shown on the spinner. - fn set_active(&mut self, label: &str) { - self.active_label = label.to_string(); - self.active_detail.clear(); - // Reset the spinner's elapsed time for the new step. - self.spinner.reset_elapsed(); - self.step_start = Instant::now(); - self.update_spinner(); - } - - /// Set the active step from a known provisioning step enum. - fn set_active_step(&mut self, step: ProvisioningStep) { - self.set_active(step.active_label()); - } - - /// Set detail text shown alongside the active step (e.g. image name). - fn set_active_detail(&mut self, detail: &str) { - self.active_detail = detail.to_string(); - self.update_spinner(); - } - - fn update_spinner(&self) { - let msg = if self.active_detail.is_empty() { - self.active_label.clone() - } else { - format!("{} {}", self.active_label, self.active_detail.dimmed()) - }; - self.spinner.set_message(msg); - } - - /// Finish with an error message shown on the last step line. - fn finish_error(&self, msg: &str) { - let _ = self - .mp - .println(format!("{} {}", "\u{2717}".red().bold(), msg.red())); - self.spinner.finish_and_clear(); - } - - /// Print a line above the progress bars (for static header content). - fn println(&self, msg: &str) { - let _ = self.mp.println(msg); - } - - /// Clear all progress output (spinner, spacer, and completed step lines). - fn clear(&self) { - self.spacer.finish_and_clear(); - self.spinner.finish_and_clear(); - for bar in &self.completed_bars { - bar.finish_and_clear(); - } - } -} - -/// Format a duration as a compact elapsed time string, e.g. `(3s)` or `(1m 12s)`. -fn format_elapsed(d: Duration) -> String { - let secs = d.as_secs(); - if secs < 60 { - format!("({secs}s)") - } else { - let mins = secs / 60; - let rem = secs % 60; - format!("({mins}m {rem}s)") - } -} - -/// Format a total elapsed time for non-interactive mode timestamps. -fn format_timestamp(d: Duration) -> String { - let secs = d.as_secs_f64(); - format!("[{secs:.1}s]") -} - -fn progress_step_from_metadata(value: &str) -> Option { - match value { - PROGRESS_STEP_REQUESTING_SANDBOX => Some(ProvisioningStep::RequestingSandbox), - PROGRESS_STEP_PULLING_IMAGE => Some(ProvisioningStep::PullingSandboxImage), - PROGRESS_STEP_STARTING_SANDBOX => Some(ProvisioningStep::StartingSandbox), - _ => None, - } -} - -fn noninteractive_active_label(step: ProvisioningStep) -> String { - step.active_label().trim_end_matches('.').to_string() -} - -fn handle_platform_progress_event( - event: &PlatformEvent, - display: &mut Option, - provision_start: Instant, -) -> bool { - let completed_step = event - .metadata - .get(PROGRESS_COMPLETE_STEP_KEY) - .and_then(|step| progress_step_from_metadata(step)); - let active_step = event - .metadata - .get(PROGRESS_ACTIVE_STEP_KEY) - .and_then(|step| progress_step_from_metadata(step)); - let active_detail = event - .metadata - .get(PROGRESS_ACTIVE_DETAIL_KEY) - .filter(|detail| !detail.is_empty()); - - let handled = completed_step.is_some() || active_step.is_some() || active_detail.is_some(); - if !handled { - return false; - } - - if let Some(step) = completed_step { - let label = event - .metadata - .get(PROGRESS_COMPLETE_LABEL_KEY) - .map_or_else(|| step.completed_label(), String::as_str); - if let Some(d) = display.as_mut() { - d.complete_step_with_label(step, label); - } else { - let ts = format_timestamp(provision_start.elapsed()); - println!("{} {}", ts.dimmed(), label); - } - } - - if let Some(step) = active_step - && let Some(d) = display.as_mut() - { - d.set_active_step(step); - } - - if let Some(detail) = active_detail { - if let Some(d) = display.as_mut() { - d.set_active_detail(detail); - } else { - let ts = format_timestamp(provision_start.elapsed()); - if let Some(step) = active_step { - println!( - "{} {} {}", - ts.dimmed(), - noninteractive_active_label(step), - detail - ); - } else { - println!("{} {}", ts.dimmed(), detail); - } - } - } - - true -} - -fn is_provisioning_progress_event(event: &PlatformEvent) -> bool { - if event.metadata.contains_key(PROGRESS_COMPLETE_STEP_KEY) - || event.metadata.contains_key(PROGRESS_ACTIVE_STEP_KEY) - || event.metadata.contains_key(PROGRESS_ACTIVE_DETAIL_KEY) - { - return true; - } - - event.source == "vm" - && matches!( - event.reason.as_str(), - "PullingLayer" - | "ResolvingImage" - | "AuthenticatingRegistry" - | "FetchingManifest" - | "CacheHit" - | "CacheMiss" - | "WaitingForImageCacheLock" - | "ExportingRootfs" - | "PreparingRootfs" - | "CreatingRootDisk" - | "PreparingOverlay" - | "Started" - ) -} - -fn print_sandbox_header(sandbox: &Sandbox, display: Option<&ProvisioningDisplay>) { - let lines = [ - String::new(), - format!( - "{} {}", - "Created sandbox:".cyan().bold(), - sandbox.object_name().bold() - ), - String::new(), - ]; - match display { - Some(d) => { - for line in lines { - d.println(&line); - } - } - None => { - for line in lines { - println!("{line}"); - } - } - } -} - #[derive(Debug, Clone)] struct GatewayInfoView { gateway: String, @@ -3450,63 +3024,6 @@ async fn sandbox_exec_interactive_grpc( Ok(exit_code) } -/// Print a single YAML line with dimmed keys and regular values. -fn print_yaml_line(line: &str) { - // Find leading whitespace - let trimmed = line.trim_start(); - let indent = &line[..line.len() - trimmed.len()]; - - // Handle list items - if let Some(rest) = trimmed.strip_prefix("- ") { - print!("{indent}"); - print!("{}", "- ".dimmed()); - print!("{rest}"); - println!(); - return; - } - - // Handle key: value pairs - if let Some(colon_pos) = trimmed.find(':') { - let key = &trimmed[..colon_pos]; - let after_colon = &trimmed[colon_pos + 1..]; - - print!("{indent}"); - print!("{}", key.dimmed()); - print!("{}", ":".dimmed()); - - if after_colon.is_empty() { - // Key with nested content (no value on this line) - } else if let Some(value) = after_colon.strip_prefix(' ') { - // Key: value - print!(" {value}"); - } else { - // Shouldn't happen in valid YAML, but handle it - print!("{after_colon}"); - } - println!(); - return; - } - - // Plain line (shouldn't happen often in YAML) - println!("{line}"); -} - -/// Print sandbox policy as YAML with dimmed keys. -fn print_sandbox_policy(policy: &SandboxPolicy) { - println!("{}", "Policy:".cyan().bold()); - println!(); - if let Ok(yaml_str) = openshell_policy::serialize_sandbox_policy(policy) { - // Indent the YAML output and skip the initial "---" line - for line in yaml_str.lines() { - if line == "---" { - continue; - } - print!(" "); - print_yaml_line(line); - } - } -} - /// List sandboxes. #[allow(clippy::too_many_arguments)] pub async fn sandbox_list( @@ -4228,196 +3745,6 @@ async fn auto_create_provider( Ok(()) } -pub fn parse_key_value_pairs(items: &[String], flag: &str) -> Result> { - let mut map = HashMap::new(); - - for item in items { - let Some((key, value)) = item.split_once('=') else { - return Err(miette::miette!("{flag} expects KEY=VALUE, got '{item}'")); - }; - - let key = key.trim(); - if key.is_empty() { - return Err(miette::miette!("{flag} key cannot be empty")); - } - - map.insert(key.to_string(), value.to_string()); - } - - Ok(map) -} - -pub fn parse_env_pairs(items: &[String]) -> Result> { - let map = parse_key_value_pairs(items, "--env")?; - for key in map.keys() { - if !is_valid_env_name(key) { - return Err(miette::miette!( - "--env key must match [A-Za-z_][A-Za-z0-9_]*; got '{key}'" - )); - } - if key.starts_with("OPENSHELL_") { - return Err(miette::miette!( - "--env keys starting with OPENSHELL_ are reserved; got '{key}'" - )); - } - } - Ok(map) -} - -/// Resolve `--secret-material-env KEY[=ENVVAR]` values from the CLI process -/// environment (`ENVVAR` defaults to `KEY`) so secrets never transit argv. -pub fn parse_secret_material_env_pairs(items: &[String]) -> Result> { - let mut map = HashMap::new(); - - for item in items { - let (key, env_name) = match item.split_once('=') { - Some((key, env_name)) => (key.trim(), env_name.trim()), - None => (item.trim(), item.trim()), - }; - if key.is_empty() { - return Err(miette::miette!("--secret-material-env key cannot be empty")); - } - if env_name.is_empty() { - return Err(miette::miette!( - "--secret-material-env {key} names an empty environment variable" - )); - } - - let value = std::env::var(env_name).map_err(|_| { - miette::miette!( - "--secret-material-env {key} requires local env var '{env_name}' to be set to a non-empty value" - ) - })?; - if value.trim().is_empty() { - return Err(miette::miette!( - "--secret-material-env {key} requires local env var '{env_name}' to be set to a non-empty value" - )); - } - - if map.contains_key(key) { - return Err(miette::miette!( - "--secret-material-env key '{key}' supplied more than once" - )); - } - map.insert(key.to_string(), value); - } - - Ok(map) -} - -fn is_valid_env_name(key: &str) -> bool { - let mut bytes = key.bytes(); - let Some(first) = bytes.next() else { - return false; - }; - if !(first == b'_' || first.is_ascii_alphabetic()) { - return false; - } - bytes.all(|b| b == b'_' || b.is_ascii_alphanumeric()) -} - -fn parse_credential_pairs(items: &[String]) -> Result> { - let mut map = HashMap::new(); - - for item in items { - if let Some((key, value)) = item.split_once('=') { - let key = key.trim(); - if key.is_empty() { - return Err(miette::miette!("--credential key cannot be empty")); - } - map.insert(key.to_string(), value.to_string()); - continue; - } - - let key = item.trim(); - if key.is_empty() { - return Err(miette::miette!("--credential key cannot be empty")); - } - - let value = std::env::var(key).map_err(|_| { - miette::miette!( - "--credential {key} requires local env var '{key}' to be set to a non-empty value" - ) - })?; - - if value.trim().is_empty() { - return Err(miette::miette!( - "--credential {key} requires local env var '{key}' to be set to a non-empty value" - )); - } - - map.insert(key.to_string(), value); - } - - Ok(map) -} - -pub fn parse_credential_expiry_cli_value(value: &str) -> std::result::Result { - parse_credential_expiry_value(value, None).map_err(|err| err.to_string()) -} - -fn credential_expiry_value_error(key: Option<&str>, detail: &str) -> miette::Report { - key.map_or_else( - || miette::miette!("--credential-expires-at value {detail}"), - |key| miette::miette!("--credential-expires-at value for '{key}' {detail}"), - ) -} - -fn parse_credential_expiry_value(value: &str, key: Option<&str>) -> Result { - let value = value.trim(); - if value.is_empty() { - return Err(credential_expiry_value_error(key, "cannot be empty")); - } - - if let Ok(value_ms) = value.parse::() { - if value_ms < 0 { - return Err(credential_expiry_value_error( - key, - "must be greater than or equal to 0", - )); - } - return Ok(value_ms); - } - - let parsed = DateTime::parse_from_rfc3339(value).map_err(|_| { - credential_expiry_value_error( - key, - "must be a Unix epoch millisecond timestamp or RFC3339 timestamp", - ) - })?; - let value_ms = parsed.timestamp_millis(); - if value_ms < 0 { - return Err(credential_expiry_value_error( - key, - "must be greater than or equal to 0", - )); - } - - Ok(value_ms) -} - -fn parse_credential_expiry_pairs(items: &[String]) -> Result> { - let mut map = HashMap::new(); - - for item in items { - let Some((key, value)) = item.split_once('=') else { - return Err(miette::miette!( - "--credential-expires-at expects KEY=TIMESTAMP, got '{item}'" - )); - }; - let key = key.trim(); - if key.is_empty() { - return Err(miette::miette!( - "--credential-expires-at key cannot be empty" - )); - } - let value = parse_credential_expiry_value(value, Some(key))?; - map.insert(key.to_string(), value); - } - - Ok(map) -} - pub async fn service_expose( server: &str, sandbox: &str, @@ -5903,27 +5230,6 @@ fn refresh_status_row(status: &ProviderCredentialRefreshStatus) -> String { ) } -fn format_optional_epoch_ms(ms: i64) -> String { - if ms > 0 { - format_epoch_ms(ms) - } else { - "-".to_string() - } -} - -fn truncate_status_field(value: &str, max_chars: usize) -> String { - if value.is_empty() { - return "-".to_string(); - } - let mut chars = value.chars(); - let truncated = chars.by_ref().take(max_chars).collect::(); - if chars.next().is_some() { - format!("{truncated}...") - } else { - truncated - } -} - fn provider_refresh_strategy_name(strategy: ProviderCredentialRefreshStrategy) -> &'static str { match strategy { ProviderCredentialRefreshStrategy::Static => "static", @@ -6161,17 +5467,6 @@ fn print_provider_type_row( ); } -fn truncate_display(value: &str, max_width: usize) -> String { - if value.chars().count() <= max_width { - return value.to_string(); - } - - let keep = max_width.saturating_sub(3); - let mut truncated = value.chars().take(keep).collect::(); - truncated.push_str("..."); - truncated -} - #[allow(clippy::too_many_arguments)] pub async fn provider_update( server: &str, @@ -7119,174 +6414,10 @@ pub async fn sandbox_upload( Ok(()) } -fn scrub_git_env(command: &mut Command) -> &mut Command { - for key in [ - "GIT_DIR", - "GIT_WORK_TREE", - "GIT_INDEX_FILE", - "GIT_PREFIX", - "GIT_COMMON_DIR", - "GIT_OBJECT_DIRECTORY", - "GIT_ALTERNATE_OBJECT_DIRECTORIES", - ] { - command.env_remove(key); - } - command -} - // --------------------------------------------------------------------------- // Sandbox policy commands // --------------------------------------------------------------------------- -/// Parse a duration string like "5m", "1h", "30s" into milliseconds. -fn parse_duration_to_ms(s: &str) -> Result { - let s = s.trim(); - if s.is_empty() { - return Err(miette::miette!("empty duration string")); - } - let (num_str, unit) = s.split_at(s.len() - 1); - let num: i64 = num_str - .parse() - .map_err(|_| miette::miette!("invalid duration: {s} (expected e.g. 5m, 1h, 30s)"))?; - let multiplier = match unit { - "s" => 1_000, - "m" => 60_000, - "h" => 3_600_000, - _ => { - return Err(miette::miette!( - "unknown duration unit: {unit} (use s, m, or h)" - )); - } - }; - Ok(num * multiplier) -} - -fn confirm_global_setting_takeover(key: &str, yes: bool) -> Result<()> { - if yes { - return Ok(()); - } - - if !std::io::stdin().is_terminal() || !std::io::stdout().is_terminal() { - return Err(miette::miette!( - "global setting updates require confirmation; pass --yes in non-interactive mode" - )); - } - - let proceed = Confirm::with_theme(&ColorfulTheme::default()) - .with_prompt(format!( - "Setting '{key}' globally will disable sandbox-level management for this key. Continue?" - )) - .default(false) - .interact() - .into_diagnostic()?; - - if !proceed { - return Err(miette::miette!("aborted by user")); - } - - Ok(()) -} - -fn confirm_global_setting_delete(key: &str, yes: bool) -> Result<()> { - if yes { - return Ok(()); - } - - if !std::io::stdin().is_terminal() || !std::io::stdout().is_terminal() { - return Err(miette::miette!( - "global setting deletes require confirmation; pass --yes in non-interactive mode" - )); - } - - let proceed = Confirm::with_theme(&ColorfulTheme::default()) - .with_prompt(format!( - "Deleting global setting '{key}' re-enables sandbox-level management for this key. Continue?" - )) - .default(false) - .interact() - .into_diagnostic()?; - - if !proceed { - return Err(miette::miette!("aborted by user")); - } - - Ok(()) -} - -fn parse_cli_setting_value(key: &str, raw_value: &str) -> Result { - let setting = settings::setting_for_key(key).ok_or_else(|| { - miette::miette!( - "unknown setting key '{}'. Allowed keys: {}", - key, - settings::registered_keys_csv() - ) - })?; - - let value = match setting.kind { - SettingValueKind::String => { - // Reject typos client-side so `openshell settings set ... - // proposal_approval_mode autom` errors immediately instead of - // round-tripping through the server. The server enforces the - // same check independently for non-CLI callers. - setting - .validate_string_value(raw_value) - .map_err(|allowed| { - miette::miette!( - "invalid value '{}' for key '{}'; expected one of: {}", - raw_value, - key, - allowed.join(", ") - ) - })?; - setting_value::Value::StringValue(raw_value.to_string()) - } - SettingValueKind::Int => { - let parsed = raw_value.trim().parse::().map_err(|_| { - miette::miette!( - "invalid int value '{}' for key '{}'; expected base-10 integer", - raw_value, - key - ) - })?; - setting_value::Value::IntValue(parsed) - } - SettingValueKind::Bool => { - let parsed = settings::parse_bool_like(raw_value).ok_or_else(|| { - miette::miette!( - "invalid bool value '{}' for key '{}'; expected one of: true,false,yes,no,1,0", - raw_value, - key - ) - })?; - setting_value::Value::BoolValue(parsed) - } - }; - - Ok(SettingValue { value: Some(value) }) -} - -fn format_setting_value(value: Option<&SettingValue>) -> String { - let Some(value) = value.and_then(|v| v.value.as_ref()) else { - return "".to_string(); - }; - match value { - setting_value::Value::StringValue(v) => v.clone(), - setting_value::Value::BoolValue(v) => v.to_string(), - setting_value::Value::IntValue(v) => v.to_string(), - setting_value::Value::BytesValue(v) => format!("", v.len()), - } -} - -fn short_hash(hash: &str) -> &str { - if hash.len() >= 12 { &hash[..12] } else { hash } -} - -fn print_policy_merge_warnings(warnings: &[openshell_policy::PolicyMergeWarning]) { - for warning in warnings { - eprintln!("{} {}", "!".yellow().bold(), warning); - } -} - pub async fn sandbox_policy_set_global( server: &str, policy_path: &str, @@ -8859,26 +7990,6 @@ fn format_endpoint(endpoint: &openshell_core::proto::NetworkEndpoint) -> String format!("{host_port} [{}]", tags.join(", ")) } -fn non_empty_or<'a>(value: &'a str, fallback: &'a str) -> &'a str { - if value.is_empty() { fallback } else { value } -} - -/// Format a millisecond timestamp into a readable string. -fn format_timestamp_ms(ms: i64) -> String { - if ms <= 0 { - return "-".to_string(); - } - let secs = ms / 1000; - let mins = (secs / 60) % 60; - let hours = (secs / 3600) % 24; - let days = secs / 86400; - if days > 0 { - format!("{days}d {hours:02}:{mins:02}") - } else { - format!("{hours:02}:{mins:02}") - } -} - #[cfg(test)] mod tests { use super::{ @@ -8892,13 +8003,14 @@ mod tests { inferred_provider_type, mtls_certs_exist_for_gateway, package_managed_tls_dirs, 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, - plaintext_gateway_is_remote, policy_revision_to_json, progress_step_from_metadata, + plaintext_gateway_is_remote, 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_expose_status_error, service_url_for_gateway, }; use crate::TEST_ENV_LOCK; + use crate::commands::common::progress_step_from_metadata; use hyper::StatusCode; use std::fs; use std::io::{Read, Write}; diff --git a/crates/openshell-core/src/driver_utils.rs b/crates/openshell-core/src/driver_utils.rs index e5eba760d8..8a7d177ba3 100644 --- a/crates/openshell-core/src/driver_utils.rs +++ b/crates/openshell-core/src/driver_utils.rs @@ -30,6 +30,13 @@ pub const LABEL_SANDBOX_NAMESPACE: &str = "openshell.ai/sandbox-namespace"; /// Container/pod label carrying the sandbox workspace. pub const LABEL_SANDBOX_WORKSPACE: &str = "openshell.ai/sandbox-workspace"; +/// Label selector that matches all OpenShell-managed resources which carry a +/// sandbox ID label. Used by list and watch operations to exclude foreign +/// resources from the same namespace. +pub fn openshell_sandbox_label_selector() -> String { + format!("{LABEL_MANAGED_BY}={LABEL_MANAGED_BY_VALUE},{LABEL_SANDBOX_ID}") +} + // --------------------------------------------------------------------------- /// Path to the sandbox supervisor binary inside the container image. diff --git a/crates/openshell-driver-kubernetes/src/driver.rs b/crates/openshell-driver-kubernetes/src/driver.rs index 5dba71adcc..c784f10db9 100644 --- a/crates/openshell-driver-kubernetes/src/driver.rs +++ b/crates/openshell-driver-kubernetes/src/driver.rs @@ -21,7 +21,7 @@ use kube::{Client, Error as KubeError}; use openshell_core::driver_mounts; use openshell_core::driver_utils::{ LABEL_MANAGED_BY, LABEL_MANAGED_BY_VALUE, LABEL_SANDBOX_ID, LABEL_SANDBOX_NAME, - LABEL_SANDBOX_WORKSPACE, SUPERVISOR_IMAGE_BINARY_PATH, + LABEL_SANDBOX_WORKSPACE, SUPERVISOR_IMAGE_BINARY_PATH, openshell_sandbox_label_selector, }; use openshell_core::gpu::{driver_gpu_requirements, effective_driver_gpu_count}; use openshell_core::progress::{ @@ -744,10 +744,9 @@ impl KubernetesComputeDriver { .await?; match tokio::time::timeout( KUBE_API_TIMEOUT, - agent_sandbox_api.api.list( - &ListParams::default() - .labels(&format!("{LABEL_MANAGED_BY}={LABEL_MANAGED_BY_VALUE}")), - ), + agent_sandbox_api + .api + .list(&ListParams::default().labels(&openshell_sandbox_label_selector())), ) .await { @@ -755,8 +754,16 @@ impl KubernetesComputeDriver { let mut sandboxes: Vec = list .items .into_iter() - .filter_map(|obj| sandbox_from_object(&self.config.namespace, obj).ok()) - .map(|(_, s)| s) + .filter_map(|obj| { + let name = obj.metadata.name.clone().unwrap_or_default(); + match sandbox_from_object(&self.config.namespace, obj) { + Ok((_, s)) => Some(s), + Err(err) => { + warn!(object_name = %name, error = %err, "skipping unrecognized Sandbox in list"); + None + } + } + }) .collect(); sandboxes.sort_by(|left, right| { left.name @@ -1034,8 +1041,7 @@ impl KubernetesComputeDriver { .supported_agent_sandbox_api(self.watch_client.clone()) .await?; let event_api: Api = Api::namespaced(self.watch_client.clone(), &namespace); - let watcher_config = watcher::Config::default() - .labels(&format!("{LABEL_MANAGED_BY}={LABEL_MANAGED_BY_VALUE}")); + let watcher_config = watcher::Config::default().labels(&openshell_sandbox_label_selector()); let mut sandbox_stream = watcher::watcher(agent_sandbox_api.api, watcher_config).boxed(); let mut event_stream = watcher::watcher(event_api, watcher::Config::default()).boxed(); let (tx, rx) = mpsc::channel(256); @@ -1132,7 +1138,8 @@ impl KubernetesComputeDriver { let _ = tx.send(Err(KubernetesDriverError::Message(err.to_string()))).await; break; } - } + }, + () = tx.closed() => break, } } }); diff --git a/crates/openshell-driver-vm/src/driver.rs b/crates/openshell-driver-vm/src/driver.rs index 6c203f7a9d..7af0ddc389 100644 --- a/crates/openshell-driver-vm/src/driver.rs +++ b/crates/openshell-driver-vm/src/driver.rs @@ -3538,6 +3538,8 @@ impl VmDriver { apply_registry_layer_blob(image_ref, rootfs, layer).await?; } + remove_registry_layer_staging(staging_dir).await?; + Ok(()) } @@ -3688,6 +3690,16 @@ async fn apply_registry_layer_blob( }) } +async fn remove_registry_layer_staging(staging_dir: &Path) -> Result<(), Status> { + let layers_dir = staging_dir.join("layers"); + tokio::fs::remove_dir_all(&layers_dir).await.map_err(|err| { + Status::internal(format!( + "remove registry layer staging dir '{}' failed: {err}", + layers_dir.display() + )) + }) +} + async fn download_registry_descriptor_blob_file( client: &OciClient, reference: &Reference, @@ -6615,6 +6627,29 @@ mod tests { ); } + #[tokio::test] + async fn remove_registry_layer_staging_preserves_merged_rootfs() { + let base = unique_temp_dir(); + let layers_dir = base.join("layers"); + let rootfs_dir = base.join("rootfs"); + fs::create_dir_all(&layers_dir).unwrap(); + fs::create_dir_all(&rootfs_dir).unwrap(); + fs::write(layers_dir.join("layer.blob"), b"compressed layer").unwrap(); + fs::write(rootfs_dir.join("merged.txt"), b"merged rootfs").unwrap(); + + remove_registry_layer_staging(&base) + .await + .expect("remove layer staging"); + + assert!(!layers_dir.exists()); + assert_eq!( + fs::read(rootfs_dir.join("merged.txt")).unwrap(), + b"merged rootfs" + ); + + let _ = fs::remove_dir_all(base); + } + #[test] fn sanitize_image_identity_rewrites_path_separators() { assert_eq!( diff --git a/crates/openshell-driver-vm/src/rootfs.rs b/crates/openshell-driver-vm/src/rootfs.rs index 536b359e38..c71ebe6884 100644 --- a/crates/openshell-driver-vm/src/rootfs.rs +++ b/crates/openshell-driver-vm/src/rootfs.rs @@ -461,12 +461,19 @@ fn round_up_to_mib(bytes: u64) -> u64 { bytes.div_ceil(MIB) * MIB } +enum FormatterAttempt { + Succeeded, + Failed(String), + Unavailable(String), +} + fn format_ext4_image_from_dir(source: &Path, image_path: &Path) -> Result<(), String> { - let mut last_error = None; - for tool in ["mke2fs", "mkfs.ext4"] { - for candidate in e2fs_tool_candidates(tool) { + let candidates = ["mke2fs", "mkfs.ext4"] + .into_iter() + .flat_map(e2fs_tool_candidates); + run_ext4_formatter_candidates(candidates, |candidate| { let label = candidate.display().to_string(); - let output = Command::new(&candidate) + let output = Command::new(candidate) .arg("-q") .arg("-F") .arg("-t") @@ -478,29 +485,51 @@ fn format_ext4_image_from_dir(source: &Path, image_path: &Path) -> Result<(), St .arg(image_path) .output(); match output { - Ok(output) if output.status.success() => return Ok(()), - Ok(output) => { - last_error = Some(format!( + Ok(output) if output.status.success() => FormatterAttempt::Succeeded, + Ok(output) => FormatterAttempt::Failed(format!( "{label} failed with status {}\nstdout: {}\nstderr: {}", output.status, String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stderr) - )); - } + )), Err(err) if err.kind() == std::io::ErrorKind::NotFound => { - last_error = Some(format!("{label} not found")); - } - Err(err) => { - last_error = Some(format!("run {label}: {err}")); + FormatterAttempt::Unavailable(format!("{label} not found")) } + Err(err) => FormatterAttempt::Failed(format!("run {label}: {err}")), } + }) + .map_err(|details| { + format!( + "failed to create ext4 rootfs image from {}: {details}. Install e2fsprogs (mke2fs/mkfs.ext4) and retry", + source.display() + ) + }) +} + +fn run_ext4_formatter_candidates( + candidates: impl IntoIterator, + mut run: impl FnMut(&Path) -> FormatterAttempt, +) -> Result<(), String> { + let mut failures = Vec::new(); + let mut unavailable = Vec::new(); + + for candidate in candidates { + match run(&candidate) { + FormatterAttempt::Succeeded => return Ok(()), + FormatterAttempt::Failed(error) => failures.push(error), + FormatterAttempt::Unavailable(error) => unavailable.push(error), } } - Err(format!( - "failed to create ext4 rootfs image from {}: {}. Install e2fsprogs (mke2fs/mkfs.ext4) and retry", - source.display(), - last_error.unwrap_or_else(|| "no ext4 formatter found".to_string()) - )) + + if failures.is_empty() { + Err(if unavailable.is_empty() { + "no ext4 formatter candidates configured".to_string() + } else { + unavailable.join("\n") + }) + } else { + Err(failures.join("\n")) + } } fn ensure_rootfs_image_parent_dirs(image_path: &Path, guest_path: &str) { @@ -1131,6 +1160,61 @@ mod tests { assert_eq!(debugfs_quote_argument("/tmp/bad\npath"), None); } + #[test] + fn formatter_candidates_preserve_executed_failure_over_missing_fallback() { + let candidates = vec![PathBuf::from("mke2fs"), PathBuf::from("missing")]; + + let err = run_ext4_formatter_candidates(candidates, |candidate| { + if candidate == Path::new("mke2fs") { + FormatterAttempt::Failed( + "mke2fs failed with status 1\nstdout: formatter output\nstderr: no space left" + .to_string(), + ) + } else { + FormatterAttempt::Unavailable("missing not found".to_string()) + } + }) + .expect_err("formatter should fail"); + + assert!(err.contains("mke2fs failed with status 1")); + assert!(err.contains("no space left")); + assert!(!err.contains("missing not found")); + } + + #[test] + fn formatter_candidates_report_all_missing_tools() { + let candidates = vec![PathBuf::from("mke2fs"), PathBuf::from("mkfs.ext4")]; + + let err = run_ext4_formatter_candidates(candidates, |candidate| { + FormatterAttempt::Unavailable(format!("{} not found", candidate.display())) + }) + .expect_err("formatter should be unavailable"); + + assert!(err.contains("mke2fs not found")); + assert!(err.contains("mkfs.ext4 not found")); + } + + #[test] + fn formatter_candidates_accept_successful_fallback() { + let candidates = vec![PathBuf::from("first"), PathBuf::from("second")]; + let mut attempted = Vec::new(); + + run_ext4_formatter_candidates(candidates, |candidate| { + attempted.push(candidate.to_path_buf()); + if candidate == Path::new("second") { + FormatterAttempt::Succeeded + } else { + FormatterAttempt::Failed("first failed".to_string()) + } + }) + .expect("fallback should succeed"); + + assert_eq!( + attempted, + vec![PathBuf::from("first"), PathBuf::from("second")] + ); + } + fn unique_temp_dir() -> PathBuf { static COUNTER: AtomicU64 = AtomicU64::new(0); let nanos = SystemTime::now() diff --git a/crates/openshell-tui/Cargo.toml b/crates/openshell-tui/Cargo.toml index caa2ec1ab4..c1c64d83cb 100644 --- a/crates/openshell-tui/Cargo.toml +++ b/crates/openshell-tui/Cargo.toml @@ -26,6 +26,7 @@ miette = { workspace = true } owo-colors = { workspace = true } serde = { workspace = true } url = { workspace = true } +indexmap = { workspace = true } [lints] workspace = true diff --git a/crates/openshell-tui/src/app.rs b/crates/openshell-tui/src/app.rs index 6db3ac14f2..9e3b8575b5 100644 --- a/crates/openshell-tui/src/app.rs +++ b/crates/openshell-tui/src/app.rs @@ -5,6 +5,7 @@ use std::collections::HashMap; use std::time::{Duration, Instant}; use crossterm::event::{KeyCode, KeyEvent, KeyModifiers}; +use indexmap::IndexMap; use openshell_bootstrap::GatewayMetadataSource; use openshell_core::auth::EdgeAuthInterceptor; use openshell_core::proto::open_shell_client::OpenShellClient; @@ -348,6 +349,12 @@ pub enum ProviderKeyField { EnvVarName, /// Custom env var value (generic / no-known-env-vars types only). GenericValue, + /// Browsing/deleting existing config entries (Up/Down/Ctrl+D). + ConfigList, + /// Config key name input. + ConfigKeyName, + /// Config key value input. + ConfigKeyValue, Submit, } @@ -364,6 +371,14 @@ pub struct CreateProviderForm { pub credentials: Vec<(String, String)>, /// Which credential row is focused. pub cred_cursor: usize, + /// Provider config key-value pairs (e.g. `ANTHROPIC_BASE_URL`). + pub config: IndexMap, + /// Which existing config entry is selected (for deletion). + pub config_cursor: usize, + /// Config key being entered. + pub config_key_input: String, + /// Config value being entered. + pub config_value_input: String, /// For generic / types with no known env vars: custom env var name. pub generic_env_name: String, /// For generic / types with no known env vars: custom value. @@ -411,12 +426,12 @@ pub struct ProviderDetailView { } #[derive(Clone)] -pub struct ProviderV2Entry { +pub struct ProviderListEntry { pub provider: openshell_core::proto::Provider, pub profile: Option, } -impl ProviderV2Entry { +impl ProviderListEntry { pub fn name(&self) -> &str { provider_name(&self.provider) } @@ -498,9 +513,41 @@ pub struct UpdateProviderForm { pub provider_type: String, pub credential_key: String, pub new_value: String, + pub config: IndexMap, + pub original_config: IndexMap, + pub config_key_input: String, + pub config_value_input: String, + pub config_cursor: usize, + pub deleted_keys: Vec, + pub focus: UpdateProviderField, pub status: Option, } +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum UpdateProviderField { + CredentialValue, + ConfigEntry, + ConfigKey, + ConfigValue, + Submit, +} + +// --------------------------------------------------------------------------- +// Shared config helpers +// --------------------------------------------------------------------------- + +fn flush_config_input( + config: &mut IndexMap, + key_input: &mut String, + value_input: &mut String, +) -> bool { + if !key_input.is_empty() && !value_input.is_empty() { + config.insert(std::mem::take(key_input), std::mem::take(value_input)); + return true; + } + false +} + // --------------------------------------------------------------------------- // App state // --------------------------------------------------------------------------- @@ -538,7 +585,7 @@ pub struct App { // Provider list pub providers_v2_enabled: bool, - pub provider_entries: Vec, + pub provider_entries: Vec, pub provider_names: Vec, pub provider_types: Vec, pub provider_cred_keys: Vec, @@ -2285,6 +2332,10 @@ impl App { name: String::new(), credentials: Vec::new(), cred_cursor: 0, + config: IndexMap::new(), + config_cursor: 0, + config_key_input: String::new(), + config_value_input: String::new(), generic_env_name: String::new(), generic_value: String::new(), key_field: ProviderKeyField::Name, @@ -2393,34 +2444,119 @@ impl App { form.name.clear(); form.credentials.clear(); form.cred_cursor = 0; + form.config.clear(); + form.config_cursor = 0; + form.config_key_input.clear(); + form.config_value_input.clear(); form.generic_env_name.clear(); form.generic_value.clear(); } KeyCode::Tab => { if form.is_generic { - // Name → EnvVarName → GenericValue → Submit → Name - form.key_field = match form.key_field { - ProviderKeyField::Name => ProviderKeyField::EnvVarName, - ProviderKeyField::EnvVarName => ProviderKeyField::GenericValue, - ProviderKeyField::GenericValue => ProviderKeyField::Submit, - _ => ProviderKeyField::Name, - }; + // Name → EnvVarName → GenericValue → ConfigList → ConfigKeyName → ConfigKeyValue → Submit → Name + match form.key_field { + ProviderKeyField::Name => { + form.key_field = ProviderKeyField::EnvVarName; + } + ProviderKeyField::EnvVarName => { + form.key_field = ProviderKeyField::GenericValue; + } + ProviderKeyField::GenericValue => { + if form.config.is_empty() { + form.key_field = ProviderKeyField::ConfigKeyName; + } else { + form.key_field = ProviderKeyField::ConfigList; + form.config_cursor = 0_usize; + } + } + ProviderKeyField::ConfigList => { + if form.config_cursor < form.config.len().saturating_sub(1) { + form.config_cursor += 1; + } else { + form.key_field = ProviderKeyField::ConfigKeyName; + } + } + ProviderKeyField::ConfigKeyName => { + form.key_field = ProviderKeyField::ConfigKeyValue; + } + ProviderKeyField::ConfigKeyValue => { + if flush_config_input( + &mut form.config, + &mut form.config_key_input, + &mut form.config_value_input, + ) { + form.key_field = ProviderKeyField::ConfigKeyName; + form.config_cursor = form.config.len().saturating_sub(1_usize); + } else if form.config_key_input.is_empty() + && form.config_value_input.is_empty() + { + form.key_field = ProviderKeyField::Submit; + } else { + form.status = Some( + "Both key and value required to add config entry." + .to_string(), + ); + form.key_field = ProviderKeyField::ConfigKeyName; + } + } + _ => { + form.key_field = ProviderKeyField::Name; + } + } } else { - // Name → Credential[0..N-1] → Submit → Name + // Name → Credential[0..N-1] → [ConfigList →] ConfigKeyName → ConfigKeyValue → Submit → Name match form.key_field { ProviderKeyField::Name => { if form.credentials.is_empty() { - form.key_field = ProviderKeyField::Submit; + if form.config.is_empty() { + form.key_field = ProviderKeyField::ConfigKeyName; + } else { + form.key_field = ProviderKeyField::ConfigList; + form.config_cursor = 0_usize; + } } else { form.key_field = ProviderKeyField::Credential; - form.cred_cursor = 0; + form.cred_cursor = 0_usize; } } ProviderKeyField::Credential => { if form.cred_cursor < form.credentials.len().saturating_sub(1) { form.cred_cursor += 1; + } else if !form.config.is_empty() { + form.key_field = ProviderKeyField::ConfigList; + form.config_cursor = 0_usize; + } else { + form.key_field = ProviderKeyField::ConfigKeyName; + } + } + ProviderKeyField::ConfigList => { + if form.config_cursor < form.config.len().saturating_sub(1) { + form.config_cursor += 1_usize; } else { + form.key_field = ProviderKeyField::ConfigKeyName; + } + } + ProviderKeyField::ConfigKeyName => { + form.key_field = ProviderKeyField::ConfigKeyValue; + } + ProviderKeyField::ConfigKeyValue => { + if flush_config_input( + &mut form.config, + &mut form.config_key_input, + &mut form.config_value_input, + ) { + form.key_field = ProviderKeyField::ConfigKeyName; + form.config_cursor = form.config.len().saturating_sub(1_usize); + } else if form.config_key_input.is_empty() + && form.config_value_input.is_empty() + { form.key_field = ProviderKeyField::Submit; + } else { + form.status = Some( + "Both key and value required to add config entry." + .to_string(), + ); + form.key_field = ProviderKeyField::ConfigKeyName; } } _ => { @@ -2431,12 +2567,38 @@ impl App { } KeyCode::BackTab => { if form.is_generic { - form.key_field = match form.key_field { - ProviderKeyField::EnvVarName => ProviderKeyField::Name, - ProviderKeyField::GenericValue => ProviderKeyField::EnvVarName, - ProviderKeyField::Submit => ProviderKeyField::GenericValue, - _ => ProviderKeyField::Submit, - }; + match form.key_field { + ProviderKeyField::EnvVarName => { + form.key_field = ProviderKeyField::Name; + } + ProviderKeyField::GenericValue => { + form.key_field = ProviderKeyField::EnvVarName; + } + ProviderKeyField::ConfigList => { + if form.config_cursor > 0 { + form.config_cursor -= 1_usize; + } else { + form.key_field = ProviderKeyField::GenericValue; + } + } + ProviderKeyField::ConfigKeyName => { + if form.config.is_empty() { + form.key_field = ProviderKeyField::GenericValue; + } else { + form.config_cursor = form.config.len().saturating_sub(1); + form.key_field = ProviderKeyField::ConfigList; + } + } + ProviderKeyField::ConfigKeyValue => { + form.key_field = ProviderKeyField::ConfigKeyName; + } + ProviderKeyField::Submit => { + form.key_field = ProviderKeyField::ConfigKeyValue; + } + _ => { + form.key_field = ProviderKeyField::Submit; + } + } } else { match form.key_field { ProviderKeyField::Credential => { @@ -2446,14 +2608,33 @@ impl App { form.key_field = ProviderKeyField::Name; } } - ProviderKeyField::Submit => { - if form.credentials.is_empty() { + ProviderKeyField::ConfigList => { + if form.config_cursor > 0 { + form.config_cursor -= 1; + } else if form.credentials.is_empty() { + form.key_field = ProviderKeyField::Name; + } else { + form.key_field = ProviderKeyField::Credential; + form.cred_cursor = form.credentials.len().saturating_sub(1); + } + } + ProviderKeyField::ConfigKeyName => { + if !form.config.is_empty() { + form.config_cursor = form.config.len().saturating_sub(1); + form.key_field = ProviderKeyField::ConfigList; + } else if form.credentials.is_empty() { form.key_field = ProviderKeyField::Name; } else { form.key_field = ProviderKeyField::Credential; form.cred_cursor = form.credentials.len().saturating_sub(1); } } + ProviderKeyField::ConfigKeyValue => { + form.key_field = ProviderKeyField::ConfigKeyName; + } + ProviderKeyField::Submit => { + form.key_field = ProviderKeyField::ConfigKeyValue; + } _ => { form.key_field = ProviderKeyField::Submit; } @@ -2467,6 +2648,60 @@ impl App { Self::handle_text_input(value, key); } } + ProviderKeyField::ConfigList => match key.code { + KeyCode::Up => { + form.config_cursor = form.config_cursor.saturating_sub(1); + } + KeyCode::Down if !form.config.is_empty() => { + form.config_cursor = + (form.config_cursor + 1).min(form.config.len() - 1); + } + KeyCode::Char('d') + if key.modifiers.contains(KeyModifiers::CONTROL) + && !form.config.is_empty() => + { + let key_to_remove = form + .config + .keys() + .nth(form.config_cursor) + .cloned() + .unwrap_or_default(); + form.config.shift_remove(&key_to_remove); + form.config_cursor = + form.config_cursor.min(form.config.len().saturating_sub(1)); + if form.config.is_empty() { + form.key_field = ProviderKeyField::ConfigKeyName; + } + } + _ => {} + }, + ProviderKeyField::ConfigKeyName => match key.code { + KeyCode::Enter => { + flush_config_input( + &mut form.config, + &mut form.config_key_input, + &mut form.config_value_input, + ); + } + _ => { + Self::handle_text_input(&mut form.config_key_input, key); + } + }, + ProviderKeyField::ConfigKeyValue => match key.code { + KeyCode::Enter => { + if flush_config_input( + &mut form.config, + &mut form.config_key_input, + &mut form.config_value_input, + ) { + form.key_field = ProviderKeyField::ConfigKeyName; + form.config_cursor = form.config.len().saturating_sub(1_usize); + } + } + _ => { + Self::handle_text_input(&mut form.config_value_input, key); + } + }, ProviderKeyField::EnvVarName => { Self::handle_text_input(&mut form.generic_env_name, key); } @@ -2475,6 +2710,20 @@ impl App { } ProviderKeyField::Submit => { if key.code == KeyCode::Enter { + flush_config_input( + &mut form.config, + &mut form.config_key_input, + &mut form.config_value_input, + ); + if !form.config_key_input.is_empty() + || !form.config_value_input.is_empty() + { + form.status = Some( + "Both key and value are required to add config entry." + .to_string(), + ); + return; + } // Validate and build credentials map. let mut creds = HashMap::new(); if form.is_generic { @@ -2588,6 +2837,17 @@ impl App { .get(self.provider_selected) .cloned() .unwrap_or_default(); + let existing_config = self + .provider_entries + .get(self.provider_selected) + .map(|e| { + e.provider + .config + .iter() + .map(|(k, v)| (k.clone(), v.clone())) + .collect::>() + }) + .unwrap_or_default(); // If we don't know the credential key, derive from registry. let key = if cred_key.is_empty() { @@ -2605,6 +2865,13 @@ impl App { provider_type: ptype, credential_key: key, new_value: String::new(), + config: existing_config.clone(), + original_config: existing_config, + config_key_input: String::new(), + config_value_input: String::new(), + config_cursor: 0, + deleted_keys: Vec::new(), + focus: UpdateProviderField::CredentialValue, status: None, }); } @@ -2618,18 +2885,153 @@ impl App { KeyCode::Esc => { self.update_provider_form = None; } - KeyCode::Enter => { - if form.new_value.is_empty() { - form.status = Some("Value is required.".to_string()); - return; + KeyCode::Tab => match form.focus { + UpdateProviderField::CredentialValue => { + if form.config.is_empty() { + form.focus = UpdateProviderField::ConfigKey; + } else { + form.focus = UpdateProviderField::ConfigEntry; + form.config_cursor = 0_usize; + } } - self.pending_provider_update = true; - } - KeyCode::Char(c) => form.new_value.push(c), - KeyCode::Backspace => { - form.new_value.pop(); - } - _ => {} + UpdateProviderField::ConfigEntry => { + if form.config_cursor < form.config.len().saturating_sub(1) { + form.config_cursor += 1_usize; + } else { + form.focus = UpdateProviderField::ConfigKey; + } + } + UpdateProviderField::ConfigKey => { + form.focus = UpdateProviderField::ConfigValue; + } + UpdateProviderField::ConfigValue => { + if flush_config_input( + &mut form.config, + &mut form.config_key_input, + &mut form.config_value_input, + ) { + form.focus = UpdateProviderField::ConfigKey; + form.config_cursor = form.config.len().saturating_sub(1_usize); + } else if form.config_key_input.is_empty() && form.config_value_input.is_empty() + { + form.focus = UpdateProviderField::Submit; + } else { + form.status = + Some("Both key and value required to add config entry.".to_string()); + form.focus = UpdateProviderField::ConfigKey; + } + } + UpdateProviderField::Submit => { + form.focus = UpdateProviderField::CredentialValue; + } + }, + KeyCode::BackTab => match form.focus { + UpdateProviderField::CredentialValue => { + form.focus = UpdateProviderField::Submit; + } + UpdateProviderField::ConfigEntry => { + if form.config_cursor > 0 { + form.config_cursor -= 1_usize; + } else { + form.focus = UpdateProviderField::CredentialValue; + } + } + UpdateProviderField::ConfigKey => { + if form.config.is_empty() { + form.focus = UpdateProviderField::CredentialValue; + } else { + form.focus = UpdateProviderField::ConfigEntry; + form.config_cursor = form.config.len().saturating_sub(1); + } + } + UpdateProviderField::ConfigValue => { + form.focus = UpdateProviderField::ConfigKey; + } + UpdateProviderField::Submit => { + form.focus = UpdateProviderField::ConfigValue; + } + }, + _ => match form.focus { + UpdateProviderField::CredentialValue => { + Self::handle_text_input(&mut form.new_value, key); + } + UpdateProviderField::ConfigEntry => match key.code { + KeyCode::Up => { + form.config_cursor = form.config_cursor.saturating_sub(1); + } + KeyCode::Down if !form.config.is_empty() => { + form.config_cursor = (form.config_cursor + 1).min(form.config.len() - 1); + } + KeyCode::Char('d') + if key.modifiers.contains(KeyModifiers::CONTROL) + && !form.config.is_empty() => + { + let key_to_remove = form + .config + .keys() + .nth(form.config_cursor) + .cloned() + .unwrap_or_default(); + form.deleted_keys.push(key_to_remove.clone()); + form.config.shift_remove(&key_to_remove); + form.config_cursor = + form.config_cursor.min(form.config.len().saturating_sub(1)); + if form.config.is_empty() { + form.focus = UpdateProviderField::ConfigKey; + } + } + _ => {} + }, + UpdateProviderField::ConfigKey => match key.code { + KeyCode::Enter => { + flush_config_input( + &mut form.config, + &mut form.config_key_input, + &mut form.config_value_input, + ); + } + _ => { + Self::handle_text_input(&mut form.config_key_input, key); + } + }, + UpdateProviderField::ConfigValue => match key.code { + KeyCode::Enter => { + if flush_config_input( + &mut form.config, + &mut form.config_key_input, + &mut form.config_value_input, + ) { + form.focus = UpdateProviderField::ConfigKey; + form.config_cursor = form.config.len().saturating_sub(1_usize); + } + } + _ => { + Self::handle_text_input(&mut form.config_value_input, key); + } + }, + UpdateProviderField::Submit => { + if key.code == KeyCode::Enter { + flush_config_input( + &mut form.config, + &mut form.config_key_input, + &mut form.config_value_input, + ); + if !form.config_key_input.is_empty() || !form.config_value_input.is_empty() + { + form.status = Some( + "Both key and value are required to add config entry.".to_string(), + ); + return; + } + if form.new_value.is_empty() && form.config == form.original_config { + form.status = + Some("Credential value or config keys required.".to_string()); + return; + } + self.pending_provider_update = true; + } + } + }, } } @@ -2786,7 +3188,12 @@ impl App { }, ); - let mut config_lines = provider.config.keys().cloned().collect::>(); + let mut config_lines = provider + .config + .iter() + .map(|(k, v)| format!("{k}={v}")) + .collect::>(); + config_lines.sort(); if config_lines.is_empty() { config_lines.push("".to_string()); @@ -3171,4 +3578,246 @@ mod tests { let result = workspaces.get(selected).unwrap_or(¤t); assert_eq!(*result, "default"); } + + #[test] + fn flush_config_input_inserts_when_both_present() { + let mut config = IndexMap::new(); + let mut key = "FOO".to_string(); + let mut val = "bar".to_string(); + assert!(flush_config_input(&mut config, &mut key, &mut val)); + assert_eq!(config.get("FOO"), Some(&"bar".to_string())); + assert!(key.is_empty()); + assert!(val.is_empty()); + } + + #[test] + fn flush_config_input_noop_when_key_empty() { + let mut config = IndexMap::new(); + let mut key = String::new(); + let mut val = "bar".to_string(); + assert!(!flush_config_input(&mut config, &mut key, &mut val)); + assert!(config.is_empty()); + assert_eq!(val, "bar"); + } + + #[test] + fn flush_config_input_noop_when_value_empty() { + let mut config = IndexMap::new(); + let mut key = "FOO".to_string(); + let mut val = String::new(); + assert!(!flush_config_input(&mut config, &mut key, &mut val)); + assert!(config.is_empty()); + assert_eq!(key, "FOO"); + } + + // -- config deletion tombstones ------------------------------------ + + #[test] + fn delete_config_entry_records_tombstone() { + let config = IndexMap::from([("FOO".into(), "1".into()), ("BAR".into(), "2".into())]); + + let mut form = UpdateProviderForm { + provider_name: "p".into(), + provider_type: "t".into(), + credential_key: "k".into(), + new_value: String::new(), + original_config: config.clone(), + config, + config_key_input: String::new(), + config_value_input: String::new(), + config_cursor: 0, + focus: UpdateProviderField::ConfigKey, + status: None, + deleted_keys: Vec::new(), + }; + + let key_to_remove = form.config.keys().next().cloned().unwrap(); + form.deleted_keys.push(key_to_remove.clone()); + form.config.shift_remove(&key_to_remove); + + assert!(!form.config.contains_key("FOO")); + assert!(form.deleted_keys.contains(&"FOO".to_owned())); + } + + #[test] + fn delete_last_config_entry_allows_submit() { + let form = UpdateProviderForm { + provider_name: "p".into(), + provider_type: "t".into(), + credential_key: "k".into(), + new_value: String::new(), + config: IndexMap::new(), + original_config: IndexMap::from([("FOO".into(), "1".into())]), + config_key_input: String::new(), + config_value_input: String::new(), + config_cursor: 0, + focus: UpdateProviderField::Submit, + status: None, + deleted_keys: vec!["FOO".into()], + }; + + assert!( + !(form.new_value.is_empty() && form.config.is_empty() && form.deleted_keys.is_empty()) + ); + } + + // -- cursor-relative scroll window --------------------------------- + + #[test] + fn scroll_offset_zero_when_within_window() { + let (total, cursor, window) = (4_usize, 3_usize, 6_usize); + let offset = if total > window { + cursor + .saturating_sub(window - 2_usize) + .min(total.saturating_sub(window)) + } else { + 0_usize + }; + + assert_eq!(offset, 0_usize); + } + + #[test] + fn scroll_offset_follows_cursor_past_window() { + let (total, cursor, window) = (10_usize, 8_usize, 6_usize); + let offset = if total > window { + cursor + .saturating_sub(window - 2) + .min(total.saturating_sub(window)) + } else { + 0 + }; + assert_eq!(offset, 4); + assert!(cursor >= offset && cursor < offset + window); + } + + // -- pending input flush on submit --------------------------------- + + #[test] + fn pending_config_input_flushed_on_submit() { + let mut config = IndexMap::new(); + let mut key_input = "MY_KEY".to_string(); + let mut val_input = "my_val".to_string(); + flush_config_input(&mut config, &mut key_input, &mut val_input); + assert_eq!(config.get("MY_KEY"), Some(&"my_val".to_string())); + assert!(key_input.is_empty()); + assert!(val_input.is_empty()); + } + + // -- delta-only update request ------------------------------------- + + #[test] + fn update_request_contains_only_config_delta() { + let original_config: IndexMap = IndexMap::from([ + ("A".to_string(), "1".to_string()), + ("B".to_string(), "2".to_string()), + ]); + let config: IndexMap = IndexMap::from([ + ("A".to_string(), "1".to_string()), + ("B".to_string(), "changed".to_string()), + ]); + + let delta: HashMap = config + .iter() + .filter(|(k, v)| original_config.get(*k) != Some(*v)) + .map(|(k, v)| (k.clone(), v.clone())) + .collect(); + + assert!(delta.contains_key("B"), "changed key must be in delta"); + assert!( + !delta.contains_key("A"), + "unchanged key must not be in delta" + ); + } + + #[test] + fn deleted_key_tombstoned_readded_key_not_tombstoned() { + let original_config: IndexMap = IndexMap::from([ + ("DEL".to_string(), "old".to_string()), + ("READD".to_string(), "orig".to_string()), + ("KEEP".to_string(), "keep".to_string()), + ]); + // DEL was removed, READD was deleted then re-added with new value, KEEP unchanged. + let config: IndexMap = IndexMap::from([ + ("READD".to_string(), "new".to_string()), + ("KEEP".to_string(), "keep".to_string()), + ]); + + let mut request = config + .iter() + .filter(|(k, v)| original_config.get(*k) != Some(*v)) + .map(|(k, v)| (k.clone(), v.clone())) + .collect::>(); + original_config + .keys() + .filter(|k| !config.contains_key(*k)) + .for_each(|key| { + request.insert(key.clone(), String::new()); + }); + + assert_eq!( + request.get("DEL"), + Some(&String::new()), + "DEL must be tombstoned" + ); + assert_eq!( + request.get("READD"), + Some(&"new".to_string()), + "READD must have new value, not tombstone" + ); + assert!( + !request.contains_key("KEEP"), + "KEEP unchanged must not be in delta" + ); + } + + // -- partial config input on submit -------------------------------- + + #[test] + fn submit_guard_triggers_when_key_filled_value_empty() { + let mut config = IndexMap::new(); + let mut key_input = "FOO".to_string(); + let mut val_input = String::new(); + + let flushed = flush_config_input(&mut config, &mut key_input, &mut val_input); + + assert!(!flushed, "flush must fail when value is empty"); + assert!( + !key_input.is_empty() || !val_input.is_empty(), + "submit guard must detect partial input" + ); + assert!(config.is_empty(), "config must not be modified"); + } + + #[test] + fn submit_guard_triggers_when_value_filled_key_empty() { + let mut config = IndexMap::new(); + let mut key_input = String::new(); + let mut val_input = "bar".to_string(); + + let flushed = flush_config_input(&mut config, &mut key_input, &mut val_input); + + assert!(!flushed, "flush must fail when key is empty"); + assert!( + !key_input.is_empty() || !val_input.is_empty(), + "submit guard must detect partial input" + ); + assert!(config.is_empty(), "config must not be modified"); + } + + #[test] + fn submit_guard_clear_when_both_filled() { + let mut config = IndexMap::new(); + let mut key_input = "FOO".to_string(); + let mut val_input = "bar".to_string(); + + let flushed = flush_config_input(&mut config, &mut key_input, &mut val_input); + + assert!(flushed, "flush must succeed when both fields filled"); + assert!( + key_input.is_empty() && val_input.is_empty(), + "submit guard must not trigger after successful flush" + ); + assert_eq!(config.get("FOO"), Some(&"bar".to_string())); + } } diff --git a/crates/openshell-tui/src/lib.rs b/crates/openshell-tui/src/lib.rs index 0d9d9fe613..b3937e2b90 100644 --- a/crates/openshell-tui/src/lib.rs +++ b/crates/openshell-tui/src/lib.rs @@ -1647,6 +1647,11 @@ fn spawn_create_provider(app: &App, tx: mpsc::UnboundedSender) { }; let credentials = form.discovered_credentials.clone().unwrap_or_default(); let workspace = app.current_workspace.clone(); + let config: HashMap = form + .config + .iter() + .map(|(k, v)| (k.clone(), v.clone())) + .collect(); tokio::spawn(async move { // Try with the chosen name, retry with suffix on collision. @@ -1671,7 +1676,7 @@ fn spawn_create_provider(app: &App, tx: mpsc::UnboundedSender) { }), r#type: ptype.clone(), credentials: credentials.clone(), - config: HashMap::default(), + config: config.clone(), credential_expires_at_ms: HashMap::default(), profile_workspace: workspace.clone(), }), @@ -1751,10 +1756,24 @@ fn spawn_update_provider(app: &App, tx: mpsc::UnboundedSender) { let cred_key = form.credential_key.clone(); let new_value = form.new_value.clone(); let workspace = app.selected_provider_workspace(); + let mut config: HashMap = form + .config + .iter() + .filter(|(k, v)| form.original_config.get(*k) != Some(*v)) + .map(|(k, v)| (k.clone(), v.clone())) + .collect(); + form.original_config + .keys() + .filter(|k| !form.config.contains_key(*k)) + .for_each(|key| { + config.insert(key.clone(), String::new()); + }); tokio::spawn(async move { let mut credentials = HashMap::new(); - credentials.insert(cred_key, new_value); + if !new_value.is_empty() { + credentials.insert(cred_key, new_value); + } let req = openshell_core::proto::UpdateProviderRequest { provider: Some(openshell_core::proto::Provider { @@ -1770,7 +1789,7 @@ fn spawn_update_provider(app: &App, tx: mpsc::UnboundedSender) { }), r#type: ptype, credentials, - config: HashMap::default(), + config, credential_expires_at_ms: HashMap::default(), profile_workspace: String::new(), }), @@ -2059,20 +2078,16 @@ async fn refresh_providers(app: &mut App) { }; app.provider_count = providers.len(); - app.provider_entries = if app.providers_v2_enabled { - providers - .iter() - .cloned() - .map(|provider| app::ProviderV2Entry { - profile: profiles - .get(&(provider.profile_workspace.clone(), provider.r#type.clone())) - .cloned(), - provider, - }) - .collect() - } else { - Vec::new() - }; + app.provider_entries = providers + .iter() + .cloned() + .map(|provider| app::ProviderListEntry { + profile: profiles + .get(&(provider.profile_workspace.clone(), provider.r#type.clone())) + .cloned(), + provider, + }) + .collect(); app.provider_names = providers .iter() .map(|p| app::provider_name(p).to_string()) diff --git a/crates/openshell-tui/src/ui/create_provider.rs b/crates/openshell-tui/src/ui/create_provider.rs index a0896aa46a..cb39bff341 100644 --- a/crates/openshell-tui/src/ui/create_provider.rs +++ b/crates/openshell-tui/src/ui/create_provider.rs @@ -6,10 +6,14 @@ use ratatui::layout::{Constraint, Direction, Layout, Rect}; use ratatui::text::{Line, Span}; use ratatui::widgets::{Block, Borders, Clear, Padding, Paragraph}; -use crate::app::{App, CreateProviderPhase, ProviderKeyField}; +use crate::app::{App, CreateProviderPhase, ProviderKeyField, UpdateProviderField}; + +use indexmap::IndexMap; use super::centered_rect; +const MAX_VISIBLE_CONFIG: usize = 6; + /// Draw the create provider modal overlay. pub fn draw(frame: &mut Frame<'_>, app: &App, area: Rect) { let t = &app.theme; @@ -201,14 +205,18 @@ fn draw_enter_key( let has_warning = form.warning.is_some(); let warning_rows: u16 = if has_warning { 2 } else { 0 }; // warning + spacer + #[allow(clippy::cast_possible_truncation)] + let config_rows = (form.config.len() as u16).min(MAX_VISIBLE_CONFIG as u16) + 3; #[allow(clippy::cast_possible_truncation)] let content_height = if form.is_generic { - // type(1) + name(2) + spacer(1) + env_name(2) + value(2) + spacer(1) + submit(1) + status(1) + hint(1) - warning_rows + 12 + // type(1) + name(2) + spacer(1) + env_name(2) + value(2) + spacer(1) + // + config_section + spacer(1) + submit(1) + status(1) + hint(1) + warning_rows + 1 + 2 + 1 + 2 + 2 + 1 + config_rows + 1 + 1 + 1 + 1 } else { let num_creds = form.credentials.len().clamp(1, 8) as u16; - // type(1) + name(2) + spacer(1) + creds + spacer(1) + submit(1) + status(1) + hint(1) - warning_rows + 1 + 2 + 1 + num_creds + 1 + 1 + 1 + 1 + // type(1) + name(2) + spacer(1) + creds + spacer(1) + // + config_section + spacer(1) + submit(1) + status(1) + hint(1) + warning_rows + 1 + 2 + 1 + num_creds + 1 + config_rows + 1 + 1 + 1 + 1 }; let modal_height = (content_height + 4).min(area.height.saturating_sub(2)); let popup_area = centered_rect(modal_width, modal_height, area); @@ -241,6 +249,17 @@ fn draw_enter_key( let num_creds = form.credentials.len().clamp(1, 8) as u16; constraints.push(Constraint::Length(num_creds)); // credential rows } + + constraints.push(Constraint::Length(1)); // spacer before config + constraints.push(Constraint::Length(1)); // config keys label + #[allow(clippy::cast_possible_truncation)] + let num_config = form.config.len().min(MAX_VISIBLE_CONFIG) as u16; + if num_config > 0 { + constraints.push(Constraint::Length(num_config)); // existing config entries + } + constraints.push(Constraint::Length(1)); // config key input + constraints.push(Constraint::Length(1)); // config value input + constraints.push(Constraint::Length(1)); // spacer constraints.push(Constraint::Length(1)); // submit constraints.push(Constraint::Length(1)); // status @@ -361,7 +380,68 @@ fn draw_enter_key( } idx += 1; - // Spacer. + // Spacer before config. + idx += 1; + + // Config Keys label. + let config_section_focused = matches!( + form.key_field, + ProviderKeyField::ConfigList + | ProviderKeyField::ConfigKeyName + | ProviderKeyField::ConfigKeyValue + ); + let header_style = if config_section_focused { + t.accent_bold + } else { + t.muted + }; + frame.render_widget( + Paragraph::new(Line::from(Span::styled("Config Keys:", header_style))), + chunks[idx], + ); + idx += 1; + + // Existing config entries. + if !form.config.is_empty() { + let config_entry_active = form.key_field == ProviderKeyField::ConfigList; + render_config_entries( + frame, + &form.config, + form.config_cursor, + config_entry_active, + chunks[idx], + t, + ); + idx += 1; + } + + // Config key input. + let editing_key = form.key_field == ProviderKeyField::ConfigKeyName; + render_config_input_field( + frame, + "Key", + &form.config_key_input, + editing_key, + "key", + chunks[idx], + t, + ); + idx += 1; + + // Config value input. + let editing_val = form.key_field == ProviderKeyField::ConfigKeyValue; + render_config_input_field( + frame, + "Val", + &form.config_value_input, + editing_val, + "value", + chunks[idx], + t, + ); + idx += 1; + + // Spacer before submit. idx += 1; // Submit button. @@ -383,20 +463,7 @@ fn draw_enter_key( idx += 1; // Status. - if let Some(ref status) = form.status { - let style = if status.contains("required") - || status.contains("failed") - || status.contains("Failed") - { - t.status_err - } else { - t.status_ok - }; - frame.render_widget( - Paragraph::new(Line::from(Span::styled(format!(" {status}"), style))), - chunks[idx], - ); - } + render_status(frame, form.status.as_deref(), chunks[idx], t); idx += 1; // Hint. @@ -405,6 +472,8 @@ fn draw_enter_key( Span::styled(" Next ", t.muted), Span::styled("[S-Tab]", t.key_hint), Span::styled(" Prev ", t.muted), + Span::styled("[C-d]", t.key_hint), + Span::styled(" Delete ", t.muted), Span::styled("[Enter]", t.key_hint), Span::styled(" Submit ", t.muted), Span::styled("[Esc]", t.key_hint), @@ -669,9 +738,14 @@ pub fn draw_update(frame: &mut Frame<'_>, app: &App, area: Rect) { return; }; - let modal_width = 60u16.min(area.width.saturating_sub(4)); - // name(1) + type(1) + spacer(1) + key_label(1) + value(1) + cursor_hint(1) + spacer(1) + status(1) + hint(1) - let content_height = 9; + let modal_width = 64u16.min(area.width.saturating_sub(4)); + + #[allow(clippy::cast_possible_truncation)] + let num_config = form.config.len().min(MAX_VISIBLE_CONFIG) as u16; + let config_rows = num_config + 3; // existing entries + label(1) + key input(1) + value input(1) + // name(1) + type(1) + spacer(1) + key_label(1) + value(1) + spacer(1) + // + config_section + spacer(1) + submit(1) + status(1) + hint(1) + let content_height: u16 = 1 + 1 + 1 + 1 + 1 + 1 + config_rows + 1 + 1 + 1 + 1; let modal_height = (content_height + 4).min(area.height.saturating_sub(2)); let popup_area = centered_rect(modal_width, modal_height, area); @@ -686,91 +760,184 @@ pub fn draw_update(frame: &mut Frame<'_>, app: &App, area: Rect) { let inner = block.inner(popup_area); frame.render_widget(block, popup_area); + let mut constraints = vec![ + Constraint::Length(1), // name + Constraint::Length(1), // type + Constraint::Length(1), // spacer + Constraint::Length(1), // key label + Constraint::Length(1), // value input + Constraint::Length(1), // spacer before config + Constraint::Length(1), // config keys label + ]; + if num_config > 0 { + constraints.push(Constraint::Length(num_config)); // existing config entries + } + constraints.extend([ + Constraint::Length(1), // config key input + Constraint::Length(1), // config value input + Constraint::Length(1), // spacer before submit + Constraint::Length(1), // submit + Constraint::Length(1), // status + Constraint::Length(1), // hint + Constraint::Min(0), + ]); + let chunks = Layout::default() .direction(Direction::Vertical) - .constraints([ - Constraint::Length(1), // name - Constraint::Length(1), // type - Constraint::Length(1), // spacer - Constraint::Length(1), // key label - Constraint::Length(1), // value input - Constraint::Length(1), // cursor hint - Constraint::Length(1), // spacer - Constraint::Length(1), // status - Constraint::Length(1), // hint - Constraint::Min(0), - ]) + .constraints(constraints) .split(inner); + let mut idx = 0; + + // Name. frame.render_widget( Paragraph::new(Line::from(vec![ Span::styled("Name: ", t.muted), Span::styled(&form.provider_name, t.heading), ])), - chunks[0], + chunks[idx], ); + idx += 1; + // Type. frame.render_widget( Paragraph::new(Line::from(vec![ Span::styled("Type: ", t.muted), Span::styled(&form.provider_type, t.text), ])), - chunks[1], + chunks[idx], ); + idx += 1; + + // Spacer. + idx += 1; + // Credential key label. + let cred_focused = form.focus == UpdateProviderField::CredentialValue; let key_label = if form.credential_key.is_empty() { - "New value:" + "New value" } else { &form.credential_key }; frame.render_widget( Paragraph::new(Line::from(Span::styled( format!("{key_label}:"), - t.accent_bold, + if cred_focused { t.accent_bold } else { t.muted }, ))), - chunks[3], + chunks[idx], ); + idx += 1; - // Mask the input value as dots. + // Credential value input (masked). let masked: String = "*".repeat(form.new_value.len()); - frame.render_widget( - Paragraph::new(Line::from(vec![ - Span::styled(format!(" {masked}"), t.accent), - Span::styled("_", t.accent), - ])), - chunks[4], - ); + let cred_style = if cred_focused { t.accent } else { t.muted }; + let mut cred_spans = vec![Span::styled(format!(" {masked}"), cred_style)]; + if cred_focused { + cred_spans.push(Span::styled("_", t.accent)); + } + frame.render_widget(Paragraph::new(Line::from(cred_spans)), chunks[idx]); + idx += 1; + + // Spacer before config. + idx += 1; + // Config Keys label. + let config_section_focused = matches!( + form.focus, + UpdateProviderField::ConfigEntry + | UpdateProviderField::ConfigKey + | UpdateProviderField::ConfigValue + ); + let header_style = if config_section_focused { + t.accent_bold + } else { + t.muted + }; frame.render_widget( - Paragraph::new(Line::from(Span::styled( - " Type the new credential value", - t.muted, - ))), - chunks[5], + Paragraph::new(Line::from(Span::styled("Config Keys:", header_style))), + chunks[idx], ); + idx += 1; - if let Some(ref status) = form.status { - let style = if status.contains("required") - || status.contains("failed") - || status.contains("Failed") - { - t.status_err - } else { - t.status_ok - }; - frame.render_widget( - Paragraph::new(Line::from(Span::styled(format!(" {status}"), style))), - chunks[7], + // Existing config entries. + if !form.config.is_empty() { + let config_entry_active = form.focus == UpdateProviderField::ConfigEntry; + render_config_entries( + frame, + &form.config, + form.config_cursor, + config_entry_active, + chunks[idx], + t, ); + idx += 1; } + // Config key input. + let editing_key = form.focus == UpdateProviderField::ConfigKey; + render_config_input_field( + frame, + "Key", + &form.config_key_input, + editing_key, + "key", + chunks[idx], + t, + ); + idx += 1; + + // Config value input. + let editing_val = form.focus == UpdateProviderField::ConfigValue; + render_config_input_field( + frame, + "Val", + &form.config_value_input, + editing_val, + "value", + chunks[idx], + t, + ); + idx += 1; + + // Spacer before submit. + idx += 1; + + // Submit button. + let submit_focused = form.focus == UpdateProviderField::Submit; + let submit_style = if submit_focused { + t.accent_bold + } else { + t.muted + }; + let submit_label = if submit_focused { + " > Update Provider" + } else { + " Update Provider" + }; + frame.render_widget( + Paragraph::new(Line::from(Span::styled(submit_label, submit_style))), + chunks[idx], + ); + idx += 1; + + // Status. + render_status(frame, form.status.as_deref(), chunks[idx], t); + idx += 1; + + // Hint. let hint = Line::from(vec![ + Span::styled("[Tab]", t.key_hint), + Span::styled(" Next ", t.muted), + Span::styled("[S-Tab]", t.key_hint), + Span::styled(" Prev ", t.muted), + Span::styled("[C-d]", t.key_hint), + Span::styled(" Delete ", t.muted), Span::styled("[Enter]", t.key_hint), - Span::styled(" Update ", t.muted), + Span::styled(" Submit ", t.muted), Span::styled("[Esc]", t.key_hint), Span::styled(" Cancel", t.muted), ]); - frame.render_widget(Paragraph::new(hint), chunks[8]); + frame.render_widget(Paragraph::new(hint), chunks[idx]); } // --------------------------------------------------------------------------- @@ -813,3 +980,117 @@ fn draw_secret_field( }; frame.render_widget(Paragraph::new(display), chunks[1]); } + +fn render_config_entries( + frame: &mut Frame<'_>, + config: &IndexMap, + config_cursor: usize, + config_focused: bool, + area: Rect, + theme: &crate::theme::Theme, +) { + let total = config.len(); + let scroll_offset = if total > MAX_VISIBLE_CONFIG { + config_cursor + .saturating_sub(MAX_VISIBLE_CONFIG - 2_usize) + .min(total.saturating_sub(MAX_VISIBLE_CONFIG)) + } else { + 0_usize + }; + let take_count = MAX_VISIBLE_CONFIG.min(total.saturating_sub(scroll_offset)); + let overflow_below = scroll_offset + take_count < total; + let take_count = if overflow_below { + take_count.saturating_sub(1_usize) + } else { + take_count + }; + + let mut config_lines: Vec> = config + .iter() + .enumerate() + .skip(scroll_offset) + .take(take_count) + .map(|(i, (key, value))| { + let is_selected = config_focused && i == config_cursor; + let style = if is_selected { + theme.accent_bold + } else { + theme.text + }; + Line::from(vec![ + Span::styled(format!(" {key}="), style), + Span::styled( + value.as_str(), + if is_selected { + theme.accent + } else { + theme.muted + }, + ), + ]) + }) + .collect(); + if overflow_below { + let remaining = total - scroll_offset - take_count; + config_lines.push(Line::from(Span::styled( + format!(" \u{2026}and {remaining} more"), + theme.muted, + ))); + } + frame.render_widget(Paragraph::new(config_lines), area); +} + +fn render_config_input_field( + frame: &mut Frame<'_>, + label: &str, + input: &str, + editing: bool, + placeholder: &str, + area: Rect, + theme: &crate::theme::Theme, +) { + let t = theme; + let display = if input.is_empty() { + if editing { + "_".to_string() + } else { + placeholder.to_string() + } + } else { + let mut s = input.to_string(); + if editing { + s.push('_'); + } + s + }; + frame.render_widget( + Paragraph::new(Line::from(vec![ + Span::styled(format!(" {label}: "), t.muted), + Span::styled(display, if editing { t.accent } else { t.muted }), + ])), + area, + ); +} + +fn render_status( + frame: &mut Frame<'_>, + status: Option<&str>, + area: Rect, + theme: &crate::theme::Theme, +) { + let t = theme; + if let Some(status) = status { + let style = if status.contains("required") + || status.contains("failed") + || status.contains("Failed") + { + t.status_err + } else { + t.status_ok + }; + frame.render_widget( + Paragraph::new(Line::from(Span::styled(format!(" {status}"), style))), + area, + ); + } +} diff --git a/e2e/with-kube-gateway.sh b/e2e/with-kube-gateway.sh index e4f47008c9..0a114288e8 100755 --- a/e2e/with-kube-gateway.sh +++ b/e2e/with-kube-gateway.sh @@ -115,6 +115,24 @@ helmctl() { helm --kube-context "${KUBE_CONTEXT}" "$@" } +# Return the resource reference for the gateway workload installed by the chart. +# SQLite releases use a StatefulSet; external-database releases may use a Deployment. +kube_workload_ref() { + local name="$1" + local namespace="${2:-${NAMESPACE}}" + local resource + + for resource in "statefulset/${name}" "deployment/${name}"; do + if kctl -n "${namespace}" get "${resource}" >/dev/null 2>&1; then + printf '%s\n' "${resource}" + return 0 + fi + done + + echo "ERROR: gateway workload ${name} was not found in namespace ${namespace}" >&2 + return 1 +} + deploy_postgres_fixture() { local secret_name="$1" local pg_uri @@ -320,8 +338,10 @@ run_scenario() { fi HEALTH_LOCAL_PORT="$(e2e_pick_port)" - echo "Starting kubectl port-forward sts/${RELEASE_NAME} ${HEALTH_LOCAL_PORT}:health..." - kctl -n "${NAMESPACE}" port-forward "sts/${RELEASE_NAME}" \ + local workload_ref + workload_ref="$(kube_workload_ref "${RELEASE_NAME}")" + echo "Starting kubectl port-forward ${workload_ref} ${HEALTH_LOCAL_PORT}:health..." + kctl -n "${NAMESPACE}" port-forward "${workload_ref}" \ "${HEALTH_LOCAL_PORT}:health" >"${PORTFORWARD_HEALTH_LOG}" 2>&1 & PORTFORWARD_HEALTH_PID=$! @@ -669,8 +689,9 @@ else fi HEALTH_LOCAL_PORT="$(e2e_pick_port)" - echo "Starting kubectl port-forward sts/${RELEASE_NAME} ${HEALTH_LOCAL_PORT}:health..." - kctl -n "${NAMESPACE}" port-forward "sts/${RELEASE_NAME}" \ + WORKLOAD_REF="$(kube_workload_ref "${RELEASE_NAME}")" + echo "Starting kubectl port-forward ${WORKLOAD_REF} ${HEALTH_LOCAL_PORT}:health..." + kctl -n "${NAMESPACE}" port-forward "${WORKLOAD_REF}" \ "${HEALTH_LOCAL_PORT}:health" >"${PORTFORWARD_HEALTH_LOG}" 2>&1 & PORTFORWARD_HEALTH_PID=$! diff --git a/scripts/agents/run.sh b/scripts/agents/run.sh index 4e086399db..78ef359a49 100755 --- a/scripts/agents/run.sh +++ b/scripts/agents/run.sh @@ -639,6 +639,7 @@ File.open(dockerfile_path, "a") do |file| file.puts file.puts "USER root" file.puts "COPY openshell-agent-payload/ #{payload_image_dir}/" + file.puts "RUN chmod -R a+rX #{payload_image_dir}" file.puts "RUN chmod -R a-w #{payload_image_dir}" file.puts final_user if final_user end