From 7fc37e806fac3a55c085eb6f02d3fc9aafc116e8 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 2 Nov 2026 04:42:47 -0600 Subject: [PATCH] fix(id): keep space-form --new from swallowing the subcommand (#3144) Cli::normalize_args rewrites a bare --new followed by a top-level subcommand name to --new= before clap parses, so the documented id --new serve runs serve under a random instance name instead of creating .iroh/serve/ and starting the REPL. Subcommand names come from the clap definition itself (names + aliases), so the list cannot drift. Named, equals, bare, and trailing forms are preserved; global flag values that spell a subcommand are not mistaken for one. main.rs parses through normalize_args. Tests: 3 new lib parse/normalize tests and 2 new CLI integration tests (space-form subcommand runs under an 8-hex random instance; space-form named instance). Existing --new integration tests still pass (6/6 test_new_flag*). --- pkgs/id/src/cli.rs | 181 ++++++++++++++++++++++++++++++- pkgs/id/src/main.rs | 2 +- pkgs/id/tests/cli_integration.rs | 66 +++++++++++ 3 files changed, 247 insertions(+), 2 deletions(-) diff --git a/pkgs/id/src/cli.rs b/pkgs/id/src/cli.rs index b1154bb24b..57f2dd84e1 100644 --- a/pkgs/id/src/cli.rs +++ b/pkgs/id/src/cli.rs @@ -82,10 +82,11 @@ //! - **Stdout output**: `-` as output path, `--stdout` flag, or `cat` command //! - **Renaming**: Use `source:dest` syntax for any path argument +use std::ffi::OsString; use std::net::SocketAddr; use std::path::PathBuf; -use clap::{Args, Parser, Subcommand, ValueEnum}; +use clap::{Args, CommandFactory, Parser, Subcommand, ValueEnum}; use crate::groups::Role; use crate::groups::policy::Delegation; @@ -196,6 +197,93 @@ pub struct Cli { /// Each variant represents a distinct operation mode for the `id` tool. /// Commands are organized by their primary function: storage, retrieval, /// search, or system operations. +/// Names and aliases of the top-level subcommands, taken from the clap +/// definition itself so the list can never drift from the real parser. +fn top_level_subcommand_names() -> std::collections::HashSet { + let command = Cli::command(); + let mut names = std::collections::HashSet::new(); + for sub in command.get_subcommands() { + names.insert(sub.get_name().to_owned()); + names.extend(sub.get_aliases().map(str::to_owned)); + names.extend(sub.get_visible_aliases().map(str::to_owned)); + } + names +} + +/// Rewrite raw argv so the space form of `--new` never swallows a +/// subcommand as the instance name (#3144). +/// +/// `--new` takes an optional value (`num_args = 0..=1`), so clap greedily +/// consumes the next token: the documented `id --new serve` parsed as +/// instance name `serve` with no subcommand, created `.iroh/serve/`, and +/// started the REPL. When the token after a bare `--new` is a top-level +/// subcommand name (and no subcommand has been seen yet), rewrite that +/// `--new` to `--new=` — the empty value still means "random name", and +/// the token is then parsed as the subcommand. Every other form is +/// passed through untouched: bare `--new`, `--new=`, `--new +/// `, and a trailing `--new` after the subcommand. +pub fn normalize_args(args: I) -> Vec +where + I: IntoIterator, + T: Into, +{ + // Global options that take a separate value token: the token after + // one of these is a value even when it spells a subcommand name. + const VALUE_FLAGS: [&str; 5] = [ + "--log-level", + "--data-dir", + "-d", + "--groups-log", + "--event-store", + ]; + let subcommands = top_level_subcommand_names(); + let raw: Vec = args.into_iter().map(Into::into).collect(); + let mut out: Vec = Vec::with_capacity(raw.len()); + let mut seen_subcommand = false; + let mut expect_value = false; + let mut iter = raw.into_iter().peekable(); + // The first token is the program name; copy it verbatim. + if let Some(prog) = iter.next() { + out.push(prog); + } + while let Some(arg) = iter.next() { + if expect_value { + out.push(arg); + expect_value = false; + continue; + } + let text = arg.to_str().map(str::to_owned); + if !seen_subcommand && text.as_deref() == Some("--new") { + match iter.peek().and_then(|next| next.to_str()) { + Some(next) if subcommands.contains(next) => { + out.push(OsString::from("--new=")); + } + _ => { + // The next token (if any) is the instance name; do + // not mistake it for a subcommand on the next pass. + out.push(arg); + expect_value = true; + } + } + continue; + } + out.push(arg); + if seen_subcommand { + continue; + } + match text.as_deref() { + // After `--`, every token is a positional value. + Some("--") => seen_subcommand = true, + Some(name) if VALUE_FLAGS.contains(&name) => expect_value = true, + Some(name) if !name.starts_with('-') && subcommands.contains(name) => { + seen_subcommand = true; + } + _ => {} + } + } + out +} + /// Parses a result limit (`--first` / `--last` / peek `--lines`): zero is /// rejected with a clear error instead of silently producing an empty result /// or a header-only preview (#3059). Clap names the flag in its error prefix, @@ -2387,6 +2475,97 @@ mod tests { assert!(cli.log_level.is_none()); } + /// Parse via `normalize_args` on a big-stack thread: building this + /// CLI's clap tree is deep enough to overflow the default test + /// thread stack (the #3059 parse tests below spawn a thread for the + /// same reason). + fn parse_normalized(args: &[&str]) -> Cli { + let owned: Vec = args.iter().map(OsString::from).collect(); + std::thread::Builder::new() + .stack_size(32 * 1024 * 1024) + .spawn(move || Cli::parse_from(normalize_args(owned))) + .unwrap() + .join() + .unwrap() + } + + #[test] + fn test_cli_parse_new_space_form_subcommand_not_swallowed() { + // #3144: `id --new serve` must run serve under a random instance + // name, not create an instance literally named "serve". + let cli = parse_normalized(&["id", "--new", "serve"]); + assert_eq!(cli.new.as_deref(), Some("")); + assert!(matches!(cli.command, Some(Command::Serve { .. }))); + + let cli = parse_normalized(&["id", "--new", "id"]); + assert_eq!(cli.new.as_deref(), Some("")); + assert!(matches!(cli.command, Some(Command::Id { .. }))); + + let cli = parse_normalized(&["id", "--new", "list"]); + assert_eq!(cli.new.as_deref(), Some("")); + assert!(matches!(cli.command, Some(Command::List { .. }))); + } + + #[test] + fn test_cli_parse_new_forms_preserved() { + // Named space form: the name is kept and the subcommand still runs. + let cli = parse_normalized(&["id", "--new", "my-dev", "list"]); + assert_eq!(cli.new.as_deref(), Some("my-dev")); + assert!(matches!(cli.command, Some(Command::List { .. }))); + + // Bare --new: random name, no subcommand. + let cli = parse_normalized(&["id", "--new"]); + assert_eq!(cli.new.as_deref(), Some("")); + assert!(cli.command.is_none()); + + // Equals form is passed through untouched, even when the name + // spells a subcommand. + let cli = parse_normalized(&["id", "--new=serve", "list"]); + assert_eq!(cli.new.as_deref(), Some("serve")); + assert!(matches!(cli.command, Some(Command::List { .. }))); + + // Trailing --new after the subcommand keeps working. + let cli = parse_normalized(&["id", "list", "--new"]); + assert_eq!(cli.new.as_deref(), Some("")); + assert!(matches!(cli.command, Some(Command::List { .. }))); + } + + #[test] + fn test_normalize_args_rewrites_only_the_ambiguous_form() { + // Same big-stack thread as parse_normalized: collecting the + // subcommand names builds the clap tree. + let (rewritten, flag_value) = std::thread::Builder::new() + .stack_size(32 * 1024 * 1024) + .spawn(|| { + ( + normalize_args(["id", "--new", "serve"]), + normalize_args(["id", "--log-level", "list", "--new", "id"]), + ) + }) + .unwrap() + .join() + .unwrap(); + assert_eq!( + rewritten, + vec![ + OsString::from("id"), + OsString::from("--new="), + OsString::from("serve") + ] + ); + // A global flag value that spells a subcommand is not a subcommand. + assert_eq!( + flag_value, + vec![ + OsString::from("id"), + OsString::from("--log-level"), + OsString::from("list"), + OsString::from("--new="), + OsString::from("id") + ] + ); + } + #[test] fn test_cli_parse_debug_flag() { let cli = Cli::parse_from(["id", "--debug"]); diff --git a/pkgs/id/src/main.rs b/pkgs/id/src/main.rs index e8ad09d038..8bca8e871e 100644 --- a/pkgs/id/src/main.rs +++ b/pkgs/id/src/main.rs @@ -98,7 +98,7 @@ const NOISY_MODULE_FILTERS: &[&str] = &[ #[tokio::main] async fn main() -> Result<()> { // Parse CLI first so we can use flags for logging configuration - let cli = Cli::parse(); + let cli = Cli::parse_from(id::cli::normalize_args(std::env::args_os())); // Switch to the data directory if specified. // All data paths (.iroh-store, .iroh-key, .iroh-serve.lock) are CWD-relative, diff --git a/pkgs/id/tests/cli_integration.rs b/pkgs/id/tests/cli_integration.rs index c4dfb0e586..84e9faf420 100644 --- a/pkgs/id/tests/cli_integration.rs +++ b/pkgs/id/tests/cli_integration.rs @@ -3848,6 +3848,72 @@ mod serve_tests { ); } + /// Test that space-form `--new ` does not swallow the + /// subcommand as the instance name (#3144): `id --new id` must run the + /// `id` subcommand under a randomly-named instance, like `--new= id`. + #[test] + fn test_new_flag_space_form_subcommand_not_swallowed() { + let tmp = TempDir::new().unwrap(); + + let output = run_cmd(&["--new", "id"], tmp.path()); + assert!( + output.status.success(), + "id --new id should succeed. stderr: {}", + String::from_utf8_lossy(&output.stderr) + ); + + let iroh_dir = tmp.path().join(".iroh"); + assert!(iroh_dir.exists(), ".iroh/ directory should be created"); + assert!( + !iroh_dir.join("id").exists(), + "the subcommand token must not become the instance directory" + ); + + let entries: Vec<_> = fs::read_dir(&iroh_dir) + .unwrap() + .filter_map(Result::ok) + .collect(); + assert_eq!( + entries.len(), + 1, + "Should have exactly one auto-generated subdirectory" + ); + let name = entries[0].file_name().to_string_lossy().to_string(); + assert_eq!(name.len(), 8, "Auto-generated name should be 8 chars"); + assert!( + name.chars().all(|c| c.is_ascii_hexdigit()), + "Auto-generated name should be hex: {name}" + ); + assert!( + iroh_dir.join(&name).join(".iroh-key").exists(), + "Key file should be created in instance directory" + ); + } + + /// Test that space-form `--new ` still creates the + /// named instance and runs the subcommand (#3144 preserved form). + #[test] + fn test_new_flag_space_form_named() { + let tmp = TempDir::new().unwrap(); + + let output = run_cmd(&["--new", "space-dev", "id"], tmp.path()); + assert!( + output.status.success(), + "id --new space-dev id should succeed. stderr: {}", + String::from_utf8_lossy(&output.stderr) + ); + + let instance_dir = tmp.path().join(".iroh").join("space-dev"); + assert!( + instance_dir.exists(), + ".iroh/space-dev/ should be created" + ); + assert!( + instance_dir.join(".iroh-key").exists(), + "Key file should be in named instance directory" + ); + } + /// Test that --new=NAME rejects a name that already has an existing directory. #[test] fn test_new_flag_duplicate_rejects() {